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.

Separate private hosting and retain public Kiln integrations (#157)

Matthew Kissinger7581ac469b3a
diff --git a/.agents/skills/kiln-setup-workspace/SKILL.md b/.agents/skills/kiln-setup-workspace/SKILL.md
index b1e637f9..3f6efd58 100644
--- a/.agents/skills/kiln-setup-workspace/SKILL.md
+++ b/.agents/skills/kiln-setup-workspace/SKILL.md
@@ -1,6 +1,6 @@
---
name: kiln-setup-workspace
-description: Create and verify a Kiln asset workspace for a chosen coding-agent harness. Use before authoring when the current directory is the engine repository, an empty folder, or any project without a working kiln_workspace server.
+description: Configure and verify Kiln in an existing project or a new asset workspace for the selected coding agent. Use before authoring when the project has no working kiln_workspace server or needs another agent integration; engine development stays in the engine checkout.
license: MIT
metadata:
kiln-workflow: workspace
@@ -20,13 +20,16 @@ Do not author assets inside the engine checkout. The authoring skills assume a w
When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `bin/kiln-setup-workspace.mjs` (plugin 1.0.0 used `scripts/setup-workspace.mjs`). Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.
-Choose an absolute path to an empty directory outside the checkout.
+Choose the user's existing project or an absolute path for a new workspace outside the engine installation. Check the installed initializer's `--help`: this setup version supports `--adopt`; older engines support only empty destinations. Upgrade an older installation explicitly before adopting a populated project.
```bash
-node scripts/create-workspace.mjs /absolute/empty-workspace --harness claude
+node scripts/create-workspace.mjs /absolute/project --adopt --harness claude --check
+node scripts/create-workspace.mjs /absolute/project --adopt --harness claude
```
-From an installed package, the equivalent is `kiln-init /absolute/empty-workspace --harness claude`. Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional scene-composition and trial-dispatch workflows. Use the harness already selected by the user or current host; ask only when it is unknown. The choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+From an installed package, use `kiln-init` with the same arguments. Check reports planned changes and exits 1 when changes are needed; it writes nothing. Adoption preserves existing instruction files, unrelated settings, assets and skills. Read the returned `instructions` file (`.kiln/AGENTS.md`) and `.kiln/START.md`, alongside the project's existing instructions. Conflicts stop setup before writes; do not delete or replace owner configuration to make the command pass.
+
+Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional workflows. Use the agent selected by the user or current host; ask only when it is unknown. Repeat `--adopt --harness codex` (or another supported adapter) to add that integration around the same program store. It explicitly migrates a legacy managed workspace while preserving assets. A combination whose config formats conflict is reported before changes; do not force one client's configuration into another. The plain empty-directory setup command remains compatible with older workflows.
CLI/MCP workspaces use the shared skills under `skills/`. Kiln's optional built-in Strands agent adds its workflow internally, outside that directory. Do not copy its system prompt, native workflow skill or completion protocol into another harness's skills or instructions. This applies to manual setup and plugin installs too; the engine's `src/agent/` directory is not a skill source.
@@ -37,24 +40,18 @@ CLI/MCP workspaces use the shared skills under `skills/`. Kiln's optional built-
| `cursor-agent` | `cursor-agent` |
| `opencode` | `opencode` |
| `agy` | `node agy.mjs` |
-| `codex` | `node codex.mjs` |
+| `codex` | `codex` after project trust; `node codex.mjs "TASK"` for a headless run |
| `hermes` | `node hermes.mjs` |
-**Use the launcher where the table names one, and read the workspace's own START.md over this table.** Antigravity, Codex and Hermes keep all configuration in a user-level home and read nothing from a project directory, so their workspace configuration is applied per invocation by the generated launcher. Running their bare command inside the workspace reaches no Kiln tools at all. None of the three writes outside the workspace, and none touches the user's existing configuration or authentication.
+Read `.kiln/START.md` for an adopted project, or `START.md` in a legacy workspace. Codex reads trusted project configuration from `.codex/config.toml`; its optional headless launcher supplies the same settings per invocation without relocating authentication. Antigravity and Hermes use their generated launchers for the measured workspace flow. Setup does not grant project trust or edit global credentials. Skill registration is client-specific: Claude uses `.claude/skills`, Codex uses `.agents/skills`, and OpenCode uses its configured skills path, all copied from the same maintained Kiln skills.
Hermes needs one user-level registration for the MCP server, because it has no project-scoped equivalent and no per-invocation flag for one. Its START.md prints the exact `hermes mcp add` command; offer to run it, and verify with `hermes mcp list`. Never redirect `HERMES_HOME` at the workspace: that one variable resolves the configuration path and the credential path together, so pointing it at a workspace leaves the run with no provider.
-## Start the GPU render service
-
-Setup asks for render mode `auto`: textured or metallic scenes use a compatible GPU service, starting one lazily when available. Ordinary untextured scenes with zero metalness and no advanced material extensions use CPU views, even with a GPU available. CPU views support silhouette, proportion and contact review, but cannot confirm PBR appearance. Use CLI `--render gpu` when material review is required, including roughness on nonmetallic surfaces.
-
-The renderer code is included with Kiln; its native GPU dependency is optional at the Kiln package root. For material-dependent tasks, check `node kiln.mjs service status` before starting the authoring session. If dependencies are missing or incompatible, reinstall the official Kiln package with optional dependencies enabled. npm 11 may print an `install-scripts` warning for the optional `webgpu` package; its postinstall only clears the macOS download quarantine from the prebuilt Dawn binary the package ships, so Windows and Linux need nothing and the warning is not an install failure. Read `runtime` from `.kiln/workspace.json` to identify the installation. A source checkout uses `bun install --frozen-lockfile` at that root. Setup checks dependency resolution without loading native code; ready dependencies alone do not prove the device can render.
+## Check rendering readiness
-Once dependencies are available, local CLI/MCP auto mode starts a managed service lazily for a view that needs PBR shading. Compatible clients share it; it survives the initiating session and exits after five minutes without admitted uploads, queued jobs or active renders. From the installation root, `node --import ./render-service/src/register-hooks.mjs render-service/src/server.mjs` starts a manual service that remains running while idle. It binds loopback; widening `HOST` requires `RENDER_SERVICE_TOKEN`.
+Setup selects render mode `auto`. Textured or metallic scenes use a compatible render service; plain scenes use CPU geometry views. CPU views cannot confirm PBR appearance. Check `node kiln.mjs service status` before material-dependent work and require a real `viewFidelity` result before claiming material evidence.
-`node kiln.mjs service status` reports installation, verified health and lifetime. `node kiln.mjs service start` joins a compatible service or starts a managed one the way an on-demand view does, and prints its port, renderer, pid, lifetime and build; it starts nothing when a stale, foreign or unknown listener holds the socket. After dependency repair or a cached startup failure, call `kiln_renderer({action:"reprobe"})` inside the MCP session to refresh its existing route. It neither installs dependencies nor starts a renderer; the next view starts one if needed. CLI `service reprobe` checks only its own process. Restart the session after changing Kiln, environment variables or credentials. Unknown or incompatible listeners are reported and left alone. `service stop` explicitly stops a verified local service. If no usable GPU is available, report the material-review limitation and continue on CPU views when that fits the task.
-
-A `KILN_RENDER_PORT_URL` whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) takes the local route: it starts on demand and restarts after an idle exit. For rendering on another device, configure the MCP server process's `KILN_RENDER_PORT_URL` and, when needed, `KILN_RENDER_TOKEN` through the chosen harness. CLI accepts `--render-port URL` and reads `KILN_RENDER_TOKEN`. Start a compatible Kiln renderer on that device; its wider bind requires `RENDER_SERVICE_TOKEN` unless an authenticated proxy is explicitly configured. Manage the remote service on its own device. Verify the selected route with capabilities and require an actual `viewFidelity` receipt for material evidence.
+Read [local renderer setup](references/renderer-setup.md) when dependencies are missing, a service is unavailable, or the task uses a renderer on another device. It covers dependency repair, shared-service lifetime, reprobe and authenticated remote rendering. Do not replace an unknown listener or install dependencies merely to clear a diagnostic.
## Verify the loadout before authoring
@@ -97,7 +94,9 @@ node /current/kiln/scripts/create-workspace.mjs /absolute/empty-workspace --repa
Repair rewrites generated runtime paths only. It preserves copied skills, saved revisions and assets, refuses configuration that was edited by hand, and does not upgrade the skills.
-For an existing workspace, stop its harness/MCP session and run setup from the desired installation with `--check`, then `--upgrade`. Check returns JSON and exits 1 when an update is required. Upgrade refreshes unchanged configuration, instructions and all registered skill copies while preserving assets and source stores. Conflicting local edits stop the whole upgrade before writing. Older instruction files without ownership hashes also require explicit resolution: preserve them separately, compare against a fresh temporary workspace, then move them aside or supply the current version before retrying. Reapply compatible customizations after upgrading. Do not overwrite an edited file merely to clear a conflict.
+For an existing workspace, stop its harness/MCP session and run setup from the desired installation with `--check`, then `--upgrade`. Check returns JSON and exits 1 when an update is required. Upgrade refreshes unchanged owned configuration, instructions and registered skill copies while preserving assets and source stores. Conflicting local edits stop the whole upgrade before writing. Adopted projects preserve unrelated configuration changes and leave pre-existing instruction files alone. Legacy instruction files without ownership hashes can require explicit resolution; preserve them before resolving the named conflict. Do not overwrite an edited file merely to clear a diagnostic.
+
+If adopted-project setup stops partway through writing, it attempts rollback. When it reports recovery required, preserve the project and run `kiln-init /absolute/project --recover` after confirming setup has stopped. Recovery refuses conflicting edits and retains its private snapshots outside the project. Resolve named conflicts explicitly; do not delete a lock or journal to force another setup. Recovery is for interrupted setup, not a general asset backup.
New managed launchers reject runtime/skill mismatches before serving tools; older workspaces need this explicit check first. Restart the harness/MCP session after upgrading so cached tool schemas and instructions match. `--repair` alone does not refresh copied skills or a running session. For independent model evaluations, create a fresh workspace from the candidate.
@@ -105,4 +104,4 @@ Discovery replaces the removed `kiln_list_primitives` tool; its old `name`, `nam
## What isolation means
-A separate workspace limits task context. It is not an operating-system sandbox, and it is not a git repository. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md` in the engine checkout, which covers recording inherited context and reporting trials.
+A separate workspace limits task context; an adopted project retains its existing application context and Git repository. Neither is an operating-system sandbox. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, use a fresh workspace and read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md`, which covers inherited context and reporting trials.
diff --git a/.agents/skills/kiln-setup-workspace/references/plugin-install.md b/.agents/skills/kiln-setup-workspace/references/plugin-install.md
index c3f933f7..5050fcca 100644
--- a/.agents/skills/kiln-setup-workspace/references/plugin-install.md
+++ b/.agents/skills/kiln-setup-workspace/references/plugin-install.md
@@ -17,8 +17,11 @@ installation, confirm and use that file instead. Plugin and engine versions are
independent. `runtime.json` always names the exact engine to install.
For a fresh workspace, use an absolute empty destination outside both the plugin
-and its runtime data directory. Select `claude` or `codex` from the current host
-or the user's stated choice:
+and its runtime data directory. Select the current host or the user's stated
+adapter. New bundles list the engine's supported adapters in `runtime.json`;
+older bundles without that list accept `claude` or `codex` only. The plugin itself
+is installed in Claude Code or Codex, but its helper can configure another adapter
+supported by the pinned engine:
```sh
node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --harness codex
@@ -32,11 +35,23 @@ or `$XDG_DATA_HOME/instruktlabs/kiln` on other systems, falling back to
Do not place it or the asset workspace inside a removable plugin version directory.
Read the returned workspace's `START.md`. Open Claude Code in that workspace, or
-launch Codex there with `node codex.mjs`. Accept the host's ordinary project/MCP
+launch Codex there with `codex`. The `node codex.mjs "TASK"` launcher is for
+headless execution with an explicit prompt. Accept the host's ordinary project/MCP
trust prompts, then call `kiln_discover({capabilities:true})` on `kiln_workspace`.
Compare its installation identity to `.kiln/workspace.json`; a config file alone
does not prove the server loaded. The plugin itself starts no global MCP server.
+For an existing project, use a plugin whose helper advertises `--adopt` and whose
+pinned engine supports project adoption. The published engine 1.0.0 predates this
+feature. The helper checks the engine capability and refuses unsupported adoption
+instead of silently falling back to empty-folder setup. Preview with
+`--adopt --check --harness codex`, then apply with `--adopt --harness codex`.
+Use the same path with another `--harness` to add an integration around the same
+assets. Read the returned `instructions` path and `.kiln/START.md`; existing project
+instruction files remain intact. The helper still leaves normal client trust
+prompts to the host. No manual changes to a plugin's runtime pin are needed or
+appropriate.
+
If the current workspace already has a working `kiln_workspace`, keep it. Do not
create a second server. Use its installed authoring skills, which come from its
engine version. The plugin supplies only setup, so authoring instructions are not
diff --git a/.agents/skills/kiln-setup-workspace/references/renderer-setup.md b/.agents/skills/kiln-setup-workspace/references/renderer-setup.md
new file mode 100644
index 00000000..8cdd06cd
--- /dev/null
+++ b/.agents/skills/kiln-setup-workspace/references/renderer-setup.md
@@ -0,0 +1,11 @@
+# Local renderer setup
+
+Setup asks for render mode `auto`: textured or metallic scenes use a compatible GPU service, starting one lazily when available. Ordinary untextured scenes with zero metalness and no advanced material extensions use CPU views, even with a GPU available. CPU views support silhouette, proportion and contact review, but cannot confirm PBR appearance. Use CLI `--render gpu` when material review is required, including roughness on nonmetallic surfaces.
+
+The renderer code is included with Kiln; its native GPU dependency is optional at the Kiln package root. For material-dependent tasks, check `node kiln.mjs service status` before starting the authoring session. If dependencies are missing or incompatible, reinstall the official Kiln package with optional dependencies enabled. npm 11 may print an `install-scripts` warning for the optional `webgpu` package; its postinstall only clears the macOS download quarantine from the prebuilt Dawn binary the package ships, so Windows and Linux need nothing and the warning is not an install failure. Read `runtime` from `.kiln/workspace.json` to identify the installation. A source checkout uses `bun install --frozen-lockfile` at that root. Setup checks dependency resolution without loading native code; ready dependencies alone do not prove the device can render.
+
+Once dependencies are available, local CLI/MCP auto mode starts a managed service lazily for a view that needs PBR shading. Compatible clients share it; it survives the initiating session and exits after five minutes without admitted uploads, queued jobs or active renders. From the installation root, `node --import ./render-service/src/register-hooks.mjs render-service/src/server.mjs` starts a manual service that remains running while idle. It binds loopback; widening `HOST` requires `RENDER_SERVICE_TOKEN`.
+
+`node kiln.mjs service status` reports installation, verified health and lifetime. `node kiln.mjs service start` joins a compatible service or starts a managed one the way an on-demand view does, and prints its port, renderer, pid, lifetime and build; it starts nothing when a stale, foreign or unknown listener holds the socket. After dependency repair or a cached startup failure, call `kiln_renderer({action:"reprobe"})` inside the MCP session to refresh its existing route. It neither installs dependencies nor starts a renderer; the next view starts one if needed. CLI `service reprobe` checks only its own process. Restart the session after changing Kiln, environment variables or credentials. Unknown or incompatible listeners are reported and left alone. `service stop` explicitly stops a verified local service. If no usable GPU is available, report the material-review limitation and continue on CPU views when that fits the task.
+
+A `KILN_RENDER_PORT_URL` whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) takes the local route: it starts on demand and restarts after an idle exit. For rendering on another device, configure the MCP server process's `KILN_RENDER_PORT_URL` and, when needed, `KILN_RENDER_TOKEN` through the chosen harness. CLI accepts `--render-port URL` and reads `KILN_RENDER_TOKEN`. Start a compatible Kiln renderer on that device; its wider bind requires `RENDER_SERVICE_TOKEN` unless an authenticated proxy is explicitly configured. Manage the remote service on its own device. Verify the selected route with capabilities and require an actual `viewFidelity` receipt for material evidence.
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 936632b6..9df3d3cf 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "kiln",
"description": "Build and revise 3D assets with your coding agent. Write JavaScript, inspect selected views, edit saved source revisions, and export GLB files locally.",
- "version": "1.0.0",
+ "version": "1.1.0-dev.1",
"author": {
"name": "Matthew Kissinger"
},
diff --git a/.claude/skills/kiln-setup-workspace/SKILL.md b/.claude/skills/kiln-setup-workspace/SKILL.md
index b1e637f9..3f6efd58 100644
--- a/.claude/skills/kiln-setup-workspace/SKILL.md
+++ b/.claude/skills/kiln-setup-workspace/SKILL.md
@@ -1,6 +1,6 @@
---
name: kiln-setup-workspace
-description: Create and verify a Kiln asset workspace for a chosen coding-agent harness. Use before authoring when the current directory is the engine repository, an empty folder, or any project without a working kiln_workspace server.
+description: Configure and verify Kiln in an existing project or a new asset workspace for the selected coding agent. Use before authoring when the project has no working kiln_workspace server or needs another agent integration; engine development stays in the engine checkout.
license: MIT
metadata:
kiln-workflow: workspace
@@ -20,13 +20,16 @@ Do not author assets inside the engine checkout. The authoring skills assume a w
When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `bin/kiln-setup-workspace.mjs` (plugin 1.0.0 used `scripts/setup-workspace.mjs`). Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.
-Choose an absolute path to an empty directory outside the checkout.
+Choose the user's existing project or an absolute path for a new workspace outside the engine installation. Check the installed initializer's `--help`: this setup version supports `--adopt`; older engines support only empty destinations. Upgrade an older installation explicitly before adopting a populated project.
```bash
-node scripts/create-workspace.mjs /absolute/empty-workspace --harness claude
+node scripts/create-workspace.mjs /absolute/project --adopt --harness claude --check
+node scripts/create-workspace.mjs /absolute/project --adopt --harness claude
```
-From an installed package, the equivalent is `kiln-init /absolute/empty-workspace --harness claude`. Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional scene-composition and trial-dispatch workflows. Use the harness already selected by the user or current host; ask only when it is unknown. The choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+From an installed package, use `kiln-init` with the same arguments. Check reports planned changes and exits 1 when changes are needed; it writes nothing. Adoption preserves existing instruction files, unrelated settings, assets and skills. Read the returned `instructions` file (`.kiln/AGENTS.md`) and `.kiln/START.md`, alongside the project's existing instructions. Conflicts stop setup before writes; do not delete or replace owner configuration to make the command pass.
+
+Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional workflows. Use the agent selected by the user or current host; ask only when it is unknown. Repeat `--adopt --harness codex` (or another supported adapter) to add that integration around the same program store. It explicitly migrates a legacy managed workspace while preserving assets. A combination whose config formats conflict is reported before changes; do not force one client's configuration into another. The plain empty-directory setup command remains compatible with older workflows.
CLI/MCP workspaces use the shared skills under `skills/`. Kiln's optional built-in Strands agent adds its workflow internally, outside that directory. Do not copy its system prompt, native workflow skill or completion protocol into another harness's skills or instructions. This applies to manual setup and plugin installs too; the engine's `src/agent/` directory is not a skill source.
@@ -37,24 +40,18 @@ CLI/MCP workspaces use the shared skills under `skills/`. Kiln's optional built-
| `cursor-agent` | `cursor-agent` |
| `opencode` | `opencode` |
| `agy` | `node agy.mjs` |
-| `codex` | `node codex.mjs` |
+| `codex` | `codex` after project trust; `node codex.mjs "TASK"` for a headless run |
| `hermes` | `node hermes.mjs` |
-**Use the launcher where the table names one, and read the workspace's own START.md over this table.** Antigravity, Codex and Hermes keep all configuration in a user-level home and read nothing from a project directory, so their workspace configuration is applied per invocation by the generated launcher. Running their bare command inside the workspace reaches no Kiln tools at all. None of the three writes outside the workspace, and none touches the user's existing configuration or authentication.
+Read `.kiln/START.md` for an adopted project, or `START.md` in a legacy workspace. Codex reads trusted project configuration from `.codex/config.toml`; its optional headless launcher supplies the same settings per invocation without relocating authentication. Antigravity and Hermes use their generated launchers for the measured workspace flow. Setup does not grant project trust or edit global credentials. Skill registration is client-specific: Claude uses `.claude/skills`, Codex uses `.agents/skills`, and OpenCode uses its configured skills path, all copied from the same maintained Kiln skills.
Hermes needs one user-level registration for the MCP server, because it has no project-scoped equivalent and no per-invocation flag for one. Its START.md prints the exact `hermes mcp add` command; offer to run it, and verify with `hermes mcp list`. Never redirect `HERMES_HOME` at the workspace: that one variable resolves the configuration path and the credential path together, so pointing it at a workspace leaves the run with no provider.
-## Start the GPU render service
-
-Setup asks for render mode `auto`: textured or metallic scenes use a compatible GPU service, starting one lazily when available. Ordinary untextured scenes with zero metalness and no advanced material extensions use CPU views, even with a GPU available. CPU views support silhouette, proportion and contact review, but cannot confirm PBR appearance. Use CLI `--render gpu` when material review is required, including roughness on nonmetallic surfaces.
-
-The renderer code is included with Kiln; its native GPU dependency is optional at the Kiln package root. For material-dependent tasks, check `node kiln.mjs service status` before starting the authoring session. If dependencies are missing or incompatible, reinstall the official Kiln package with optional dependencies enabled. npm 11 may print an `install-scripts` warning for the optional `webgpu` package; its postinstall only clears the macOS download quarantine from the prebuilt Dawn binary the package ships, so Windows and Linux need nothing and the warning is not an install failure. Read `runtime` from `.kiln/workspace.json` to identify the installation. A source checkout uses `bun install --frozen-lockfile` at that root. Setup checks dependency resolution without loading native code; ready dependencies alone do not prove the device can render.
+## Check rendering readiness
-Once dependencies are available, local CLI/MCP auto mode starts a managed service lazily for a view that needs PBR shading. Compatible clients share it; it survives the initiating session and exits after five minutes without admitted uploads, queued jobs or active renders. From the installation root, `node --import ./render-service/src/register-hooks.mjs render-service/src/server.mjs` starts a manual service that remains running while idle. It binds loopback; widening `HOST` requires `RENDER_SERVICE_TOKEN`.
+Setup selects render mode `auto`. Textured or metallic scenes use a compatible render service; plain scenes use CPU geometry views. CPU views cannot confirm PBR appearance. Check `node kiln.mjs service status` before material-dependent work and require a real `viewFidelity` result before claiming material evidence.
-`node kiln.mjs service status` reports installation, verified health and lifetime. `node kiln.mjs service start` joins a compatible service or starts a managed one the way an on-demand view does, and prints its port, renderer, pid, lifetime and build; it starts nothing when a stale, foreign or unknown listener holds the socket. After dependency repair or a cached startup failure, call `kiln_renderer({action:"reprobe"})` inside the MCP session to refresh its existing route. It neither installs dependencies nor starts a renderer; the next view starts one if needed. CLI `service reprobe` checks only its own process. Restart the session after changing Kiln, environment variables or credentials. Unknown or incompatible listeners are reported and left alone. `service stop` explicitly stops a verified local service. If no usable GPU is available, report the material-review limitation and continue on CPU views when that fits the task.
-
-A `KILN_RENDER_PORT_URL` whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) takes the local route: it starts on demand and restarts after an idle exit. For rendering on another device, configure the MCP server process's `KILN_RENDER_PORT_URL` and, when needed, `KILN_RENDER_TOKEN` through the chosen harness. CLI accepts `--render-port URL` and reads `KILN_RENDER_TOKEN`. Start a compatible Kiln renderer on that device; its wider bind requires `RENDER_SERVICE_TOKEN` unless an authenticated proxy is explicitly configured. Manage the remote service on its own device. Verify the selected route with capabilities and require an actual `viewFidelity` receipt for material evidence.
+Read [local renderer setup](references/renderer-setup.md) when dependencies are missing, a service is unavailable, or the task uses a renderer on another device. It covers dependency repair, shared-service lifetime, reprobe and authenticated remote rendering. Do not replace an unknown listener or install dependencies merely to clear a diagnostic.
## Verify the loadout before authoring
@@ -97,7 +94,9 @@ node /current/kiln/scripts/create-workspace.mjs /absolute/empty-workspace --repa
Repair rewrites generated runtime paths only. It preserves copied skills, saved revisions and assets, refuses configuration that was edited by hand, and does not upgrade the skills.
-For an existing workspace, stop its harness/MCP session and run setup from the desired installation with `--check`, then `--upgrade`. Check returns JSON and exits 1 when an update is required. Upgrade refreshes unchanged configuration, instructions and all registered skill copies while preserving assets and source stores. Conflicting local edits stop the whole upgrade before writing. Older instruction files without ownership hashes also require explicit resolution: preserve them separately, compare against a fresh temporary workspace, then move them aside or supply the current version before retrying. Reapply compatible customizations after upgrading. Do not overwrite an edited file merely to clear a conflict.
+For an existing workspace, stop its harness/MCP session and run setup from the desired installation with `--check`, then `--upgrade`. Check returns JSON and exits 1 when an update is required. Upgrade refreshes unchanged owned configuration, instructions and registered skill copies while preserving assets and source stores. Conflicting local edits stop the whole upgrade before writing. Adopted projects preserve unrelated configuration changes and leave pre-existing instruction files alone. Legacy instruction files without ownership hashes can require explicit resolution; preserve them before resolving the named conflict. Do not overwrite an edited file merely to clear a diagnostic.
+
+If adopted-project setup stops partway through writing, it attempts rollback. When it reports recovery required, preserve the project and run `kiln-init /absolute/project --recover` after confirming setup has stopped. Recovery refuses conflicting edits and retains its private snapshots outside the project. Resolve named conflicts explicitly; do not delete a lock or journal to force another setup. Recovery is for interrupted setup, not a general asset backup.
New managed launchers reject runtime/skill mismatches before serving tools; older workspaces need this explicit check first. Restart the harness/MCP session after upgrading so cached tool schemas and instructions match. `--repair` alone does not refresh copied skills or a running session. For independent model evaluations, create a fresh workspace from the candidate.
@@ -105,4 +104,4 @@ Discovery replaces the removed `kiln_list_primitives` tool; its old `name`, `nam
## What isolation means
-A separate workspace limits task context. It is not an operating-system sandbox, and it is not a git repository. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md` in the engine checkout, which covers recording inherited context and reporting trials.
+A separate workspace limits task context; an adopted project retains its existing application context and Git repository. Neither is an operating-system sandbox. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, use a fresh workspace and read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md`, which covers inherited context and reporting trials.
diff --git a/.claude/skills/kiln-setup-workspace/references/plugin-install.md b/.claude/skills/kiln-setup-workspace/references/plugin-install.md
index c3f933f7..5050fcca 100644
--- a/.claude/skills/kiln-setup-workspace/references/plugin-install.md
+++ b/.claude/skills/kiln-setup-workspace/references/plugin-install.md
@@ -17,8 +17,11 @@ installation, confirm and use that file instead. Plugin and engine versions are
independent. `runtime.json` always names the exact engine to install.
For a fresh workspace, use an absolute empty destination outside both the plugin
-and its runtime data directory. Select `claude` or `codex` from the current host
-or the user's stated choice:
+and its runtime data directory. Select the current host or the user's stated
+adapter. New bundles list the engine's supported adapters in `runtime.json`;
+older bundles without that list accept `claude` or `codex` only. The plugin itself
+is installed in Claude Code or Codex, but its helper can configure another adapter
+supported by the pinned engine:
```sh
node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --harness codex
@@ -32,11 +35,23 @@ or `$XDG_DATA_HOME/instruktlabs/kiln` on other systems, falling back to
Do not place it or the asset workspace inside a removable plugin version directory.
Read the returned workspace's `START.md`. Open Claude Code in that workspace, or
-launch Codex there with `node codex.mjs`. Accept the host's ordinary project/MCP
+launch Codex there with `codex`. The `node codex.mjs "TASK"` launcher is for
+headless execution with an explicit prompt. Accept the host's ordinary project/MCP
trust prompts, then call `kiln_discover({capabilities:true})` on `kiln_workspace`.
Compare its installation identity to `.kiln/workspace.json`; a config file alone
does not prove the server loaded. The plugin itself starts no global MCP server.
+For an existing project, use a plugin whose helper advertises `--adopt` and whose
+pinned engine supports project adoption. The published engine 1.0.0 predates this
+feature. The helper checks the engine capability and refuses unsupported adoption
+instead of silently falling back to empty-folder setup. Preview with
+`--adopt --check --harness codex`, then apply with `--adopt --harness codex`.
+Use the same path with another `--harness` to add an integration around the same
+assets. Read the returned `instructions` path and `.kiln/START.md`; existing project
+instruction files remain intact. The helper still leaves normal client trust
+prompts to the host. No manual changes to a plugin's runtime pin are needed or
+appropriate.
+
If the current workspace already has a working `kiln_workspace`, keep it. Do not
create a second server. Use its installed authoring skills, which come from its
engine version. The plugin supplies only setup, so authoring instructions are not
diff --git a/.claude/skills/kiln-setup-workspace/references/renderer-setup.md b/.claude/skills/kiln-setup-workspace/references/renderer-setup.md
new file mode 100644
index 00000000..8cdd06cd
--- /dev/null
+++ b/.claude/skills/kiln-setup-workspace/references/renderer-setup.md
@@ -0,0 +1,11 @@
+# Local renderer setup
+
+Setup asks for render mode `auto`: textured or metallic scenes use a compatible GPU service, starting one lazily when available. Ordinary untextured scenes with zero metalness and no advanced material extensions use CPU views, even with a GPU available. CPU views support silhouette, proportion and contact review, but cannot confirm PBR appearance. Use CLI `--render gpu` when material review is required, including roughness on nonmetallic surfaces.
+
+The renderer code is included with Kiln; its native GPU dependency is optional at the Kiln package root. For material-dependent tasks, check `node kiln.mjs service status` before starting the authoring session. If dependencies are missing or incompatible, reinstall the official Kiln package with optional dependencies enabled. npm 11 may print an `install-scripts` warning for the optional `webgpu` package; its postinstall only clears the macOS download quarantine from the prebuilt Dawn binary the package ships, so Windows and Linux need nothing and the warning is not an install failure. Read `runtime` from `.kiln/workspace.json` to identify the installation. A source checkout uses `bun install --frozen-lockfile` at that root. Setup checks dependency resolution without loading native code; ready dependencies alone do not prove the device can render.
+
+Once dependencies are available, local CLI/MCP auto mode starts a managed service lazily for a view that needs PBR shading. Compatible clients share it; it survives the initiating session and exits after five minutes without admitted uploads, queued jobs or active renders. From the installation root, `node --import ./render-service/src/register-hooks.mjs render-service/src/server.mjs` starts a manual service that remains running while idle. It binds loopback; widening `HOST` requires `RENDER_SERVICE_TOKEN`.
+
+`node kiln.mjs service status` reports installation, verified health and lifetime. `node kiln.mjs service start` joins a compatible service or starts a managed one the way an on-demand view does, and prints its port, renderer, pid, lifetime and build; it starts nothing when a stale, foreign or unknown listener holds the socket. After dependency repair or a cached startup failure, call `kiln_renderer({action:"reprobe"})` inside the MCP session to refresh its existing route. It neither installs dependencies nor starts a renderer; the next view starts one if needed. CLI `service reprobe` checks only its own process. Restart the session after changing Kiln, environment variables or credentials. Unknown or incompatible listeners are reported and left alone. `service stop` explicitly stops a verified local service. If no usable GPU is available, report the material-review limitation and continue on CPU views when that fits the task.
+
+A `KILN_RENDER_PORT_URL` whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) takes the local route: it starts on demand and restarts after an idle exit. For rendering on another device, configure the MCP server process's `KILN_RENDER_PORT_URL` and, when needed, `KILN_RENDER_TOKEN` through the chosen harness. CLI accepts `--render-port URL` and reads `KILN_RENDER_TOKEN`. Start a compatible Kiln renderer on that device; its wider bind requires `RENDER_SERVICE_TOKEN` unless an authenticated proxy is explicitly configured. Manage the remote service on its own device. Verify the selected route with capabilities and require an actual `viewFidelity` receipt for material evidence.
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index fcc90f53..4bcc8f8c 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "kiln",
- "version": "1.0.0",
+ "version": "1.1.0-dev.1",
"description": "Create, review, save, and refine procedural 3D assets with portable source and GLB collections.",
"author": {
"name": "Matthew Kissinger"
diff --git a/.github/workflows/container-image.yml b/.github/workflows/container-image.yml
deleted file mode 100644
index 2bd623a8..00000000
--- a/.github/workflows/container-image.yml
+++ /dev/null
@@ -1,203 +0,0 @@
-name: Private native image checks
-
-on:
- pull_request:
- paths:
- - .github/workflows/container-image.yml
- - .github/published-candidate.json
- - hosting/container/**
- - hosting/src/native-*.ts
- - hosting/src/render-limits.ts
- - hosting/scripts/build*.mjs
- - hosting/scripts/prepare-native-host.mjs
- - hosting/scripts/smoke-native-host.mjs
- - hosting/scripts/smoke-native-render.mjs
- - hosting/scripts/software-render-fixture.mjs
- - hosting/package*.json
- - scripts/smoke-renderer.mjs
- workflow_dispatch:
-
-permissions:
- contents: read
-
-concurrency:
- group: container-image-${{ github.ref }}
- cancel-in-progress: true
-
-jobs:
- native-host:
- name: Installed MCP host image · Linux amd64
- runs-on: ubuntu-24.04
- timeout-minutes: 15
- steps:
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- with:
- persist-credentials: false
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- with:
- node-version: 22.23.3
- - name: Install the pinned build tools
- run: |
- npm install --global [email protected] --ignore-scripts --no-fund
- npm ci --prefix hosting --ignore-scripts --no-fund
- npm run build --prefix hosting -- --native-only
- - name: Prepare the isolated image context from the exact published archive
- shell: bash
- run: |
- set -euo pipefail
- mkdir -p .cache/native-host-image
- version=$(node --input-type=module -e 'import assert from "node:assert/strict";import{readFileSync}from"node:fs";const p=JSON.parse(readFileSync(".github/published-candidate.json"));assert.equal(p.name,"@instruktlabs/kiln");assert.match(p.version,/^\d+\.\d+\.\d+(?:-rc\.\d+)?$/);process.stdout.write(p.version)')
- npm pack --ignore-scripts --registry=https://registry.npmjs.org --pack-destination .cache/native-host-image "@instruktlabs/kiln@$version"
- node hosting/scripts/prepare-native-host.mjs ".cache/native-host-image/instruktlabs-kiln-$version.tgz"
- - name: Resolve and retain the private image lock
- working-directory: .cache/native-host-image/context
- run: npm install --package-lock-only --ignore-scripts --no-fund
- - name: Build and exercise the private MCP entry without cloud access
- shell: bash
- run: |
- set -euo pipefail
- test "$(find .cache/native-host-image/context -mindepth 1 -maxdepth 1 -type f | wc -l)" -eq 8
- docker build --platform linux/amd64 --provenance=false --tag kiln-native-host:ci .cache/native-host-image/context 2>&1 | tee .cache/native-host-image/build.log
- node hosting/scripts/smoke-native-host.mjs kiln-native-host:ci
- - name: Retain native host identities and test results
- if: always()
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
- with:
- name: private-native-host-image-evidence
- path: |
- .cache/native-host-image/context-receipt.json
- .cache/native-host-image/build.log
- .cache/native-host-image/qualification/
- include-hidden-files: true
- if-no-files-found: error
- retention-days: 30
- image:
- name: Installed ${{ matrix.label }} image · Linux amd64
- strategy:
- fail-fast: false
- matrix:
- include:
- - kind: cpu
- label: CPU
- dockerfile: Dockerfile
- - kind: software
- label: software Vulkan
- dockerfile: Dockerfile.software
- runs-on: ubuntu-24.04
- timeout-minutes: 20
- steps:
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- with:
- persist-credentials: false
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- with:
- node-version: 22.23.3
- - name: Build the private software-rendering transport
- if: matrix.kind == 'software'
- run: |
- npm install --global [email protected] --ignore-scripts --no-fund
- npm ci --prefix hosting --ignore-scripts --no-fund
- npm run build --prefix hosting -- --native-only
- - name: Prepare only the reviewed minimal context
- shell: bash
- run: |
- set -euo pipefail
- mkdir -p image-context image-evidence
- node --input-type=module -e '
- import assert from "node:assert/strict";
- import {readFileSync,writeFileSync} from "node:fs";
- import {createHash} from "node:crypto";
- const p=JSON.parse(readFileSync(".github/published-candidate.json"));
- assert.equal(p.name,"@instruktlabs/kiln");
- assert.match(p.version,/^\d+\.\d+\.\d+(?:-rc\.\d+)?$/);
- assert.match(p.sha256,/^[a-f0-9]{64}$/);
- const metadataResponse=await fetch(`https://registry.npmjs.org/@instruktlabs%2fkiln/${p.version}`,{redirect:"error"});
- assert.equal(metadataResponse.status,200);const m=await metadataResponse.json();
- assert.equal(m.name,p.name);assert.equal(m.version,p.version);
- assert.equal(new URL(m.dist.tarball).origin,"https://registry.npmjs.org");
- const response=await fetch(m.dist.tarball,{redirect:"error"});assert.equal(response.status,200);
- const bytes=Buffer.from(await response.arrayBuffer());
- assert.equal(createHash("sha256").update(bytes).digest("hex"),p.sha256);
- writeFileSync("image-context/candidate.tgz",bytes);
- writeFileSync("image-context/candidate.sha256",`${p.sha256} candidate.tgz\n`);
- writeFileSync("image-evidence/candidate.json",JSON.stringify(p,null,2));
- '
- cp 'hosting/container/${{ matrix.dockerfile }}' image-context/Dockerfile
- cp hosting/container/evaluate.mjs image-context/
- if [ '${{ matrix.kind }}' = software ]; then
- cp .cache/hosted-worker/native-render.mjs hosting/container/render.mjs image-context/
- test "$(find image-context -mindepth 1 -maxdepth 1 -type f | wc -l)" -eq 6
- else
- test "$(find image-context -mindepth 1 -maxdepth 1 -type f | wc -l)" -eq 4
- fi
- - name: Build without registry publication
- id: image
- shell: bash
- run: |
- set -euo pipefail
- docker build --platform linux/amd64 --provenance=false --tag kiln-evaluation:ci image-context 2>&1 | tee image-evidence/build.log
- docker image inspect kiln-evaluation:ci > image-evidence/image.json
- docker create --name kiln-evaluation-inventory kiln-evaluation:ci
- docker cp kiln-evaluation-inventory:/opt/kiln/package-lock.json image-evidence/package-lock.json
- docker cp kiln-evaluation-inventory:/opt/kiln/os-packages.txt image-evidence/os-packages.txt
- docker cp kiln-evaluation-inventory:/opt/kiln/node-version.txt image-evidence/node-version.txt
- docker rm kiln-evaluation-inventory
- - name: Exercise the actual entry using a fixed trusted fixture
- shell: bash
- run: |
- set -euo pipefail
- # This checks image functionality, not hostile-source or Cloudflare isolation.
- docker run --rm --network none --cpus 1 --memory 6g --memory-swap 6g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges kiln-evaluation:ci \
- node --input-type=module -e 'import{createEvaluatorRequestV2}from"@instruktlabs/kiln/evaluator";process.stdout.write(createEvaluatorRequestV2({requestId:"image-fixture",code:"function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}",maxGlbBytes:2097152}).json)' \
- > image-evidence/request.json
- for attempt in 1 2; do
- docker create --interactive --name "kiln-evaluation-$attempt" --network none --cpus 1 --memory 6g --memory-swap 6g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges \
- --env KILN_RENDER=cpu kiln-evaluation:ci /usr/local/bin/node /opt/kiln/evaluate.mjs
- timeout --signal=TERM --kill-after=5s 90s docker start --attach --interactive "kiln-evaluation-$attempt" \
- < image-evidence/request.json > "image-evidence/result-$attempt.json" 2> "image-evidence/stderr-$attempt.txt"
- test "$(docker inspect "kiln-evaluation-$attempt" --format '{{.State.ExitCode}}')" -eq 0
- docker inspect "kiln-evaluation-$attempt" --format '{{json .State}}' > "image-evidence/state-$attempt.json"
- done
- docker run --rm --interactive --network none --cpus 1 --memory 6g --memory-swap 6g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges kiln-evaluation:ci \
- node --input-type=module -e 'import assert from"node:assert/strict";import{readFileSync}from"node:fs";import{createHash}from"node:crypto";import{decodeEvaluatorResultV2}from"@instruktlabs/kiln/evaluator";const r=decodeEvaluatorResultV2(readFileSync(0,"utf8"),2097152,"image-fixture");assert.equal(r.ok,true);assert.equal(r.render.glb.subarray(0,4).toString(),"glTF");console.log(JSON.stringify({status:"passed",cloudflareQualified:false,hostileSourceQualified:false,bytes:r.render.glb.length,sha256:createHash("sha256").update(r.render.glb).digest("hex")}))' \
- < image-evidence/result-1.json > image-evidence/receipt.json
- node --input-type=module -e 'import assert from"node:assert/strict";import{readFileSync}from"node:fs";const a=JSON.parse(readFileSync("image-evidence/result-1.json"));const b=JSON.parse(readFileSync("image-evidence/result-2.json"));assert.equal(a.render.glbBase64,b.render.glbBase64)'
- - name: Qualify packaged software rendering with a fixed trusted fixture
- if: matrix.kind == 'software'
- shell: bash
- run: |
- set -euo pipefail
- mkdir image-evidence/software
- # Only this disposable output directory is writable by the image's UID.
- chmod 0777 image-evidence/software
- docker create --name kiln-software-fixture --network none --cpus 2 --memory 4g --memory-swap 4g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges \
- --mount "type=bind,source=$PWD/scripts/smoke-renderer.mjs,target=/probe/smoke-renderer.mjs,readonly" \
- --mount "type=bind,source=$PWD/image-evidence/software,target=/out" \
- kiln-evaluation:ci node /probe/smoke-renderer.mjs /opt/kiln/node_modules/@instruktlabs/kiln /out software
- timeout --signal=TERM --kill-after=5s 60s docker start --attach kiln-software-fixture \
- > image-evidence/software-stdout.log 2> image-evidence/software-stderr.log
- docker inspect kiln-software-fixture --format '{{json .State}}' > image-evidence/software-state.json
- test "$(docker inspect kiln-software-fixture --format '{{.State.ExitCode}}')" -eq 0
- node --input-type=module -e 'import assert from"node:assert/strict";import{readFileSync}from"node:fs";const r=JSON.parse(readFileSync("image-evidence/software/receipt.json"));assert.equal(r.status,"passed");assert.equal(r.software,true);assert.equal(r.views.length,6)'
- - name: Qualify the one-shot render entry and private port
- if: matrix.kind == 'software'
- run: node hosting/scripts/smoke-native-render.mjs kiln-evaluation:ci
- - name: Retain image evidence without publishing the image
- if: always()
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
- with:
- name: private-evaluation-image-evidence-${{ matrix.kind }}
- path: |
- image-evidence/
- !image-evidence/software/.kiln/**
- .cache/software-render-entry/qualification/
- include-hidden-files: true
- if-no-files-found: error
- retention-days: 30
- - name: Remove only this job's test containers
- if: always()
- shell: bash
- run: |
- for name in kiln-evaluation-inventory kiln-evaluation-1 kiln-evaluation-2 kiln-software-fixture; do
- if docker container inspect "$name" >/dev/null 2>&1; then docker rm --force "$name"; fi
- done
diff --git a/.github/workflows/hosted-gateway.yml b/.github/workflows/hosted-gateway.yml
deleted file mode 100644
index 7a95002a..00000000
--- a/.github/workflows/hosted-gateway.yml
+++ /dev/null
@@ -1,74 +0,0 @@
-name: Hosted gateway checks
-
-on:
- pull_request:
- branches: [main]
- paths:
- - 'hosting/**'
- - 'src/**'
- - 'scripts/build-runtime.mjs'
- - 'scripts/build-sdk.mjs'
- - 'package.json'
- - 'bun.lock'
- - '.github/workflows/hosted-gateway.yml'
- push:
- branches: [main]
- paths:
- - 'hosting/**'
- - 'src/**'
- - 'scripts/build-runtime.mjs'
- - 'scripts/build-sdk.mjs'
- - 'package.json'
- - 'bun.lock'
- - '.github/workflows/hosted-gateway.yml'
- workflow_dispatch:
-
-permissions:
- contents: read
-
-concurrency:
- group: hosted-gateway-${{ github.ref }}
- cancel-in-progress: true
-
-jobs:
- gateway:
- name: OAuth, storage and engine adapters · ${{ matrix.os }}
- strategy:
- fail-fast: false
- matrix:
- os: [ubuntu-22.04, windows-2022]
- runs-on: ${{ matrix.os }}
- timeout-minutes: 10
- env:
- KILN_RENDER: cpu
- defaults:
- run:
- working-directory: hosting
- steps:
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- with:
- persist-credentials: false
- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- with:
- node-version: 22.23.3
- - run: npm install --global [email protected]
- - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
- with:
- bun-version: 1.4.2
- - name: Install the engine's pinned dependencies
- working-directory: .
- run: bun install --frozen-lockfile
- - name: Rebuild the actual Node engine used by the integration tests
- working-directory: .
- run: node scripts/build-runtime.mjs all
- - run: npm ci --ignore-scripts --no-audit --no-fund
- - run: npm run typecheck
- - run: npm test
- - run: npm run build
- - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
- with:
- name: hosted-gateway-${{ matrix.os }}
- path: .cache/hosted-worker/
- include-hidden-files: true
- if-no-files-found: error
- retention-days: 14
diff --git a/.github/workflows/hosting-probe.yml b/.github/workflows/hosting-probe.yml
index 9654d6d7..82a4aca5 100644
--- a/.github/workflows/hosting-probe.yml
+++ b/.github/workflows/hosting-probe.yml
@@ -20,11 +20,138 @@ concurrency:
group: hosting-probe-${{ github.ref }}
cancel-in-progress: true
-# This conditional provider-neutral probe is separate from the required package
-# matrix. A successful Docker run would still require qualification on Cloudflare.
+# This provider-neutral probe is separate from the package matrix. Both positive
+# VM evaluation and restricted-host refusal must pass. Neither qualifies Cloudflare.
jobs:
+ nested-evaluator:
+ name: Installed nested evaluator · unprivileged Linux VM
+ runs-on: ubuntu-22.04
+ timeout-minutes: 20
+ env:
+ KILN_RENDER: cpu
+ CANDIDATE_COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.4.2
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: 22.23.3
+ - run: npm install --global [email protected]
+ - run: bun install --frozen-lockfile
+ - run: bun run build:runtime
+
+ - name: Prepare exact archive and non-setuid Bubblewrap
+ shell: bash
+ run: |
+ set -euo pipefail
+ mkdir -p .cache/nested-evaluator/context .cache/nested-evaluator/receipts
+ context="$PWD/.cache/nested-evaluator/context"
+ receipts="$PWD/.cache/nested-evaluator/receipts"
+ npm pack --ignore-scripts --pack-destination "$context"
+ set -- "$context"/*.tgz
+ test "$#" -eq 1 && test -f "$1"
+ mv "$1" "$context/candidate.tgz"
+ (cd "$context" && sha256sum candidate.tgz > candidate.sha256)
+ cp "$context/candidate.sha256" "$receipts/"
+ # Build v0.12.0 from its immutable upstream commit. Runner sudo is used
+ # only to install build prerequisites/binaries, never to run evaluation.
+ sudo apt-get update
+ sudo apt-get install -y --no-install-recommends meson ninja-build libcap-dev libcap2-bin pkg-config
+ curl --fail --location --proto '=https' --tlsv1.2 \
+ https://codeload.github.com/containers/bubblewrap/tar.gz/2a76602a8c71f36c1527cf9fc3417d9149822e0c \
+ --output "$context/bubblewrap.tar.gz"
+ printf '%s %s\n' d1383cdc691a335f531564c6d0a1e06165932a4bb9e62a42f952eb0286995431 \
+ "$context/bubblewrap.tar.gz" | sha256sum --check
+ mkdir "$context/bubblewrap"
+ tar -xzf "$context/bubblewrap.tar.gz" --strip-components=1 -C "$context/bubblewrap"
+ meson setup "$context/bubblewrap-build" "$context/bubblewrap" \
+ -Dman=disabled -Dtests=false -Dbash_completion=disabled -Dzsh_completion=disabled
+ meson compile -C "$context/bubblewrap-build"
+ test ! -e /usr/local/bin/kiln-probe-bwrap
+ test ! -e /usr/local/bin/kiln-probe-node
+ sudo install -m 0755 "$context/bubblewrap-build/bwrap" /usr/local/bin/kiln-probe-bwrap
+ sudo install -m 0755 "$(command -v node)" /usr/local/bin/kiln-probe-node
+ test ! -u /usr/local/bin/kiln-probe-bwrap
+ test ! -g /usr/local/bin/kiln-probe-bwrap
+ test -z "$(getcap /usr/local/bin/kiln-probe-bwrap /usr/local/bin/kiln-probe-node)"
+ /usr/local/bin/kiln-probe-bwrap --version > "$receipts/bwrap-version.txt"
+ /usr/local/bin/kiln-probe-node --version > "$receipts/node-version.txt"
+ sha256sum /usr/local/bin/kiln-probe-bwrap /usr/local/bin/kiln-probe-node > "$receipts/executables.sha256"
+ dpkg-query -W > "$receipts/os-packages.txt"
+ uname -a > "$receipts/kernel.txt"
+ # Do not change sysctl, AppArmor, seccomp, capabilities or runner policy.
+ node --input-type=module -e '
+ import {readFileSync, writeFileSync} from "node:fs";
+ const policy = {};
+ for (const path of ["/proc/sys/user/max_user_namespaces", "/proc/sys/kernel/unprivileged_userns_clone",
+ "/proc/sys/kernel/apparmor_restrict_unprivileged_userns"]) {
+ try { policy[path] = readFileSync(path, "utf8").slice(0, 4096); } catch { policy[path] = null; }
+ }
+ writeFileSync(".cache/nested-evaluator/receipts/provenance.json", JSON.stringify({
+ commit: process.env.CANDIDATE_COMMIT, runId: process.env.GITHUB_RUN_ID,
+ attempt: process.env.GITHUB_RUN_ATTEMPT, provider: "github-actions-ubuntu-22.04-vm",
+ uid: process.getuid(), policy, cloudflareQualified: false,
+ bubblewrapCommit: "2a76602a8c71f36c1527cf9fc3417d9149822e0c"
+ }, null, 2) + "\n");'
+
+ - name: Install archive outside the checkout and require the complete evaluator proof
+ id: isolation
+ shell: bash
+ run: |
+ set -euo pipefail
+ test "$(id -u)" -ne 0
+ test ! -e /app
+ sudo mkdir /app
+ sudo chown "$(id -u):$(id -g)" /app
+ archive="$PWD/.cache/nested-evaluator/context/candidate.tgz"
+ receipts="$PWD/.cache/nested-evaluator/receipts"
+ (cd /app && npm init -y && npm install "$archive" --omit=dev --include=optional --ignore-scripts --no-audit --no-fund)
+ cp /app/package-lock.json "$receipts/package-lock.json"
+ # The fixed source fixture runs as the ordinary runner user. The engine
+ # itself creates the isolated namespace and strips the child environment.
+ set +e
+ timeout --signal=TERM --kill-after=15s 180s /usr/local/bin/kiln-probe-node \
+ scripts/hosting/run-native-qualification.mjs /app/node_modules/@instruktlabs/kiln \
+ "$receipts/isolation" "$archive" --isolation-only > "$receipts/probe.log" 2>&1
+ probe_exit=$?
+ set -e
+ printf '%s\n' "$probe_exit" > "$receipts/probe-exit.txt"
+ test "$probe_exit" -eq 0
+ node --input-type=module -e '
+ import assert from "node:assert/strict";import{readFileSync}from"node:fs";
+ const r=JSON.parse(readFileSync(".cache/nested-evaluator/receipts/isolation/receipt.json"));
+ assert.equal(r.version,"kiln.nested-evaluator-qualification.v1");
+ assert.equal(r.status,"passed");assert.equal(r.checks.length,9);
+ assert.equal(r.isolation.checks.length,10);assert.equal(r.artifacts.length,2);
+ assert(!r.software);assert(r.uid>0);'
+
+ - name: Diagnose the fixed transport launch without changing restrictions
+ if: ${{ !cancelled() && steps.isolation.outcome == 'failure' }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ node scripts/hosting/diagnose-native-launch.mjs \
+ .cache/nested-evaluator/receipts/transport-diagnostic.json
+
+ - name: Retain VM evaluator evidence, including failed prerequisites
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: nested-evaluator-preflight
+ path: |
+ .cache/nested-evaluator/receipts/
+ .cache/nested-evaluator/context/candidate.tgz
+ include-hidden-files: true
+ if-no-files-found: error
+ retention-days: 14
+
image-preflight:
- name: Linux image isolation and software rendering
+ name: Restricted Docker refusal and software rendering
runs-on: ubuntu-24.04
timeout-minutes: 25
env:
@@ -120,7 +247,7 @@ jobs:
timeout --signal=TERM --kill-after=5s 30s docker start --attach kiln-probe-diagnostics \
> .cache/hosting-ci/receipts/namespace-diagnostics.json
- - name: Require isolated native evaluation and rendering
+ - name: Require refusal when Docker denies nested isolation
if: ${{ !cancelled() && steps.image.outcome == 'success' }}
shell: bash
run: |
@@ -128,7 +255,10 @@ jobs:
receipts="$PWD/.cache/hosting-ci/receipts"
docker create --name kiln-probe-isolation --network none --cpus 1 \
--memory 6g --memory-swap 6g --pids-limit 256 --cap-drop ALL \
- --security-opt no-new-privileges kiln-native-probe:ci
+ --security-opt no-new-privileges kiln-native-probe:ci \
+ node /probe/hosting/run-native-qualification.mjs \
+ /app/node_modules/@instruktlabs/kiln /tmp/qualification /probe/candidate.tgz \
+ --expect-unsupported-isolation
set +e
timeout --signal=TERM --kill-after=15s 240s docker start --attach kiln-probe-isolation \
> "$receipts/isolation.log" 2>&1
@@ -143,7 +273,18 @@ jobs:
docker cp kiln-probe-isolation:/tmp/qualification "$receipts/isolation"
test "$attached_status" -eq 0
test "$(docker inspect kiln-probe-isolation --format '{{.State.ExitCode}}')" -eq 0
- node --input-type=module -e 'import{readFileSync}from"node:fs";if(JSON.parse(readFileSync(".cache/hosting-ci/receipts/isolation/receipt.json")).status!=="passed")process.exit(1)'
+ node --input-type=module -e '
+ import assert from "node:assert/strict";
+ import { readFileSync } from "node:fs";
+ const r = JSON.parse(readFileSync(".cache/hosting-ci/receipts/isolation/receipt.json"));
+ assert.equal(r.version, "kiln.unsupported-evaluator-rejection.v1");
+ assert.equal(r.status, "passed");
+ assert.equal(r.isolatedExecutionAvailable, false);
+ assert.equal(r.namespaceProbe.permissionDenied, true);
+ assert.equal(r.readinessFailure, "wrapper-launch");
+ assert.equal(r.evaluationFailure, "WORKER_FAILED");
+ assert.deepEqual(r.checks.map(c => c.name), ["host", "kernel-namespace-denied", "readiness-refused", "source-request-refused"]);
+ assert.deepEqual(r.artifacts, []);'
- name: Diagnose the trusted software-renderer fixture independently
if: ${{ !cancelled() && steps.image.outcome == 'success' }}
diff --git a/AGENTS.md b/AGENTS.md
index 6ec63151..7ea18675 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -181,7 +181,7 @@ lower them without a measured rationale. Live model tests are opt-in via `bun ru
`bun run test` is `bun test src scripts` and does **not** reach `render-service/`; run
`bun run test:render-service` whenever you change it (CI requires it).
-For hosted-service changes, follow [hosting/AGENTS.md](hosting/AGENTS.md).
+Private hosting: `instruktlabs/kiln-hosted`; public metadata: `plugins/kiln-hosted/`.
Tests use `--timeout 20000` for cold Windows startup; a larger budget needs an explicit third
`test()` argument with a measured-duration comment. Tests and CI pin `KILN_RENDER=cpu` so the
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bd4cbacb..7ea753d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,36 @@ Source releases and installable package publication are separate milestones.
Published versions and tags are recorded by the npm registry; changing this file
does not publish a package.
+## 1.1.0-dev.1 (unreleased)
+
+Development candidate for shared project setup. Published npm 1.0.0 remains
+unchanged. This candidate requires a reviewed local archive; it is not a registry
+release or an accepted plugin listing.
+
+- `kiln-init --adopt` configures an existing project or a new workspace through
+ the same initializer. Preview with `--adopt --check`; existing instructions,
+ unrelated configuration, saved assets and customized skills remain intact.
+- Multiple compatible client registrations share one program store. Managed
+ upgrades retain narrow configuration ownership and recover interrupted setup
+ writes without putting recovery snapshots inside the project.
+- Explicit migration of a copied legacy OpenCode workspace replaces its old
+ owned skill path instead of loading both original and copied instructions.
+- The local plugin's setup helper uses the pinned engine's adapter list. Plugin
+ installation remains specific to Claude Code and Codex; those clients can also
+ configure another supported workspace adapter through the shared helper.
+- The optional Linux isolated evaluator no longer passes an unsupported
+ `--preserve-fds` option to Bubblewrap. Its explicit fd3 protocol pipe uses
+ inherited descriptors; namespace, capability, filesystem and resource limits
+ remain required by readiness qualification.
+- Isolated readiness compares the child's namespace and non-root identity with
+ the parent, accounting for Bubblewrap's nested mapping when further user
+ namespaces are disabled. The final worker environment is cleared again to
+ remove Bubblewrap's injected `PWD` while retaining the exact allowed variables.
+- The isolated worker removes Node's legacy `__proto__` accessor instead of
+ throwing on reads, allowing Khronos glTF validation to initialize. Readiness
+ verifies that the accessor is absent; a regression also checks that assigning
+ a JSON `__proto__` key cannot change an object's prototype.
+
## 1.0.0
Changes since the 0.10.0 tagged package release, qualified first through the public
diff --git a/biome.json b/biome.json
index c6a2afc3..58d4ff51 100644
--- a/biome.json
+++ b/biome.json
@@ -8,11 +8,6 @@
"site/*.ts",
"scripts/**/*.mjs",
"scripts/**/*.ts",
- "hosting/src/**/*.ts",
- "hosting/test/**/*.{ts,mjs}",
- "hosting/scripts/**/*.mjs",
- "hosting/container/**/*.mjs",
- "hosting/probe/**/*.ts",
"render-service/src/**/*.mjs",
"render-service/test/**/*.mjs"
],
diff --git a/bun.lock b/bun.lock
index cd9841dc..e74cc250 100644
--- a/bun.lock
+++ b/bun.lock
@@ -15,10 +15,12 @@
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
+ "jsonc-parser": "3.3.1",
"manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
"sharp": "^0.35.5",
+ "smol-toml": "1.9.0",
"three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
@@ -509,6 +511,8 @@
"json-schema-typed": ["[email protected]", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
+ "jsonc-parser": ["[email protected]", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="],
+
"jwa": ["[email protected]", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],
"jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],
@@ -619,6 +623,8 @@
"side-channel-weakmap": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
+ "smol-toml": ["[email protected]", "", {}, "sha512-hpd+HLON7HdZXqYchMM/+LaTTbdK0AU3NngIJ4KVyWbY9bfQqdL9cD+4yf6dUoU2Ap4VsU0JkQi6FxAI1B2mXQ=="],
+
"standardwebhooks": ["[email protected]", "", { "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" } }, "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg=="],
"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 77fb8de3..cbb055b8 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -32939,7 +32939,7 @@ function createKilnSourceDef(store) {
}
// src/engine-identity.ts
-var ENGINE_VERSION = "1.0.0";
+var ENGINE_VERSION = "1.1.0-dev.1";
var ENGINE_INSTALL_URL = new URL("../", import.meta.url).href;
function engineIdentity() {
return { version: ENGINE_VERSION, installUrl: ENGINE_INSTALL_URL };
diff --git a/dist/build.json b/dist/build.json
index c47d1023..9ec913a9 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,12 +2,12 @@
"schemaVersion": 1,
"entries": {
"worker": {
- "identity": "sha256:81875ff0bc5f7b4b952f2bb32ffa11d9b4e2ee7067f1ccd458f6ec0aec455538",
- "engineVersion": "1.0.0",
+ "identity": "sha256:934e6fe27bf971fd0270266b4d3c4c8da2b51217242590e2862ae3c44e68d512",
+ "engineVersion": "1.1.0-dev.1",
"toolchain": "[email protected]",
- "sourceHash": "83b57574766f2e278eeee58d8b923b9bfc642a6832f2d1c137408b2b389acc7f",
+ "sourceHash": "ce7a81e9141c83e9a41e98b6a3d2cfc13738d889a610919c51c1f538724db61f",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "182eedef24fb67faae8fed2506e5ad51afee511fdcbce8fb8c709c3cc6fd91f9",
+ "dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -19,10 +19,12 @@
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
+ "jsonc-parser": "3.3.1",
"manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
"sharp": "^0.35.5",
+ "smol-toml": "1.9.0",
"three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
@@ -37,12 +39,12 @@
"bundleHash": "sha256:37098a17b5304a5f5746131c9652498d937a5181c0fb0975861dec999721d5be"
},
"agent-run": {
- "identity": "sha256:81875ff0bc5f7b4b952f2bb32ffa11d9b4e2ee7067f1ccd458f6ec0aec455538",
- "engineVersion": "1.0.0",
+ "identity": "sha256:934e6fe27bf971fd0270266b4d3c4c8da2b51217242590e2862ae3c44e68d512",
+ "engineVersion": "1.1.0-dev.1",
"toolchain": "[email protected]",
- "sourceHash": "83b57574766f2e278eeee58d8b923b9bfc642a6832f2d1c137408b2b389acc7f",
+ "sourceHash": "ce7a81e9141c83e9a41e98b6a3d2cfc13738d889a610919c51c1f538724db61f",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "182eedef24fb67faae8fed2506e5ad51afee511fdcbce8fb8c709c3cc6fd91f9",
+ "dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -54,10 +56,12 @@
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
+ "jsonc-parser": "3.3.1",
"manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
"sharp": "^0.35.5",
+ "smol-toml": "1.9.0",
"three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
@@ -69,15 +73,15 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:60946cbf1ddfbc28e60829013354fd069947892c1698c9597e14c672730f8628"
+ "bundleHash": "sha256:950d69ded532d9ca410ecd6bd10ab958c405a9c5a99f735db37d133b1e8e82e8"
},
"agent-providers": {
- "identity": "sha256:81875ff0bc5f7b4b952f2bb32ffa11d9b4e2ee7067f1ccd458f6ec0aec455538",
- "engineVersion": "1.0.0",
+ "identity": "sha256:934e6fe27bf971fd0270266b4d3c4c8da2b51217242590e2862ae3c44e68d512",
+ "engineVersion": "1.1.0-dev.1",
"toolchain": "[email protected]",
- "sourceHash": "83b57574766f2e278eeee58d8b923b9bfc642a6832f2d1c137408b2b389acc7f",
+ "sourceHash": "ce7a81e9141c83e9a41e98b6a3d2cfc13738d889a610919c51c1f538724db61f",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "182eedef24fb67faae8fed2506e5ad51afee511fdcbce8fb8c709c3cc6fd91f9",
+ "dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -89,10 +93,12 @@
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
+ "jsonc-parser": "3.3.1",
"manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
"sharp": "^0.35.5",
+ "smol-toml": "1.9.0",
"three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
@@ -107,12 +113,12 @@
"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"
},
"mcp": {
- "identity": "sha256:81875ff0bc5f7b4b952f2bb32ffa11d9b4e2ee7067f1ccd458f6ec0aec455538",
- "engineVersion": "1.0.0",
+ "identity": "sha256:934e6fe27bf971fd0270266b4d3c4c8da2b51217242590e2862ae3c44e68d512",
+ "engineVersion": "1.1.0-dev.1",
"toolchain": "[email protected]",
- "sourceHash": "83b57574766f2e278eeee58d8b923b9bfc642a6832f2d1c137408b2b389acc7f",
+ "sourceHash": "ce7a81e9141c83e9a41e98b6a3d2cfc13738d889a610919c51c1f538724db61f",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "182eedef24fb67faae8fed2506e5ad51afee511fdcbce8fb8c709c3cc6fd91f9",
+ "dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -124,10 +130,12 @@
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
+ "jsonc-parser": "3.3.1",
"manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
"sharp": "^0.35.5",
+ "smol-toml": "1.9.0",
"three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
@@ -139,15 +147,15 @@
},
"target": "node",
"file": "mcp-server.mjs",
- "bundleHash": "sha256:1f0727c7d63590d950d964e4dd15e303fdd27a79c97bf864aaaee5d7a7b9289e"
+ "bundleHash": "sha256:386083c5c3f34e9ee2bbc193dc4c058d23125a582c45a21fb08787116f7c961d"
},
"cli": {
- "identity": "sha256:81875ff0bc5f7b4b952f2bb32ffa11d9b4e2ee7067f1ccd458f6ec0aec455538",
- "engineVersion": "1.0.0",
+ "identity": "sha256:934e6fe27bf971fd0270266b4d3c4c8da2b51217242590e2862ae3c44e68d512",
+ "engineVersion": "1.1.0-dev.1",
"toolchain": "[email protected]",
- "sourceHash": "83b57574766f2e278eeee58d8b923b9bfc642a6832f2d1c137408b2b389acc7f",
+ "sourceHash": "ce7a81e9141c83e9a41e98b6a3d2cfc13738d889a610919c51c1f538724db61f",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "182eedef24fb67faae8fed2506e5ad51afee511fdcbce8fb8c709c3cc6fd91f9",
+ "dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -159,10 +167,12 @@
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
+ "jsonc-parser": "3.3.1",
"manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
"sharp": "^0.35.5",
+ "smol-toml": "1.9.0",
"three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
@@ -174,15 +184,15 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:bfe2e039974e093486b4d92af795235ac20c2d3772424237c90eb16455db47c5"
+ "bundleHash": "sha256:cdae5aab17e6941d28c647621435bb62a510e29747ce21790a683560203c38c2"
},
"engine": {
- "identity": "sha256:81875ff0bc5f7b4b952f2bb32ffa11d9b4e2ee7067f1ccd458f6ec0aec455538",
- "engineVersion": "1.0.0",
+ "identity": "sha256:934e6fe27bf971fd0270266b4d3c4c8da2b51217242590e2862ae3c44e68d512",
+ "engineVersion": "1.1.0-dev.1",
"toolchain": "[email protected]",
- "sourceHash": "83b57574766f2e278eeee58d8b923b9bfc642a6832f2d1c137408b2b389acc7f",
+ "sourceHash": "ce7a81e9141c83e9a41e98b6a3d2cfc13738d889a610919c51c1f538724db61f",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "182eedef24fb67faae8fed2506e5ad51afee511fdcbce8fb8c709c3cc6fd91f9",
+ "dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -194,10 +204,12 @@
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
+ "jsonc-parser": "3.3.1",
"manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
"sharp": "^0.35.5",
+ "smol-toml": "1.9.0",
"three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
@@ -209,7 +221,7 @@
},
"target": "node",
"file": "mcp-engine.mjs",
- "bundleHash": "sha256:c86e0280590c819d12baad3173fa0acc788cc6feb376e53cebf11abb44814d35"
+ "bundleHash": "sha256:a9fbfde488bcaa7be47c14aa2a22e3a32ae800e0785038a50348cbdaed7c79cd"
}
}
}
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 9bbda0d4..3d9cc886 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -29342,7 +29342,7 @@ function isolatedWorkerUrls(moduleUrl) {
}
// src/evaluator/isolation.ts
-import { existsSync } from "node:fs";
+import { existsSync, readlinkSync } from "node:fs";
import { posix } from "node:path";
import { fileURLToPath as fileURLToPath2 } from "node:url";
function isolationUnavailable() {
@@ -29384,7 +29384,7 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"
const setprivPath = requiredAbsolutePath(host.setprivPath ?? DEFAULT_SETPRIV_PATH);
const prlimitPath = requiredAbsolutePath(host.prlimitPath ?? DEFAULT_PRLIMIT_PATH);
const nodePath = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);
- for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath]) {
+ for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath, ENV_PATH]) {
if (!pathExists(executable))
isolationUnavailable();
}
@@ -29420,11 +29420,11 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"
for (const mount of runtimeMounts(runtimeRoot, pathExists)) {
bwrapArgs.push("--ro-bind", mount, mount);
}
- const nodeArgs = [nodePath, "--max-old-space-size=512", "--disable-proto=throw"];
+ const nodeArgs = [nodePath, "--max-old-space-size=512", "--disable-proto=delete"];
if (loader === "tsx")
nodeArgs.push("--import", "tsx");
nodeArgs.push(resolvedWorkerPath);
- bwrapArgs.push("--chdir", runtimeRoot, "--preserve-fds", "1", "--", prlimitPath, "--cpu=65:65", "--as=6442450944:6442450944", "--fsize=100663296:100663296", "--nofile=64:64", "--nproc=64:64", "--", ...nodeArgs);
+ bwrapArgs.push("--chdir", runtimeRoot, "--", prlimitPath, "--cpu=65:65", "--as=6442450944:6442450944", "--fsize=100663296:100663296", "--nofile=64:64", "--nproc=64:64", "--", ENV_PATH, "-i", "NODE_ENV=production", "NO_COLOR=1", ...nodeArgs);
return {
command: setprivPath,
args: [
@@ -29448,7 +29448,7 @@ async function renderGLBViaIsolatedEvaluator(code, options = {}, controls = {})
const { host: _, ...processControls } = controls;
return renderGLBViaProcessLaunch(code, options, processControls, launch);
}
-var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", MAX_READINESS_PROTOCOL_BYTES;
+var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", ENV_PATH = "/usr/bin/env", MAX_READINESS_PROTOCOL_BYTES;
var init_isolation = __esm(() => {
init_subprocess();
MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;
@@ -36171,7 +36171,7 @@ var init_program_artifacts = __esm(() => {
function engineIdentity() {
return { version: ENGINE_VERSION, installUrl: ENGINE_INSTALL_URL };
}
-var ENGINE_VERSION = "1.0.0", ENGINE_INSTALL_URL;
+var ENGINE_VERSION = "1.1.0-dev.1", ENGINE_INSTALL_URL;
var init_engine_identity = __esm(() => {
ENGINE_INSTALL_URL = new URL("../", import.meta.url).href;
});
diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjs
index 6f92074d..0d47ee6e 100644
--- a/dist/mcp-engine.mjs
+++ b/dist/mcp-engine.mjs
@@ -28525,7 +28525,7 @@ function isolatedWorkerUrls(moduleUrl) {
}
// src/evaluator/isolation.ts
-import { existsSync as existsSync3 } from "node:fs";
+import { existsSync as existsSync3, readlinkSync } from "node:fs";
import { posix } from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";
function isolationUnavailable() {
@@ -28567,7 +28567,7 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"
const setprivPath = requiredAbsolutePath(host.setprivPath ?? DEFAULT_SETPRIV_PATH);
const prlimitPath = requiredAbsolutePath(host.prlimitPath ?? DEFAULT_PRLIMIT_PATH);
const nodePath = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);
- for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath]) {
+ for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath, ENV_PATH]) {
if (!pathExists(executable))
isolationUnavailable();
}
@@ -28603,11 +28603,11 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"
for (const mount of runtimeMounts(runtimeRoot, pathExists)) {
bwrapArgs.push("--ro-bind", mount, mount);
}
- const nodeArgs = [nodePath, "--max-old-space-size=512", "--disable-proto=throw"];
+ const nodeArgs = [nodePath, "--max-old-space-size=512", "--disable-proto=delete"];
if (loader === "tsx")
nodeArgs.push("--import", "tsx");
nodeArgs.push(resolvedWorkerPath);
- bwrapArgs.push("--chdir", runtimeRoot, "--preserve-fds", "1", "--", prlimitPath, "--cpu=65:65", "--as=6442450944:6442450944", "--fsize=100663296:100663296", "--nofile=64:64", "--nproc=64:64", "--", ...nodeArgs);
+ bwrapArgs.push("--chdir", runtimeRoot, "--", prlimitPath, "--cpu=65:65", "--as=6442450944:6442450944", "--fsize=100663296:100663296", "--nofile=64:64", "--nproc=64:64", "--", ENV_PATH, "-i", "NODE_ENV=production", "NO_COLOR=1", ...nodeArgs);
return {
command: setprivPath,
args: [
@@ -28631,7 +28631,7 @@ async function renderGLBViaIsolatedEvaluator(code, options = {}, controls = {})
const { host: _, ...processControls } = controls;
return renderGLBViaProcessLaunch(code, options, processControls, launch);
}
-var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", MAX_READINESS_PROTOCOL_BYTES;
+var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", ENV_PATH = "/usr/bin/env", MAX_READINESS_PROTOCOL_BYTES;
var init_isolation = __esm(() => {
init_subprocess();
MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;
@@ -36102,7 +36102,7 @@ import { readFile as readFile8 } from "node:fs/promises";
var KILN_ASSET_WIDGET_URI = "ui://kiln/asset-v5.html";
// src/engine-identity.ts
-var ENGINE_VERSION = "1.0.0";
+var ENGINE_VERSION = "1.1.0-dev.1";
var ENGINE_INSTALL_URL = new URL("../", import.meta.url).href;
function engineIdentity() {
return { version: ENGINE_VERSION, installUrl: ENGINE_INSTALL_URL };
diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjs
index 955d36eb..af982665 100644
--- a/dist/mcp-server.mjs
+++ b/dist/mcp-server.mjs
@@ -2085,7 +2085,7 @@ import { readFile } from "node:fs/promises";
var KILN_ASSET_WIDGET_URI = "ui://kiln/asset-v5.html";
// src/engine-identity.ts
-var ENGINE_VERSION = "1.0.0";
+var ENGINE_VERSION = "1.1.0-dev.1";
var ENGINE_INSTALL_URL = new URL("../", import.meta.url).href;
// src/requirements-json.ts
diff --git a/docs/local-plugin-privacy.md b/docs/local-plugin-privacy.md
index 4fba8ceb..1fb29bf5 100644
--- a/docs/local-plugin-privacy.md
+++ b/docs/local-plugin-privacy.md
@@ -15,6 +15,14 @@ data directory outside the plugin cache. Paths can contain your device account
name; paths, package identity and file hashes appear in local configuration,
installation records and command results returned to your assistant.
+When adding Kiln to an existing project, setup reads the selected client's
+configuration and records ownership of Kiln's own entries. It preserves unrelated
+settings and existing project instructions. A recoverable setup transaction
+temporarily copies the affected files into private local recovery storage outside
+the project. Those copies can contain credentials already present in the client's
+configuration. They are not uploaded, printed or added to the workspace manifest.
+This storage uses filesystem permissions; Kiln does not encrypt these snapshots.
+
Your workspace and configured asset libraries hold authored JavaScript, material
files, asset names, metadata, previews and GLBs. Local tools read and write the
work you ask them to handle and return requested source, images and results to
@@ -60,6 +68,15 @@ remain until you delete them. Uninstalling the plugin removes neither your asset
nor its separately installed engine. Plugin updates also leave existing
workspaces on their installed engine until you request a managed upgrade.
+Setup removes recovery snapshots after a successful transaction or completed
+recovery. Interrupted setup can leave them until recovery succeeds or you resolve
+the interruption. The default location is
+`%LOCALAPPDATA%/InstruktLabs/Kiln/setup-transactions` on Windows, or
+`$XDG_DATA_HOME/instruktlabs/kiln/setup-transactions` elsewhere, falling back to
+`~/.local/share/instruktlabs/kiln/setup-transactions`. Use the setup helper's
+`--recover` operation before retrying an interrupted change. Do not upload recovery
+files to a public issue or delete them while setup or recovery is active.
+
There is no automatic seven-day expiry for local work; that is a separate hosted
service policy. Remove selected local work using Kiln's library controls or your
filesystem, and manage independent exports, backups, npm caches and assistant
diff --git a/docs/plans/2026-10-05-v1-publication-plan.md b/docs/plans/2026-10-05-v1-publication-plan.md
index bcd08799..2275835e 100644
--- a/docs/plans/2026-10-05-v1-publication-plan.md
+++ b/docs/plans/2026-10-05-v1-publication-plan.md
@@ -2,7 +2,14 @@
Research dates: 5-6 October 2026. Repository audited at
`cf4abe6c7b142da56d005751e21d0f9c57a9dd21`.
-Plan updated: 6 October 2026, including release sequencing, ownership, hosting economics and decision handling.
+Plan updated: 7 October 2026 for the public-engine/private-hosting boundary and
+the revised execution goal. Earlier research sections retain their dated context.
+
+Execution checkpoint, 7 October: stable `@instruktlabs/[email protected]` and the GitHub
+release are public. The goal is active. Shared project setup is being qualified;
+public hosting and directory submissions remain unfinished. See the
+[current status and PR sequence](../reviews/2026-10-07-release-status.md).
+The research and earlier setup observations below retain their original context.
Status: documented v1 plan, with owner decisions recorded in section 9 and remaining
choices proposed for review. This document records research and planned work;
@@ -26,7 +33,30 @@ The owner has set the next publication target to **1.0**.
Older references to a separate 0.11 release remain historical until the maintained
roadmap and release documents are aligned during implementation.
-## Goal statement
+## Goal statement, updated 7 October
+
+Complete the release cycle with the public Kiln engine and agent integrations,
+an independently buildable private hosted application under Instrukt Labs, the
+authenticated Cloudflare service and applicable directory submissions. Stable
+1.0.0 is already published; deliver a qualified follow-up for the approved shared
+setup and fixes rather than replacing that version. Preserve the public repository
+and its community history while removing `hosting/` from its current default branch
+after a verified private import. Public integration metadata and generic evaluator
+checks remain public.
+
+The [updated execution goal](2026-10-06-v1-execution-goal.md) is the copyable current
+goal. The [migration scope](2026-10-07-private-hosting-separation.md) records
+the file/dependency boundary and acceptance requirements. Target a focused day of
+remaining controllable engineering, reuse completed evidence and avoid unrelated
+redesign. This target never waives explicit approvals or unfinished launch work.
+
+The monthly one-seat GitHub Team upgrade is complete. The separate private
+`instruktlabs/kiln-hosted` import is independently qualified and merged with owner
+approval. Next, remove the hosting implementation through a normal public cleanup
+PR while preserving existing history and public integrations. The owner accepts
+old hosting code remaining visible in history; no history rewrite is planned.
+
+### Original 6 October goal and setup context
Deliver Kiln Engine 1.0 as a verified public npm package with a supported SDK, CLI,
local MCP server and installable Claude Code/Codex plugins; qualify and launch an
@@ -1274,6 +1304,23 @@ complete on a successful ZIP validation or form submission alone.
## 9. Decision queue and owner collaboration
+### 7 October local setup alignment
+
+The owner selected **Kiln**, if available in the applicable directory, with
+**Instrukt Labs** as public publisher. The exact LLC name belongs in legal fields.
+This supersedes the earlier product-display-name recommendation; it does not
+rename installation identifiers or establish directory availability.
+
+The owner also selected **existing-project setup and new workspaces** for local
+v1, through one shared setup process used by thin agent integrations. Keep the
+engine, skills and project storage independent of Claude Code or any other
+harness. The implementation proposal and required preservation/onboarding tests
+are in [the agnostic local setup plan](2026-10-07-agnostic-local-setup.md).
+This is additional release work, not functionality already present in npm 1.0.0.
+The earlier binary choice between setup-only onboarding and a Claude-specific
+redesign is superseded. Claude submission changes and further outreach remain on
+hold for alignment and review of a concrete candidate.
+
### Confirmed constraints
The release target is 1.0; community issue/PR triage remains outside the pre-v1 scope.
@@ -1323,6 +1370,10 @@ This settles D8 and reinforces that $20 is a target, not a guaranteed billing ca
| D8 | Free quota-limited hosted access initially, optional sponsorship, no subscription billing in v1 | Implement within measured hosting capacity and storage/admission limits | Owner explicitly accepted on 6 October; accepts justified provider overages and may seek sponsorship/grants; do not ask again |
| D9 | Google and GitHub sign-in through one Kiln-owned account; email later | Before provisioning provider applications | Owner accepted on 6 October, requiring correct, secure implementation and professional presentation; architecture reviewed above, multi-provider implementation and deployed qualification remain open |
| D10 | In-app security notices only for v1 | Settled; do not ask again | Owner selected on 6 October. No separate security contact email collection or outbound security mail; Google/GitHub sign-in unchanged. Out-of-band notifications can follow later. |
+| D11 | Kiln as product display name if available; Instrukt Labs as public publisher; exact LLC identity in legal fields | Verify availability and publisher ownership before a concrete submission | Owner selected on 7 October; supersedes D1's earlier display-name recommendation. No plugin identifier rename or submission authorized by this choice. |
+| D12 | One shared local setup process supporting existing projects and new workspaces, with thin agent integrations | Qualify preservation, upgrades and real client onboarding before release | Owner selected on 7 October. The development extension passes local tests and an installed Windows storage-reuse check; cross-platform candidate CI and real onboarding remain. Published 1.0.0 still requires an empty folder. |
+| D13 | Public engine and integrations; separate private hosted application under Instrukt Labs | Verify private import and independent builds/tests before removing the public `hosting/` folder | Owner selected on 7 October. Private `instruktlabs/kiln-hosted` PR #1 is qualified and merged as `e84d79f`. Remove public files through a normal cleanup PR, preserving history and licenses. Cleanup merge and deployment remain separate approvals. |
+| D14 | Target migration and remaining controllable engineering within a focused day; reuse active GitHub Team billed monthly | Configure and verify branch rules and private CI during migration | Owner completed the $4/month one-seat upgrade on 7 October. Organization API verifies Team with one purchased/filled seat. This supplies protection rules in the separate private repository, not a private branch in the public repository. Private Actions usage remains metered beyond allowances. |
Do not present D4's provider decision as passed production qualification or D5 as a measured forecast. Legal
entity/account fields must come from the owner; do not infer exact legal details
diff --git a/docs/plans/2026-10-06-hosting-economics.md b/docs/plans/2026-10-06-hosting-economics.md
index 9c71c5b7..d78bc9b9 100644
--- a/docs/plans/2026-10-06-hosting-economics.md
+++ b/docs/plans/2026-10-06-hosting-economics.md
@@ -2,6 +2,17 @@
Research date: 6 October 2026. Companion to the [v1 publication plan](2026-10-05-v1-publication-plan.md).
These are calculated scenarios, not measured Cloudflare performance or an invoice forecast.
+The [updated execution goal](2026-10-06-v1-execution-goal.md#github-team-status-and-operating-constraints)
+records a separate development cost for the private hosted repository: the owner
+completed **GitHub Team, billed monthly**, on 7 October. GitHub's organization API
+verifies Team with one purchased/filled seat. Checkout showed **$4/month** before
+tax and usage; the final invoice was not inspected. This is separate from
+Cloudflare hosting and end-user billing. Private Actions usage must be tracked
+against its included 3,000-minute allowance, alongside storage and other metered
+services. Do not purchase another plan or add seats by default.
+Source: [GitHub pricing](https://github.com/pricing).
+
+The following no-action statement describes the original 6 October research:
No paid Cloudflare deployment, DNS change, sponsorship application or account upgrade
was performed. The existing, separately authorized private Sites probe remains active.
diff --git a/docs/plans/2026-10-06-v1-execution-goal.md b/docs/plans/2026-10-06-v1-execution-goal.md
index 895775d6..35d17c4c 100644
--- a/docs/plans/2026-10-06-v1-execution-goal.md
+++ b/docs/plans/2026-10-06-v1-execution-goal.md
@@ -1,92 +1,161 @@
-# Kiln 1.0 execution goal
-
-Prepared 6 October 2026. Status: activated by the owner's explicit goal on 6 October.
-Track current progress in [the execution record](../reviews/2026-10-06-v1-execution.md).
-The owner previously authorized the early transfer and npm setup separately:
-the native transfer is complete with preservation verified, an Actions-policy
-compatibility fix is applied with a passing Linux CI rerun, and the npm account/free
-organization are created with two security keys and 2FA enforcement verified.
-The local recovery backup is encrypted and verified, and its staging plaintext is
-removed. Local npm CLI login remains unconfigured until publishing requires it.
-Cloudflare's dashboard confirms Workers Paid and R2 Paid are already active;
-no subscription purchase or upgrade was needed. Implementation is now underway on
-`codex/v1-publication`, tracked in the execution record. No hosted production
-deployment or npm release has been performed.
-
-Use with the [full publication plan](2026-10-05-v1-publication-plan.md) and
-[hosting economics](2026-10-06-hosting-economics.md). Current code, `AGENTS.md` and the
-owner's subsequent instructions take precedence over dated planning observations.
+# Kiln release-cycle execution goal
+
+Updated 7 October 2026 for the owner's public-engine/private-hosting decision.
+The existing goal remains active with the accepted public/private split. This text
+records that goal and its current completion boundaries; it does not create a
+second goal. The owner separately approved
+GitHub Team at $4/month for one seat, billed monthly. The owner completed the
+upgrade, and GitHub's organization API now verifies `plan.name: team`, `seats: 1`
+and `filled_seats: 1`.
+
+Stable `@instruktlabs/[email protected]` and the GitHub release are already published.
+Reuse the completed GitHub transfer, npm security/trusted-publishing setup,
+Cloudflare subscriptions, the completed GitHub Team upgrade and existing OAuth
+applications. Do not repeat that work.
+Current evidence and unfinished tasks are in the
+[release status](../reviews/2026-10-07-release-status.md).
## Copyable goal statement
-Execute the entire Kiln Engine 1.0 publication plan in
-`docs/plans/2026-10-05-v1-publication-plan.md`, using
-`docs/plans/2026-10-06-hosting-economics.md` for hosting assumptions. Target sustained
-overnight execution from the completed publisher setup. Work in
-`C:/Users/Mattm/X/kiln-oss`; the sibling dogfood directory contains setup evidence,
-not the release checkout. Keep every outcome in scope; do not call the goal complete until all
-required work within our control has passed and its result is verified.
-
-**First, confirm the completed setup and establish the v1 contract.** The existing
-repository moved from `matthew-kissinger/kiln` to `instruktlabs/kiln` with identity,
-history, stars, watchers, forks, issues, PRs and releases preserved. Read the transfer
-receipts and current status; do not repeat the transfer. Verify the completed
-Actions-policy fix and its CI result, operational access and publishing
-bindings. Keep redirects and my personal pin intact. Do not recreate the repository
-or triage, close or merge incoming community contributions. Surface any unexplained
-preservation discrepancy immediately.
-
-**Second, prepare publishing access when the candidate needs it.** Reuse the created personal account
-`matthew-kissinger` and free `instruktlabs` organization; do not recreate them. Verify
-2FA/recovery readiness and prepare `@instruktlabs/kiln` publishing access. Bring any
-remaining verification, login, 2FA and recovery handoffs to me through the
-visible browser and chat. Never ask for secrets in chat. Configure GitHub trusted
-publishing and staged release approval when the package is ready; organization
-registration does not itself authorize publishing a placeholder or release. Do not
-repeat completed email, 2FA or recovery setup, or let a pending interactive login
-block independent package engineering.
-
-**Then implement and qualify the full release:** the supported ESM/TypeScript SDK,
-CLI, local MCP, skills, package contents and migrations; installable Claude Code and
-Codex plugins; and the authenticated service at `kiln.instruktlabs.com` on Cloudflare
-Workers, Containers, R2, D1 and Durable Objects. Qualify native evaluation, tenant
-isolation, CPU rendering and software Vulkan, downloads, retention, quotas, load and
-cost against the plan. Retain existing experimental features with explicit labels.
-Keep saved assets until deletion within quotas and expire unsaved work after seven
-days. Treat $20/month as an initial target, not a spending authorization or hard cap.
-Hosted access is free within quotas, with optional sponsorship and no subscription
-billing in v1. Reuse the already-active Cloudflare Workers Paid and R2 subscriptions;
-do not buy a duplicate plan. Evaluate reasonable usage growth against measured costs
-and the existing $10 budget alert; keep account purchases distinct from billing users.
-
-Use a `codex/` branch and commit/push tested work needed for CI. Follow current
-repository instructions, preserve unrelated changes, and verify exact packed
-artifacts and real installed/hosted flows. Prepare the complete release and directory
-candidates, surface any still-required approval against concrete artifacts or costs,
-and carry out authorized publication, deployment and submissions. Use the same
-qualified engine version across package and hosted integrations.
-
-Sequence consequential decisions through the question tool, honor settled answers,
-and continue independent work while I handle account steps. Surface missing
-permissions, provider blockers and material scope/cost changes promptly. Do not
-silently weaken checks, skip scope or switch hosts to finish overnight.
-
-Finish with verified npm `1.0.0`, working local plugin distribution, a verified hosted
-service and submission receipts for the applicable OpenAI and Anthropic directories.
-Report each milestone separately with exact versions, hashes, URLs and evidence.
-Vendor review/acceptance may remain pending after submission; unfinished engineering,
-authentication or publication work must remain explicitly open. Keep a durable
-progress record so the run can continue accurately through interruptions.
-
-## Hosted-access decision resolved
-
-D8 was explicitly accepted on 6 October: free hosted access within quotas, optional
-sponsorship and no subscription billing. The owner accepts justified provider usage
-overages and is open to a suitable paid Cloudflare plan. Exact technical quotas still
-require measurements; no further business-model preference question is needed.
-
-The owner also selected Google and GitHub sign-in through one Kiln-owned account,
-with email sign-in deferred. Correct security and a professional, clearly branded
-end-user flow are explicit acceptance requirements. Follow the publication plan's
-6 October authentication architecture review; do not treat the current GitHub-only
-fixture or passing local OAuth checks as deployed multi-provider acceptance.
+Complete this Kiln release cycle with a public, community-maintained engine and
+integrations, an independently buildable private hosted application under Instrukt
+Labs, a working authenticated Cloudflare service, and the applicable OpenAI and
+Anthropic directory submissions. Use the
+`docs/plans/2026-10-07-private-hosting-separation.md` migration scope, the existing
+publication plan and hosting economics, and my subsequent decisions. Preserve the
+full end state; migration alone does not complete this goal.
+
+Work from `C:/Users/Mattm/X/kiln-oss` and the separate private application checkout
+at `C:/Users/Mattm/X/kiln-hosted`. Preserve the reviewed hosting source,
+tests, origin and evidence in `instruktlabs/kiln-hosted`. Keep it able to install, build and
+test from a clean checkout with explicit pinned engine dependencies, with no
+adjacent developer checkout or unpublished local files required. Keep reusable
+engine contracts public and derive MCP metadata from the shared registry.
+
+Use the already-active GitHub Team organization plan to protect the private
+repository's `main` branch with pull requests, required passing checks and
+protection against force pushes and deletion. Verify the rules through readback
+and a controlled check. Keep build/test CI free of production credentials and
+track private Actions usage against its included allowance. Team does not provide
+required environment reviewers in private repositories, so production deployment
+remains an explicitly approved operator action. The public npm release workflow
+retains its existing protected environment. There is no private branch within the
+public engine repository; repository visibility and branch protection are separate.
+
+Then remove `hosting/` and private-service-only CI from the public default branch
+through a reviewed cleanup PR. Relocate public plugin manifests, skills and
+connection documentation first, and retain generic evaluator tests. Preserve
+repository identity, stars, forks, issues, PRs, releases, redirects and my personal
+pin. Use a normal deletion/relocation PR and preserve public Git history and
+existing license notices. The owner accepts the old hosting source remaining in
+history; do not rewrite commits, force-push or remove historical release tags.
+Reconcile our open release PRs without losing their
+work. Incoming community PRs remain outside this cycle's scope.
+
+Reuse the published 1.0.0 package. Finish and publish the appropriately versioned
+follow-up needed for shared setup in existing projects and new workspaces, and
+the already-developed fixes. Verify actual installed Claude Code and Codex flows,
+preservation of users' files and settings, and agent-agnostic local MCP/skills.
+Local use remains account-free. Never replace an already-published version.
+
+Finish qualification and deploy the private application to `kiln.instruktlabs.com`
+on Cloudflare. Prove real Google and GitHub sign-in, account controls, tenant
+isolation, native evaluation, CPU/software rendering, saved assets, downloads,
+retention/deletion, quotas, practical load/cost limits and rollback. Keep saved
+assets until deleted within quotas; expire unsaved work after seven days. Use
+in-app security notices. Resolve the existing backup-scope decision before adding
+a backup system. Complete an adversarial review of the actual release and deployed
+configuration; secrets and user data stay outside source repositories.
+
+Keep hosted use free within quotas, with optional sponsorship and no user billing.
+Optimize initial hosting toward $20/month without treating it as a hard cap.
+Surface exact subscription costs, bounded trial spending and material increases
+before purchase or execution; reuse existing Cloudflare plans. Record the separate
+GitHub Team development subscription at $4/month for one seat before tax or
+metered usage. Monthly billing is settled; do not buy another plan or seat by
+default.
+
+After verifying the service, complete the public README, Troy imagery, site and
+installation documentation. Review the complete directory dossiers with me,
+including Kiln naming, Instrukt Labs publisher ownership, supported clients and
+skills. Then submit the applicable OpenAI and Anthropic candidates once authorized.
+Track vendor review separately from submission; do not claim pending review as
+acceptance. Preserve my hold on further Claude portal changes or outreach until
+the concrete dossier is aligned.
+
+Target the migration and remaining controllable engineering within the next
+focused day. Use the current implementation and passing evidence, make only the
+boundary changes and demonstrated fixes needed to finish, and avoid adding
+general frameworks, unrelated features or repetitive validation. Run checks
+affected by changes and required final release gates. Surface concrete blockers
+early; timing never substitutes for working behavior or security.
+
+Use `codex/` branches and preserve unrelated changes. Continue authorized local
+implementation and tested commits/pushes needed for CI. Reuse the already-created
+private remote. Sequence remaining paid trials, main merges, publication, production deployment and
+submission approvals against concrete candidates. Put authentication in the
+browser and decisions in the question tool; never request secrets in chat. Do not
+repeat settled decisions. Continue independent work while awaiting owner steps.
+
+Finish only when private-repository independence and public cleanup, package/local
+plugin publication, real hosted operation, current public documentation and
+directory submissions each have direct evidence. Report exact versions, source
+commits, URLs and relevant artifact hashes, with any external review still pending.
+
+## Completed private-repository checkpoint
+
+The private repository is created and [PR #1](https://github.com/instruktlabs/kiln-hosted/pull/1)
+is merged with owner approval as `e84d79f15d4c143e0855bf57ea1b5709e32dd165`.
+Its tree matches approved `1d6bd74` exactly. All five CI checks passed, including
+459 application tests on Linux and Windows; all 14 production modules matched
+local and both CI builds. Main protections are configured and verified, with no
+production secrets in repository Actions. Public cleanup is prepared locally and
+still requires qualification and explicit merge approval.
+
+The private app consumes published 1.0.0 independently. Its two documented
+compatibility adapters still need supported public engine exports in the follow-up;
+independent builds do not by themselves complete the long-term API boundary.
+
+## Delivery order and acceptance
+
+| Step | Completion evidence |
+| --- | --- |
+| 1. Preserve and extract hosting | Existing Team plan reused; private repository/permissions and branch-rule readback; reviewed source and attribution retained; secrets absent from import |
+| 2. Make the private application independent | Fresh-checkout install/typecheck/test/build and private CI pass against recorded engine input; no sibling checkout required |
+| 3. Clean the public default branch | Approved cleanup PR merged; `hosting/` absent; public plugins and generic evaluator checks retained; no private source copied into another public path or artifact |
+| 4. Close package and local onboarding work | Qualified follow-up package and plugin artifacts published; real Claude Code and Codex existing/new-project flows verified |
+| 5. Complete hosted qualification and launch | Real provider/account/storage/render/retention/rollback flows and scoped security/cost evidence; approved public deployment and actual MCP client verification |
+| 6. Finish public docs and directory submissions | README/site show actual install and hosted behavior; owner-aligned submission receipts; vendor review tracked separately |
+
+Current unanswered paid-trial/onboarding and backup decisions remain unanswered.
+Reconcile the frozen trial inputs with the repository move; do not silently swap
+an approved artifact for a different candidate. The one-day target is an execution
+priority, not a promise about owner availability or vendor turnaround.
+
+## GitHub Team status and operating constraints
+
+**Completed 7 October 2026:** the owner purchased the monthly Team upgrade.
+Authenticated `gh api orgs/instruktlabs` independently returned `plan.name: team`,
+`plan.seats: 1` and `plan.filled_seats: 1`. Checkout previously showed **Pay monthly**,
+**one seat** and **$4/month** before tax or usage. The final invoice/tax amount was
+not inspected. Billing address and payment data remain outside this repository.
+
+GitHub advertises 3,000 included Actions minutes/month on Team. Track private CI
+and artifact usage; the $4 base is not a cap on metered services or extra seats.
+This development subscription is separate from the Cloudflare hosting target.
+Legal business name is verified as **Instrukt Labs, LLC**, Virginia SCC entity
+11834137; public publisher branding remains **Instrukt Labs**.
+
+Team does **not** provide required environment reviewers for private repositories.
+Keep v1 deployment as an explicitly approved operator action with production
+credentials outside build/test CI; do not promise Enterprise-only gates or buy
+Enterprise just to reproduce the public npm environment. The public npm release
+workflow and its existing approvals remain in the public engine repository.
+
+Sources checked 7 October 2026:
+
+- [GitHub pricing](https://github.com/pricing)
+- [Protected branches](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches)
+- [License users](https://docs.github.com/en/billing/reference/github-license-users)
+- [Deployment environment restrictions](https://docs.github.com/en/actions/reference/workflows-and-actions/deployments-and-environments)
+- [Virginia SCC entity 11834137](https://cis.scc.virginia.gov/EntitySearch/BusinessInformation?businessId=11834137)
diff --git a/docs/plans/2026-10-07-agnostic-local-setup.md b/docs/plans/2026-10-07-agnostic-local-setup.md
new file mode 100644
index 00000000..a8ef860f
--- /dev/null
+++ b/docs/plans/2026-10-07-agnostic-local-setup.md
@@ -0,0 +1,126 @@
+# Kiln local setup across agents
+
+Status: shared setup is implemented in the development candidate, 7 October 2026.
+Focused preservation tests and installed archives pass, including cross-platform
+CI at `225d74a`. Independent review produced two fixes; their `1.1.0-dev.1`
+follow-up and real client onboarding need fresh qualification. This is not a new
+package release or a directory submission. Published 1.0.0 remains unchanged.
+
+## Decisions and intent
+
+The owner wants Kiln to remain agent and harness agnostic. Claude Code and Codex
+plugins should be convenient integrations with a shared product, rather than
+determine the engine's architecture. Small extensions or restructuring are in
+scope when they improve that shared experience.
+
+The owner selected **support existing projects and new workspaces** for local v1
+onboarding through the question tool. The earlier question offering only the
+existing setup-only design or a Claude-specific redesign is superseded.
+
+The public product name is **Kiln**, subject to directory availability, with
+**Instrukt Labs** as publisher. Use the exact registered legal entity name in
+legal fields; its punctuation has not been verified. GitHub organization
+ownership does not establish ownership of a vendor directory listing. Do not
+rename installation identifiers or resume submission/outreach merely because this
+direction is recorded.
+
+## Current implementation and gaps
+
+- Published 1.0.0 requires an empty destination for first setup. The development
+ initializer adds `--adopt` for populated projects and new workspaces, with a
+ read-only `--adopt --check` preview. Schema 2 records multiple registrations
+ around one store; plain legacy creation and schema 1 maintenance remain available.
+- `scripts/setup-plugin-workspace.mjs` installs a pinned npm engine outside the
+ disposable plugin cache and invokes the same workspace generator. The local
+ plugin currently exposes only the setup skill; author/refine/QA skills arrive
+ in the generated workspace, with compose/batch optional.
+- `scripts/package-local-plugin.mjs` already generates Claude and OpenAI
+ manifests from shared identity and maintained setup files. Preserve that source
+ ownership instead of maintaining independent copies by hand.
+- The installed development archive preserves source, program references, saved
+ revisions and exact GLB bytes when adding Codex after Claude. This uses two
+ separately launched MCP servers from their generated registrations, not model
+ conversations or proof of concurrent authoring safety.
+- Maintained setup guidance now explains trusted `.codex/config.toml`, interactive
+ `codex`, and the explicit-prompt headless launcher. Real first-use conversations
+ remain required. Broader public documentation refresh is still deferred.
+
+## Proposed implementation boundary
+
+1. **One setup service, multiple entry points.** Extend the maintained initializer
+ used by npm/CLI and plugin setup. Keep runtime installation, version checks,
+ project storage and repair/upgrade logic outside client-specific wrappers.
+ Preserve existing initializer commands and existing managed workspaces.
+2. **Safe adoption of an existing project.** Inspect before writing. Add Kiln's
+ owned state and narrowly merge its selected integration entries. Preserve
+ unrelated MCP servers, settings, skills, `AGENTS.md`, `CLAUDE.md` and project
+ content. Report conflicts before mutation; never replace a whole project
+ config merely to add Kiln. Show the intended changes and provide a check mode.
+ Exact file placement and manifest evolution need design/test review.
+3. **Optional agent registrations around the same project.** Keep asset storage
+ and engine identity independent of agent choice. Add or remove a selected
+ integration without recreating the project, duplicating saved assets or
+ relocating authentication. Preserve the host's normal trust decisions.
+4. **Thin client adapters.** Each integration owns only its manifest, supported
+ configuration format, registration locations and any necessary launcher.
+ Reuse the maintained core skills and tool registry. Avoid duplicate skill/MCP
+ registration when the plugin and project integration are both present.
+5. **Guided first use.** Let setup use a chosen existing project or create a new
+ workspace, then verify the actual client can see the expected engine and
+ tools. Make available authoring workflows clear. Do not assume installation
+ means a live session has reloaded its tools. Keep compose/batch optional.
+6. **Separate local and hosted delivery.** Local setup stays account-free.
+ Claude apps and ChatGPT use the authenticated hosted service and their own
+ thin packages. A hosted wrapper must not depend on a local Node installer,
+ global shell permissions or Claude-specific settings. Reuse engine behavior
+ and portable workflow guidance where supported.
+
+Existing-project support applies to user projects. The engine repository remains
+the wrong place to author assets; retain that boundary. Projects as an optional
+Kiln asset-grouping feature must not become mandatory just because the containing
+directory is an application project.
+
+## Qualification and release sequence
+
+1. Add failing tests for adopting projects with existing instructions, skills and
+ MCP configuration, including collisions, interrupted writes and rollback.
+2. Implement the shared setup extension and compatible manifest migration, then
+ test check, repair, repeat setup and upgrade without losing customizations.
+3. Verify the same saved asset/program references through two independently
+ registered agents, with no duplicate server or copied asset store. Test the
+ CLI path without installing a plugin too.
+4. Rebuild and qualify the exact engine archive and derived plugin candidates.
+ The already-published `1.0.0` cannot be modified in place; choose the next
+ release version from the actual compatibility impact. Publication remains a
+ separate approval.
+5. Run real first-use conversations in each advertised client from both an empty
+ folder and a populated project. Direct SDK tests and zero-model-turn receipts
+ are not substitutes for this onboarding evidence.
+6. Review the exact candidate's name, publisher, supported clients, installed
+ workflows, setup actions and privacy links with the owner before submission.
+ Keep the findings in the [Claude distribution audit](../reviews/2026-10-07-claude-distribution-audit.md)
+ open until their individual checks pass.
+
+## Current documentation basis
+
+The [configuration preservation](../reviews/2026-10-07-project-config-preservation.md)
+and [recoverable writes](../reviews/2026-10-07-setup-recovery.md) foundations now
+serve the shared initializer. The [adoption checkpoint](../reviews/2026-10-07-project-adoption.md)
+records installed-archive evidence, preservation boundaries and unfinished
+release work. Keep client-specific skill registration paths around the same
+maintained sources; a fresh Claude probe loads `.claude/skills` and does not
+establish `.agents/skills` as a substitute.
+
+- [OpenAI's Claude-plugin portability guide](https://developers.openai.com/plugins/guides/submit-claude-plugin)
+ distinguishes reusable skills/server implementations from host-specific
+ configuration and submission requirements. Directory submission and local
+ distribution are different paths.
+- [Codex configuration reference](https://learn.chatgpt.com/docs/config-file/config-reference#configtoml)
+ documents trusted project-scoped configuration. This supports investigating
+ native project setup; it does not prove the installed-client workflow by itself.
+- [Claude plugin manifest reference](https://code.claude.com/docs/en/plugins/manifest-reference)
+ defines separate display names, skill and MCP components, and validation.
+ Client-specific metadata belongs in the adapter, not the engine contract.
+
+These sources were checked on 7 October 2026. No portal draft, listing, account
+permission or outbound message was changed during this alignment update.
diff --git a/docs/plans/2026-10-07-private-hosting-separation.md b/docs/plans/2026-10-07-private-hosting-separation.md
new file mode 100644
index 00000000..6e123aa9
--- /dev/null
+++ b/docs/plans/2026-10-07-private-hosting-separation.md
@@ -0,0 +1,184 @@
+# Private hosted application boundary
+
+7 October 2026. Owner decision: keep the Kiln engine/package and integrations
+public; separate the official hosted application into a private Instrukt Labs
+repository. The accepted release goal authorized its creation; the owner then
+approved the verified private import's main merge. Public cleanup and deployment
+remain separate approvals. The owner separately
+approved and completed GitHub Team at $4/month for one seat, billed monthly.
+The organization API independently verifies Team with one purchased/filled seat.
+
+## Repository boundary
+
+- Existing public repository: `instruktlabs/kiln`, preserving its identity,
+ stars, issues, PRs, releases, history and MIT-licensed engine.
+- Private repository: `instruktlabs/kiln-hosted`, matching the hosting
+ package's existing name. Public product name remains **Kiln**.
+- The private repository has its own protected `main` branch. Branch protection
+ means merge rules; it does not mean hiding a branch inside the public repository.
+- Local npm, CLI, MCP and Claude Code/Codex installation remain account-free.
+- Official hosting continues to target Cloudflare and `kiln.instruktlabs.com`.
+ Repository separation does not require moving the domain, OAuth apps, provider
+ resources or user data. The public hosted service has not launched.
+
+## Scope found in the current source
+
+Inspected source: `f99f1b894cf8277077c0b1377fdc8a37a0990a28`.
+`hosting/` contains 245 tracked files, including 59 files under `src`, 80 under
+`test`, and 60 under `probe`. Most can be preserved rather than rewritten.
+These are inventory counts, not estimates of how many files need behavior changes.
+
+| Area | Destination and work |
+| --- | --- |
+| Hosted gateway, identities, accounts, tenant storage, admission and native dispatch | Private repository; preserve behavior and existing tests |
+| Hosting migrations, container definitions, private probes, deployment and recovery tooling | Private repository; preserve origin and evidence references |
+| Hosted gateway and native image workflows | Private CI, adapted to consume a pinned engine dependency |
+| SDK, CLI, local MCP, skills and local plugins | Remain public |
+| Generic SDK evaluator qualification in `scripts/hosting/` and `hosting-probe.yml` | Remain public despite their historical names; they exercise the published engine |
+| Hosted plugin manifests, public skills and connection documentation now under `hosting/plugin/` | Remain publicly distributable; relocate to the public integration tree and separate packaging from private application internals |
+| Operational records and launch qualification evidence | Future records private; retain sanitized public status and historical records without rewriting Git history |
+
+The npm 1.0.0 package's `files` allowlist does not include `hosting/`. Moving
+the hosting application therefore does not require replacing the published
+archive or renaming the npm package.
+
+## Work that makes this more than a folder move
+
+The original hosted application imported engine source directly: program storage contracts,
+Discovery and lexical indexing, input-error helpers and geometry metadata. Its
+tests and metadata generator also import `dist/mcp-engine.mjs`, and native
+TypeScript paths point at the sibling `lib` directory.
+
+Use the existing `@instruktlabs/kiln/programs`, `discovery`, material-library,
+evaluator and other appropriate public entries wherever sufficient. Review the
+remaining gaps, especially a lightweight edge Discovery interface and in-process
+MCP construction. Expose only reusable engine contracts; do not copy tool schemas
+or add Cloudflare/account logic to the engine. Any new public API requires its
+normal tests, documentation and package release qualification.
+
+The private application now installs exactly `@instruktlabs/[email protected]` through
+its own lockfile. Public exports cover most imports. Two explicit compatibility
+adapters consume shipped files for the MCP host and browser-safe Discovery because
+1.0.0 lacks those named public exports. These adapters check or pin the installed
+package identity; they do not read an adjacent source checkout. Finish the boundary
+with minimal supported engine exports in the qualified follow-up package, keeping
+Cloudflare and account logic private.
+
+## Migration sequence
+
+1. Preserve a reviewed hosting snapshot and its source attribution, tests and
+ relevant receipts locally. Record a file/hash manifest. No credentials or
+ private user data enter the source import.
+2. Create the authorized named private remote, verify private visibility and
+ membership, then import the reviewed application. Retain existing MIT notices
+ for imported code; this migration does not revoke prior licenses.
+3. Make private builds/tests independent, pin the engine input, and adapt the two
+ hosting workflows. Reuse the active Team subscription; configure and verify
+ required PR/check rules and prevent force pushes/deletion on private `main`.
+ Keep cloud credentials out of build/test CI, monitor private Actions usage,
+ and use an explicitly approved operator deployment because Team does not
+ include private environment required reviewers.
+4. Qualify the extracted application and the public package boundary. Compare
+ generated tool metadata and relevant outputs, run affected hosting and
+ installed-package checks, and scan the private import and distributable
+ outputs for secrets. Reuse unchanged prior runtime evidence; a move alone
+ does not require recreating every paid trial.
+5. Prepare one public cleanup PR to remove hosted implementation and private-only
+ workflows from the current tree, retain public integration metadata and generic
+ evaluator tests, and fix maintained links. Request main-merge approval only
+ after the private copy and builds are verified.
+6. Continue the existing hosted launch work in the private repository. Retention,
+ live OAuth, rollback, cost/load qualification and launch approval remain open;
+ repository separation does not satisfy those gates.
+
+## Verified migration checkpoint
+
+On 7 October, `C:/Users/Mattm/X/kiln-hosted` preserved the original hosting source,
+notices, toolchain and workflows with a byte-matched SHA-256 inventory. The private
+`migration/source-manifest.json` now contains 251 original-source records, including
+the unchanged renderer smoke helper. Public integration metadata and its packager
+remain public deliverables rather than private application code.
+
+Private [PR #1](https://github.com/instruktlabs/kiln-hosted/pull/1), approved at
+`1d6bd74339377fa8be9d697a292eaea0b95c16e7`, merged as
+`e84d79f15d4c143e0855bf57ea1b5709e32dd165`. The merged tree exactly matches the
+approved source. Local checks and both fresh CI platforms passed all 459 application
+tests, typechecking and builds; all three native image checks also passed. All 14
+production modules match byte-for-byte between local, Linux and Windows builds.
+The redacted import secret scan passed. The repository is verified private, with
+required PR/check rules enforced for administrators and force pushes/deletion
+disabled. Build/test CI has no repository Actions secrets.
+
+The public cleanup is prepared in an isolated worktree: remove `hosting/`,
+`hosted-gateway.yml` and `container-image.yml`; relocate public metadata to
+`plugins/kiln-hosted/` and its packager/tests to `scripts/`; retain generic engine
+evaluator qualification. Plugin packaging passes with no hosting directory present.
+Full public qualification and approval of the cleanup merge remain outstanding.
+The public default branch has not been changed by this extraction.
+
+## Public removal and history
+
+The owner explicitly chose no history rewrite and accepts the old implementation
+remaining in public history. Kiln itself stays public, preserving stars, forks,
+issues, PRs, contributor history and releases in the existing repository.
+Use a normal cleanup commit and PR; do not rewrite history, force-push, delete
+release tags or change the public repository's visibility. Existing contributors
+continue with the same repository and normal pulls. Preserve source attribution
+and existing MIT notices. Future hosted implementation changes belong in the
+private repository; historical public copies are not made confidential by removal.
+
+This matches GitHub's documented [file deletion behavior](https://docs.github.com/en/repositories/working-with-files/managing-files/deleting-files-in-a-repository).
+GitHub documents [history rewrite side effects](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository),
+including changed commit hashes and disruption to pull requests and clones. This
+migration has no requirement to incur those effects. A discovered credential
+exposure would be handled separately by revocation/rotation and appropriate cleanup.
+
+Before public cleanup, the repository API returned the unchanged public repository
+ID `1278326592` (`R_kgDOTDG3QA`), default branch `main`, 244 stars and 19 forks.
+Counts can grow while work continues; this is a preservation checkpoint, not a
+requirement to freeze community activity. No community PR will be closed or edited
+as part of the hosting removal.
+
+## Existing release PRs and trials
+
+- #153 is already merged; its public history remains intact.
+- Preserve #154 and #155 source/evidence in the private migration before closing
+ them as superseded. Do not merge further hosted implementation just to move it
+ again. Their closure still requires the owner's authorization.
+- #156 contains both public setup/isolation work and some hosted changes. Separate
+ those paths so public work is retained without publishing future hosting work.
+- Keep frozen private trial `37c962e` and onboarding candidate `76c869a` unchanged.
+ Their unanswered spending/authentication handoffs remain separate. Reconcile
+ their execution location and compare any affected bundle bytes before running;
+ the repository decision does not authorize either trial.
+
+## Complexity, limits and cost
+
+This is a moderate repository/dependency migration, not a rewrite of hosting.
+The owner set a target of completing the migration within a focused day in this
+development cycle. Prioritize extraction, independent builds/tests and the public
+cleanup; reuse existing code and qualification evidence. The main uncertainty is
+the edge/MCP package boundary. Surface a concrete problem early if it threatens
+that target rather than silently expanding the architecture. Owner/provider waits
+and the remaining hosted launch work stay visible in the overall release goal.
+
+The [updated execution goal](2026-10-06-v1-execution-goal.md) integrates this
+migration into the full end state and records the completed GitHub Team upgrade.
+
+Instrukt Labs now reports **GitHub Team**, one seat purchased and filled. The
+owner completed the monthly upgrade after checkout showed a $4/month base before
+tax/usage. This enables protection rules for branches in the separate private
+repository. Private Actions usage has plan-dependent allowances; monitor it rather
+than treating the subscription as an unlimited CI budget. Production deployment
+access is not enabled by the plan upgrade. Sources checked 7 October:
+
+- [Repository visibility](https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories)
+- [Protected branches](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches)
+- [Actions billing](https://docs.github.com/en/actions/concepts/billing-and-usage)
+
+Removing files from the public default branch does not erase old commits, public
+PRs, forks or existing copies. Preserve public history and existing licenses;
+do not claim retroactive confidentiality. This split protects future unpublished
+hosting development. The separately authorized Team upgrade and private repository
+import are complete. The existing public repository remains public; public cleanup
+and the hosted launch are still pending.
diff --git a/docs/releasing.md b/docs/releasing.md
index 3cdd24bf..690b5b34 100644
--- a/docs/releasing.md
+++ b/docs/releasing.md
@@ -1,10 +1,17 @@
# Publishing Kiln 1.0
This is the maintainer runbook for `@instruktlabs/kiln`. npm publishing access is
-configured and `1.0.0-rc.1` is public under `next`; stable `1.0.0` has not been
-published. Development, registry publication,
+configured and stable `1.0.0` is published under `latest`. Follow-up changes need
+a new version and the qualification process below. Development, registry publication,
hosted deployment and directory acceptance have separate evidence requirements.
-See the [v1 execution record](reviews/2026-10-06-v1-execution.md) for current status.
+See the [release status](reviews/2026-10-07-release-status.md) for current status.
+
+The official hosted application has its own private `instruktlabs/kiln-hosted`
+repository, dependency lockfile, CI and deployment runbooks. Its source and
+credentials do not belong in public package archives or artifacts. This public
+repository retains the npm release workflow, local integrations, public hosted
+plugin metadata and generic engine qualification. A private application merge
+does not authorize a package release or public service deployment.
## Qualify the candidate
diff --git a/docs/reviews/2026-10-06-v1-execution.md b/docs/reviews/2026-10-06-v1-execution.md
index 2712a3e8..43b3d9a6 100644
--- a/docs/reviews/2026-10-06-v1-execution.md
+++ b/docs/reviews/2026-10-06-v1-execution.md
@@ -1814,7 +1814,7 @@ Only the named test containers were removed; the qualified local image is retain
## Private Cloudflare availability candidate
-Prepared the bounded [probe and teardown plan](../../hosting/probe/README.md).
+Prepared the bounded [probe and teardown plan](https://github.com/instruktlabs/kiln/blob/f99f1b894cf8277077c0b1377fdc8a37a0990a28/hosting/probe/README.md).
It has no public HTTP routes or external bindings, uses five fixed sequential
jobs, and atomically claims its run once. The first failure stops the batch;
interrupted claims do not automatically spend again. The production image is
@@ -2304,7 +2304,7 @@ before device startup. The rebuilt coordinator image
passes readiness, current/legacy MCP, hostile-header denial and failure without
private services. Both install the exact published stable archive, retain their
dependency inventories and remove their local test containers. Procedures and
-receipt paths are in [the image guide](../../hosting/container/README.md).
+receipt paths are in [the image guide](https://github.com/instruktlabs/kiln/blob/f99f1b894cf8277077c0b1377fdc8a37a0990a28/hosting/container/README.md).
The thirty-second render deadline is a candidate setting informed by the earlier
13,286 ms fixed provider fixture, not a measured production SLO. No additional
@@ -2363,7 +2363,7 @@ the final hosted behavior is verified, as requested.
## Integrated provider candidate prepared
The fixed ten-step sequence is prepared in
-[the integrated trial record](../../hosting/probe/INTEGRATED.md): nine admitted
+[the integrated trial record](https://github.com/instruktlabs/kiln/blob/f99f1b894cf8277077c0b1377fdc8a37a0990a28/hosting/probe/INTEGRATED.md): nine admitted
MCP requests plus quota rejection, with a durable ceiling of seventeen VM starts.
The actual private Worker, admission service, diagnostic allowance and R2 evidence
path now pass local workerd tests, including replay after durable-object eviction
@@ -2818,7 +2818,7 @@ cause is not established; no test was weakened or automatically retried in code.
Seventeen of eighteen checks have passed; the root Linux community-exporter step
is still running at this checkpoint. New preparation changes require their own CI.
-The [deployment guide](../../hosting/DEPLOYMENT.md) records the dependency order,
+The [deployment guide](https://github.com/instruktlabs/kiln/blob/f99f1b894cf8277077c0b1377fdc8a37a0990a28/hosting/DEPLOYMENT.md) records the dependency order,
secret/migration requirements, recovery verification and remaining launch gates.
The example manifest deliberately contains invalid identifiers and qualification
policy examples, not public quota decisions. Actual resource ownership, image
@@ -2898,7 +2898,7 @@ one-minute evaluation and five-minute windows with hourly repeat proposals.
They are not enabled and have no destination. Queries use the newer Analytics SQL
API dialect, whose sampling rules differ from the legacy Analytics Engine API.
Live catalog access, query validation, thresholds and notification delivery remain
-unverified. [OPERATIONS.md](../../hosting/OPERATIONS.md) records the schema,
+unverified. [OPERATIONS.md](https://github.com/instruktlabs/kiln/blob/f99f1b894cf8277077c0b1377fdc8a37a0990a28/hosting/OPERATIONS.md) records the schema,
limitations, retention, volume assumptions and deployment qualification steps.
Focused observation and deployment regressions failed before implementation.
@@ -2978,7 +2978,7 @@ Production dependency checks exclude every test/probe helper from all bundles.
Evidence is under `.cache/gateway-preflight-*.log`. All eighteen CI checks on
preceding head `e421455` now pass; this change needs its own exact-source CI.
-[GATEWAY_PREFLIGHT.md](../../hosting/probe/GATEWAY_PREFLIGHT.md) states the scope
+[GATEWAY_PREFLIGHT.md](https://github.com/instruktlabs/kiln/blob/f99f1b894cf8277077c0b1377fdc8a37a0990a28/hosting/probe/GATEWAY_PREFLIGHT.md) states the scope
and remaining work: a bounded private operator and updated native/material/image
phase, explicit VM/evidence budgets, complete cleanup, then renewed trial approval.
Live OAuth/account actions/deletion, real scheduled recovery, retention, load,
@@ -3029,7 +3029,7 @@ completion cannot resume the failed sequence.
All 385 hosted tests, three typechecks, thirteen production builds, root lint and
redacted probe-source/bundle scans pass locally. Logs are under
-`.cache/lifecycle-*.log`. [NATIVE_LIFECYCLE.md](../../hosting/probe/NATIVE_LIFECYCLE.md)
+`.cache/lifecycle-*.log`. [NATIVE_LIFECYCLE.md](https://github.com/instruktlabs/kiln/blob/f99f1b894cf8277077c0b1377fdc8a37a0990a28/hosting/probe/NATIVE_LIFECYCLE.md)
records scope and limitations. Wiring the unchanged production gateway/tenant/
admission services to diagnostic budget wrappers, the private operator, exact
image/config verification and full cleanup is next; only then is another paid
diff --git a/docs/reviews/2026-10-06-v1-security-review.md b/docs/reviews/2026-10-06-v1-security-review.md
index 319e1d39..4768c48b 100644
--- a/docs/reviews/2026-10-06-v1-security-review.md
+++ b/docs/reviews/2026-10-06-v1-security-review.md
@@ -234,6 +234,34 @@ Public admission/rate controls, global account/storage bounds, provider linking,
account deletion, live confirmation, deployed revocation and recovery remain
outstanding. Local tests and a secret scan cannot substitute for those gates.
+## 7 October candidate refresh
+
+The focused sign-in/account review at `2087faa` checked explicit identity linking,
+primary account/epoch validation, one-use provider-bound callbacks, consent and
+browser-origin checks, and separation of provider credentials from tenant/native
+modules. This pass did not establish a new account-flow defect; real provider
+sign-in and deployed revocation remain unqualified. Existing CI evidence was reused
+rather than rerunning the unchanged functional suite.
+
+Gitleaks 8.30.1 was rerun with full redaction, default rules and inline allow
+comments ignored. No custom rule configuration or ignore file was present. All
+four reports are empty:
+
+| Current input | Coverage |
+| --- | --- |
+| Exact `1.1.0-dev.1` package archive `ce0d7e18…878f` | 954 validated archive entries, extracted before scanning; 24,141,849 scanned bytes |
+| Generated local plugin `1.1.0-dev.1` | All eleven provenance-listed files hash-verified; 53,995 scanned bytes including provenance |
+| Rebuilt hosted output | Fourteen runtime/maintenance modules and build records; 5,250,824 scanned bytes; all bundle digests checked and the module bytes retained |
+| Reachable history after stable `fda71ac` through `2087faa` | 103 commits; 2,534,626 scanned bytes |
+
+Retained evidence: `.cache/security-candidate-2087faa/receipt.json`, the four
+redacted scan reports/logs, extracted archive, plugin and hosted module copies.
+Only documentation differed from the recorded source while building; all actual
+build dependency-boundary checks passed. This closes the stale artifact-scan
+check for these bytes, not final image/deployed-configuration review or proof
+against unknown secret formats. No provider credential was read or changed and
+no service was deployed.
+
## Acceptance
The integrated branch now also covers durable compute admission and authenticated
diff --git a/docs/reviews/2026-10-07-claude-distribution-audit.md b/docs/reviews/2026-10-07-claude-distribution-audit.md
new file mode 100644
index 00000000..a964b06e
--- /dev/null
+++ b/docs/reviews/2026-10-07-claude-distribution-audit.md
@@ -0,0 +1,178 @@
+# Claude distribution audit, October 7, 2026
+
+Status: analysis for owner alignment. No submission, naming change, account grant,
+compliance acceptance or further outreach is authorized by this report. The owner
+asked to hold Claude submission work while reviewing the intended experience.
+
+The root agent checked the live portal and sent-email thread. An independently
+delegated agent inspected packaging, retained installation evidence and current
+Anthropic documentation. Source audited: `663ff4ae6220c3bf88b7d653429b9d116e53f926`.
+This report changes documentation only; no plugin implementation was changed.
+
+## What actually happened
+
+The signed-in Claude directory dashboard currently shows **0 submissions** and
+**Nothing submitted yet**. The unfinished form says **Draft saved in this tab**.
+It is not a saved submission in the dashboard, an application under review or an
+accepted listing. The form still points at `plugins/kiln-engine` on
+`codex/v1-native-dispatch`, validated at `4b3dc62`.
+
+Validation did send the public source location to Anthropic for retrieval and
+scanning. That preparation is real external activity even though no final
+submission occurred. The form reports five warnings and two policy holds. The
+five warnings concern the icon and four directory-only URL fields; their details
+explicitly say the directory reads them and no action is needed. The two
+credential-related policy holds are unresolved. The current listing preview
+shows **Kiln Engine**, **1 skill**, **no MCP servers**, and **Claude Code only**.
+All four compliance acknowledgments remain unchecked and Next is disabled.
+
+One clarification email was sent to `[email protected]` after the owner's
+explicit approval. Subject: **Local plugin executable declaration and publisher
+ownership for Kiln**. It was sent from the maintainer's personal Gmail account,
+signed Matthew Kissinger / Instrukt Labs, with no attachments. It explained the
+public installer and asked about the executable acknowledgment, the two scanner
+holds, and ownership through a personal Claude account. It did not submit a
+plugin or request publication. The thread contains an automated support-ticket
+acknowledgment and no substantive answer as of this audit.
+
+The earlier dated preflight record ends with an unsent email draft. That describes
+its earlier state, not the later approved send. The exact sent copy is retained
+locally for owner review, outside tracked documentation. Future outreach should
+show the owner the final text, sender, recipient and purpose before sending.
+
+## What each package contains
+
+| Delivery | Contents and limits |
+| --- | --- |
+| Published npm `@instruktlabs/[email protected]` | Six maintained skills: setup, author, refine, QA, compose and batch, plus the engine/CLI/MCP runtime. |
+| Local plugin candidate 1.0.1 | One setup skill, reference, real installer, exact engine pin, manifests, icon, privacy notice and supporting files. |
+| Default generated workspace | `kiln-author-asset`, `kiln-refine-asset`, `kiln-qa-asset`, registered for the chosen harness, plus one local `kiln_workspace` MCP server. |
+| Optional workspace workflows | `kiln-compose-scene` and `kiln-batch-dispatch`, selected with `--skills compose,batch`. |
+| Hosted OpenAI draft | Remote MCP definition and hosted authoring guidance in OpenAI's format. |
+| Hosted Claude integration | Claude-format bundle and connector listing are not implemented or qualified yet. |
+
+The local packager's check passed against maintained source. The published engine
+installation inspected by the audit contains all six skills. Therefore the single
+listed skill is intentional, not a failed npm publication or missing-file defect.
+The portal only inventories the plugin folder, not what its installer later adds.
+
+Source: `scripts/package-local-plugin.mjs`, `scripts/create-workspace.mjs`,
+`package.json`, and `plugins/kiln-engine/README.md`.
+
+## Findings
+
+1. **High: the current candidate does not deliver the intended Claude apps
+ experience.** The real top-level `bin/` executable excludes Claude apps and
+ Cowork, as both the live portal and [Anthropic's component
+ documentation](https://code.claude.com/docs/en/plugins/components#executables)
+ state. Adding more skills cannot make the native installer work there. Moving
+ it to hide its classification would not establish compatibility.
+
+2. **High: hosted Claude distribution is a separate unfinished deliverable.**
+ Reuse the Cloudflare service and maintained guidance, but generate Claude's
+ `.claude-plugin/plugin.json` and `.mcp.json` wrapper. The current OpenAI ZIP
+ cannot be submitted unchanged. Anthropic requires the owned remote MCP to be
+ submitted as a connector as well as any plugin bundle referencing it. Matching
+ owner and endpoint enable pairing. See [plugin
+ structure](https://claude.com/docs/plugins/build) and [directory
+ publishing](https://claude.com/docs/directory/publish). Real authentication,
+ asset persistence, tool use and downloads must be checked in each advertised
+ client before claiming support.
+
+3. **High: publisher ownership and an execution acknowledgment remain open.**
+ The compliance form names Matthew Kissinger; manifest authorship says Instrukt
+ Labs. The first submitting Claude organization holds the repository-folder
+ listing. GitHub organization ownership does not select it, and later transfer
+ has not been established. The form's acknowledgment disallows execution outside
+ declared MCP servers, while setup demonstrably runs npm and the workspace
+ generator before that MCP exists. Do not accept an inaccurate statement.
+ Clarification or an appropriate alternate distribution path is needed. See
+ [submission requirements](https://claude.com/docs/plugins/submit).
+
+4. **Medium: the branding was a choice, not a demonstrated namespace necessity.**
+ There is no evidence that `kiln` is taken in Anthropic's directory. npm's
+ occupied unscoped name is unrelated. Claude supports separate `name` and
+ `displayName` fields; the current Claude manifest has no explicit display name.
+ Own-marketplace naming is scoped, while public directory checks also compare
+ names across organizations. `kiln@instruktlabs` is a possible local naming
+ shape, not a verified available public directory name. See the [manifest
+ reference](https://code.claude.com/docs/en/plugins/manifest-reference) and
+ [directory naming checks](https://claude.com/docs/plugins/pre-submission-checklist).
+
+5. **Medium: the setup-only design creates an onboarding cost.** Installation
+ provides setup first. Users create/select a persistent workspace and start
+ their coding agent there before authoring. This keeps assets out of disposable
+ plugin caches and avoids duplicate server/skill registration. The listing
+ should explain that sequence and name the default and optional skills. A
+ direct-authoring plugin would be a deliberate UX redesign, not a packaging fix.
+
+6. **Medium: candidate qualification and public installation differ.** GitHub
+ `main` currently serves local plugin 1.0.0, while the preflight candidate is
+ 1.0.1 on a development branch. Its new privacy URL on `main` returns 404 today.
+ The prior isolated 1.0.1 checks prove installation, generated workspace,
+ discovery and direct MCP operations. Their receipt explicitly records zero
+ model turns; they do not prove a normal Claude conversation follows the whole
+ onboarding workflow. Qualify that workflow on the exact released candidate.
+
+7. **Medium: review the boundary between remote API facts and behavioral
+ instructions.** Section 2F of the [Directory
+ Policy](https://support.claude.com/en/articles/13145358-anthropic-software-directory-policy)
+ restricts dynamically retrieved behavioral instructions. The hosted skill's
+ references are bundled files, and hosted tools do not expose the optional
+ `kiln_skill_resource` tool. However, `src/discovery/service.ts` includes workflow
+ guidance and `src/discovery/recipes.ts` includes imperative review steps in
+ remote catalog results. These deserve a specific policy review. Prefer putting
+ workflow guidance in the reviewed skill bundle while retaining remote helper
+ signatures, schemas, constraints and examples. This is an identified
+ interpretation/qualification gap, not a finding that all remote documentation
+ violates policy.
+
+The scanner holds are not proof of credential theft. Inspection shows that its
+flagged `pin` is a public package/version pair. However, npm does inherit normal
+caller environment and configuration. Do not claim credentials are universally
+stripped or dismiss the vendor's hold as resolved by local tests.
+
+Kiln evaluates assistant-authored JavaScript into geometry/GLB and renders views;
+the hosted runtime is not itself a standalone image-generation model service.
+Describe this distinction accurately when applying Directory Policy section 4B.
+Its design-workflow exception may be relevant, but does not guarantee acceptance.
+
+## Recommended alignment and sequence
+
+1. The owner selected **Kiln**, if available, as the product brand and **Instrukt
+ Labs** as publisher during this audit. Keep the npm package unchanged. Use
+ the LLC's exact registered name in legal disclosures and legal-entity fields;
+ the public publisher label can remain Instrukt Labs. The exact registered
+ punctuation has not been independently verified. Decide installation slugs
+ separately; retaining the
+ existing local slug avoids an immediate migration, while renaming requires
+ an update plan. Public directory availability still needs preflight.
+2. Describe two explicit experiences: local workspaces for coding agents, and
+ hosted Kiln for Claude apps and compatible coding clients. Retain the useful
+ workspace skill boundary unless the owner chooses a broader onboarding redesign.
+3. Resolve the long-term Claude publisher and the executable acknowledgment
+ before creating an owned submission. No additional Claude subscription or
+ future ownership transfer is assumed.
+4. Finish the hosted service and Claude-specific wrapper, then run actual client
+ workflows and review public privacy/support links. Prepare a connector record
+ and a paired hosted plugin record from the intended publisher.
+5. Present one owner-reviewable dossier for each candidate: visible name, slug,
+ exact source/version, supported clients, installed skills/tools, setup actions,
+ outbound services, privacy, publisher, screenshots, unresolved findings and
+ proposed submission settings. Keep automatic publication off for launch.
+6. Obtain approval on that concrete dossier before submission or more outreach.
+ Track preparation, submission, review, approval and publication separately.
+
+The branding preference is aligned, subject to availability. The remaining
+sequence is a recommendation, not an approved rename or authorization to submit.
+
+## Subsequent owner alignment
+
+After this audit, the owner clarified that Kiln must remain agent and harness
+agnostic, with seamless Claude Code compatibility through thin integrations or
+shared architectural improvements. The owner selected support for both existing
+projects and new workspaces through the question tool. The earlier setup-only
+versus Claude-specific-redesign question is superseded. See the
+[local setup plan](../plans/2026-10-07-agnostic-local-setup.md) for the shared
+extension and qualification requirements. This does not close the findings above,
+change the published package, or authorize further directory activity.
diff --git a/docs/reviews/2026-10-07-directory-preflight.md b/docs/reviews/2026-10-07-directory-preflight.md
index dc2494ae..4b3d1db8 100644
--- a/docs/reviews/2026-10-07-directory-preflight.md
+++ b/docs/reviews/2026-10-07-directory-preflight.md
@@ -139,8 +139,10 @@ and produces a deterministic ZIP. Its receipt deliberately remains
`submissionReady: false`; demo URL, live case receipts, immediately usable review
access, publisher/domain verification and portal validation remain outstanding.
The draft README must be updated to reflect actual availability before submission.
-Use the [maintainer command](../../hosting/README.md#public-plugin-preparation)
-instead of uploading incomplete source files.
+After the repository split, use the relocated
+[maintainer command](../../plugins/kiln-hosted/README.md#source-and-packaging-boundary)
+instead of uploading incomplete source files. The public packager no longer needs
+the private application checkout; this relocation does not approve a submission.
The gateway now serves a draft `/terms` page, linked from the public, consent and
account footer. It follows the owner's choices: free access within quotas, no
diff --git a/docs/reviews/2026-10-07-hosted-recovery-preparation.md b/docs/reviews/2026-10-07-hosted-recovery-preparation.md
new file mode 100644
index 00000000..f97158ba
--- /dev/null
+++ b/docs/reviews/2026-10-07-hosted-recovery-preparation.md
@@ -0,0 +1,118 @@
+# Hosted recovery preparation, October 7, 2026
+
+The maintenance gateway and [recovery runbook](https://github.com/instruktlabs/kiln/blob/f99f1b894cf8277077c0b1377fdc8a37a0990a28/hosting/RECOVERY.md) are
+prepared separately from the frozen private operations candidate `37c962e`.
+This work does not deploy a service, restore data, create resources or expand
+that trial's scope. PR #153 and the separate operations trial remain subject to
+their outstanding owner approvals.
+
+The new gateway rejects every HTTP route with 503 while retaining the exact
+production scheduled deletion/health handler. It does not accept cookies, bearer
+tokens or provider callbacks during maintenance. Offline preparation emits only
+this gateway, preserving binding identities and secret names while omitting
+images, other Workers and migration files. It deliberately does not automate a
+live version change. The generated no-route configuration must not be applied
+over a live public gateway; an approved code-only operation must preserve live
+routes, current secret references and external resources.
+
+## Validation
+
+- Observed focused failures before implementation: two missing-entry tests and
+ six preparation/dependency-boundary failures.
+- All 445 hosting tests passed, including actual workerd rejection of HTTP paths
+ and methods with absent bindings and forbidden outbound access. The final
+ focused rerun also checks the exact production token/download path names.
+- All three hosting TypeScript configurations passed; all fourteen bundles built.
+- Root frozen dependencies and runtime bundles rebuilt; hosting clean install
+ reported zero known vulnerabilities. Root lint passed across 1,082 files.
+- Gitleaks scanned the hosting source with full redaction and no allowlist bypass;
+ no matches were found. No secret values were added to configuration or receipts.
+
+Local logs are `.cache/maintenance-red.log`,
+`.cache/maintenance-config-red.log`, `.cache/maintenance-green-final.log`,
+`.cache/recovery-tests.log`, `.cache/recovery-typecheck.log`,
+`.cache/recovery-build.log`, `.cache/recovery-lint.log` and
+`.cache/recovery-secrets.json`. These are local evidence, not deployed proof.
+
+A subsequent local transition test switches the actual gateway from normal code
+to maintenance and back inside the same workerd deployment, keeping storage
+identities and contents. The scheduled handler finishes the first account's
+already-requested deletion during maintenance; after restoring normal code the
+old token stays denied and the other account's primary record, valid access and
+exact saved source remain intact. The five-test operations suite passes in
+`.cache/maintenance-transition-test.log`. The expanded full hosting suite passes
+all 446 tests in `.cache/recovery-transition-full-tests.log`; all three typechecks,
+fourteen builds and root lint also pass in the `recovery-transition-*` logs. The
+scheduled invocation is explicit and local; this is not provider rollback, Cron
+or data-restore evidence.
+
+## Security findings and remaining qualification
+
+Cloudflare documents code rollback separately from connected storage. D1 Time
+Travel and SQLite DO recovery operate independently; R2 durability does not
+establish recovery of application-deleted bytes. An account database rewind can
+undo an unlink, deletion or authorization epoch. A DO rewind can restore retired
+tenant state, tickets or usage counters. The runbook therefore requires preserving
+current security state and proving reconciliation before reopening access.
+
+Maintenance keeps deletion Cron alive for code repair. A data restore instead
+requires verified background-write quiescence, current-state preservation and an
+undo path. The repository does not yet provide or qualify a consistent automated
+cross-store restore or artifact backup. No recovery time/data-loss guarantee is
+asserted, and the backup/restore launch gate remains open.
+
+Real maintenance activation, compatible rollback, provider recovery, revocation
+preservation, saved-byte integrity and cleanup need an independently prepared
+bounded trial. The pending operations trial tests retention and Cron recovery,
+not these additional operations. See the runbook's official sources and the
+[deployment gates](https://github.com/instruktlabs/kiln/blob/f99f1b894cf8277077c0b1377fdc8a37a0990a28/hosting/DEPLOYMENT.md#ordered-deployment-and-launch-gates).
+
+## Cloudflare CLI build-output qualification
+
+All 25 CI checks passed on `663ff4a`. A subsequent offline `cf workers versions
+create --prebuilt --dry-run` exposed a preparation defect missed by the separate
+Wrangler check: the Build Output Specification requires `workers/default`, while
+the multi-Worker preparer had written only a `workers/gateway` entry. Selecting
+the gateway with the CLI's worker option does not bypass that reader requirement.
+
+The gateway now occupies the default directory in every generated topology.
+Deployed Worker names, receipt roles, bundle content, resource bindings, quotas
+and deployment order are unchanged. A shared path helper keeps Wrangler's main
+path aligned. Existing frozen artifacts and the pending trial at `37c962e` are
+not rewritten or replaced by this fix.
+
+Four tests failed on the original output through the actual Cloudflare
+`readBuildOutput` implementation, then passed after the change. The reader is
+pinned as a private development dependency at `@cloudflare/build-output-utils`
+0.8.5, using the same config 0.23.0. It is not an engine or hosted runtime
+dependency. All 20 focused tests, all 450 hosted tests, three typechecks,
+fourteen builds and root lint pass. Installation reports no known vulnerabilities.
+
+The corrected maintenance candidate also passed the real `cf` version-upload
+dry-run, with no upload or deployment. Its synthetic D1/KV placeholders do not
+describe provisioned resources. It still binds the production tenant class, so
+it must not be deployed over the distinct private operations topology. That
+working-tree candidate is dry-run evidence only; exact clean-source preparation
+and fresh CI remain required for a later deployment candidate.
+
+Logs: `.cache/build-output-{red,green,full-tests,typecheck,build,lint}.log`,
+`.cache/maintenance-cf-version-dry-run.log` (the original failure), and
+`.cache/maintenance-cf-version-fixed-dry-run.log` (the corrected pass).
+
+### Clean-source follow-up
+
+All 25 CI checks passed on the build-output fix at `c9bf266`. After that fix and
+the separate local-setup prerequisite were committed, a fresh maintenance
+preparation at `253cf94b6c2f9e54e13b973ef26ec9fd08cb684b` recorded
+`sourceDirty: false`. The real `cf` 1.0.0-beta.12 version-upload dry-run succeeded.
+The gateway bundle remains byte-identical, SHA-256
+`d17dc921fd23af67bb4ae27b740ad432a38fba24a43b2dc36ea2cdf9ebbc7138`.
+
+This is still offline qualification with synthetic resource identifiers. No
+version was uploaded, resource provisioned or service deployed. The production
+tenant-class warning above still applies. Preserve live binding identities and
+settings through a separately prepared and approved provider rehearsal.
+
+Evidence: `.cache/maintenance-candidate-253cf94/`,
+`.cache/maintenance-253cf94-prepare.log` and
+`.cache/maintenance-253cf94-cf-dry-run.log`.
diff --git a/docs/reviews/2026-10-07-local-onboarding-qualification.md b/docs/reviews/2026-10-07-local-onboarding-qualification.md
new file mode 100644
index 00000000..3dcd197a
--- /dev/null
+++ b/docs/reviews/2026-10-07-local-onboarding-qualification.md
@@ -0,0 +1,101 @@
+# Local client onboarding qualification
+
+Status: candidate and fixtures prepared; model sessions have not run.
+
+## Candidate and current evidence
+
+Use source `76c869aa7c8637b222b5bdf956fd1e70c3f9d83a`, with the exact
+`@instruktlabs/[email protected]` archive downloaded from
+[CI run 37668542892](https://github.com/instruktlabs/kiln/actions/runs/37668542892).
+Its SHA-256 is
+`98407508d8ec599189851aa0bd8b86313ac3abbd25e6337ac97f8510cc72215b`.
+This is an unpublished development candidate, not a replacement for stable 1.0.0.
+
+The archive's plugin inventory verifies. Claude Code 2.1.287 and Codex CLI
+0.160.0 both installed that candidate through their native marketplace commands
+in separate temporary client profiles. The fixture marketplace has a private
+test name; public naming and directory submissions remain on hold.
+
+Codex's native application server sees one setup skill, the existing owner skill,
+and only the synthetic owner's MCP server before setup. It sees no author/refine/QA
+skills prematurely. The owner's MCP server responds correctly, and all seven
+existing-project baseline files remain unchanged. These checks used no model
+credentials or model conversations. System skills supplied by Codex are present
+and are recorded in the private receipt; this is not a claim of a bare model.
+
+A separate attempt to load the plugin using only per-invocation marketplace and
+enablement settings did not install or discover its setup skill. The correctly
+parsed marketplace appeared as available but uninstalled. That shortcut is not
+used as onboarding evidence. Use the successfully installed isolated profile;
+do not copy authentication files or change the owner's ordinary client settings.
+
+Private preparation and discovery receipts are in
+`.cache/onboarding-76c869a-{preparation,fixture-checks,discovery}.json`. Earlier
+failed per-invocation attempts are retained separately. Fixtures live outside the
+engine checkout under a dedicated temporary directory recorded in those receipts.
+The separate `.cache/onboarding-76c869a-installed-integrity.json` receipt verifies
+all eleven inventoried files in each native installed cache against the exact
+archive's plugin, with no model calls. It excludes the unsuccessful shortcut.
+
+## Bounded live sequence awaiting approval
+
+Each case has two sessions: setup, then a restarted session in the resulting
+project. Run sequentially and review each result before proceeding.
+
+| Case | Setup | After restart |
+| --- | --- | --- |
+| Claude new | Select the installed setup skill and create a workspace | Discover the live engine, create/review/save a matte blue crate, export source and GLB |
+| Claude existing | Adopt a project with owner instructions, MCP configuration and a skill | Perform the same asset flow and verify preservation |
+| Codex new | Select the installed setup skill and create a workspace | Perform the same live tool and delivery flow |
+| Codex existing | Adopt the populated fixture | Perform the same asset flow and verify preservation |
+
+The prompts identify the desired result, reviewed archive, runtime-data directory,
+preservation requirements and read-only preview. They do not supply asset source.
+Setup and tool use must come from the client and its installed skill. The helper's
+reviewed `--archive` option is required because this version is unpublished.
+
+Proposed allowance: four Claude sessions, each with a $1 client-estimated limit
+and 20-turn limit, plus four sessions using the owner's existing Codex Pro access.
+Each process has a ten-minute deadline and bounded retained output. Claude's cost
+limit is an estimate, not a provider billing hard cap. Stop at the first failure,
+budget/permission denial or missing evidence; do not automatically retry.
+
+The prepared driver is `.cache/run-onboarding-case.mjs`; without `--run-live` it
+only writes the command plan. All eight command plans and its syntax check pass.
+No live invocation has been authorized or performed by this checkpoint.
+
+Claude uses the existing API credential only when an approved session starts,
+with its isolated client profile. Its child tools may inherit that credential;
+the test must not claim universal environment stripping. Other provider/cloud
+credentials are not inherited. npm uses empty configuration files and a fixture
+cache. No credential values are written into command plans.
+
+The Codex test profile still needs the owner's normal browser sign-in. That is
+separate from the existing desktop login. The driver checks login status before
+starting a session and never copies an authentication file. Fixture project trust
+and server-specific MCP choices are scoped to the test profiles/invocations.
+
+Automatic client permission review remains enabled; permission bypass flags are
+not used. Unattended runs do not demonstrate the interactive project/MCP trust
+dialog. Record that limitation and check the user-facing trust flow separately.
+
+## Acceptance evidence
+
+- Exact installed engine and plugin bytes match the qualified archive and pin.
+- The model selects the installed setup skill, previews and applies setup without
+ replacing unrelated files, instructions, skills or configuration.
+- The restarted client discovers one `kiln_workspace` and the expected skills;
+ the original MCP server and skill remain available in existing projects.
+- Actual tool traces show discovery, authoring, image delivery, review, saving
+ and export. Report the selected model, client version, cost/usage and inherited
+ configuration. Model claims alone do not prove completion or image quality.
+- Inspect the saved revision, source and exported GLB independently. Compare
+ owner-file hashes and retained MCP entries against their baselines.
+- CPU views are geometry evidence. This matte fixture does not establish material
+ fidelity or replace the separate software-rendering qualification.
+- Retain failed results and next steps. Terminal process exit alone is not success.
+
+Source basis: [Claude CLI reference](https://code.claude.com/docs/en/cli-reference),
+[Codex configuration reference](https://learn.chatgpt.com/docs/config-file/config-reference),
+and [Codex noninteractive mode](https://learn.chatgpt.com/docs/non-interactive-mode),
+checked on 7 October 2026. This check publishes, deploys and submits nothing.
diff --git a/docs/reviews/2026-10-07-native-preflight-alignment.md b/docs/reviews/2026-10-07-native-preflight-alignment.md
new file mode 100644
index 00000000..156b669e
--- /dev/null
+++ b/docs/reviews/2026-10-07-native-preflight-alignment.md
@@ -0,0 +1,235 @@
+# Native preflight and hosted execution boundaries
+
+7 October 2026. This records the exact failing check and the next validation
+change to prepare. No workflow, isolation restriction or launch requirement was
+changed by this review.
+
+## Current failure
+
+[Run 37668543023](https://github.com/instruktlabs/kiln/actions/runs/37668543023)
+tested source `76c869aa7c8637b222b5bdf956fd1e70c3f9d83a`. Its retained archive
+matches the package CI archive exactly:
+`98407508d8ec599189851aa0bd8b86313ac3abbd25e6337ac97f8510cc72215b`.
+
+The downloaded `native-hosting-preflight` artifact confirms:
+
+- The non-root image built and ran as UID 1000 with Node 22.23.3.
+- Bubblewrap 0.12.0 is installed. Both the fixed `unshare` diagnostic and the
+ Bubblewrap readiness launch return permission errors while creating namespaces.
+- The engine receipt fails at `isolation`, with code `wrapper-launch`. Only the
+ preceding host check completes. No evaluated asset or fallback output exists.
+- The same run's separate trusted renderer fixture passes six views across the
+ three backdrops, identifying Mesa/llvmpipe software Vulkan. This does not prove
+ untrusted-source isolation.
+- The host exposes enabled unprivileged-user-namespace settings and enabled
+ AppArmor user-namespace restriction. These values alone do not identify which
+ policy layer denied this launch. No policy relaxation was attempted.
+
+The retained local evidence is `.cache/hosting-preflight-76c869a/receipts/`,
+including provenance, namespace diagnostics, the failed isolation receipt and
+the passing renderer receipt. This is a supported conclusion about that specific
+GitHub Docker run, not an unexplained native-rendering failure.
+
+## Two explicit execution paths
+
+| Path | Boundary | Current evidence |
+| --- | --- | --- |
+| SDK nested isolated evaluator | Host supports the required Bubblewrap namespaces and all ten readiness invariants | This Docker host does not meet the prerequisites; the evaluator refuses to run |
+| Cloudflare hosted evaluator | Separate fresh VM per admitted evaluation/render, controlled network and lifetime outside that VM | Earlier approved private trials qualify their exact image/controller pairs; final launch and recovery gates remain open |
+
+`scripts/hosting/run-native-qualification.mjs` tests the first path through the
+installed package. Its readiness requirement remains meaningful for an embedding
+that selects this adapter.
+
+Production `hosting/container/serve.mjs` explicitly calls
+`loadContainerMcpRuntime()`. `hosting/src/native-mcp.ts` separately defines the
+nested `loadNativeMcpRuntime()` and does not select a fallback when its readiness
+fails. The hosted tests check refusal of an unavailable nested boundary and
+failure when the explicit remote evaluator is unavailable.
+
+The current native-image CI uses the separately recorded published engine 1.0.0.
+It does not qualify a new hosted 1.1 engine merely because the branch package
+version changed. Keep published image pins and local development qualification
+distinct.
+
+## Appropriate next validation work
+
+1. Retain the positive nested-isolation probe unchanged for a compatible host.
+ Do not make privileged mode, added capabilities, disabled AppArmor or disabled
+ seccomp the default route to a green check.
+2. Prepare an explicit unsupported-host rejection test: readiness must refuse
+ evaluation, return a bounded diagnostic, produce no asset and never select
+ an ordinary subprocess fallback. An unavailable prerequisite is not a passed
+ isolation qualification. Keep the original failed evidence.
+3. Keep production image functionality and actual provider isolation as separate
+ checks. The latter needs the exact deployed controller/image identities,
+ network denial, fresh-state/descendant isolation, resource limits, cancellation
+ and verified whole-instance cleanup. Local Docker cannot certify Cloudflare's
+ VM boundary.
+4. Make any workflow revision name and enforce those distinct obligations. Do not
+ remove the failing check or call the hosted service ready simply because this
+ mapping explains it. Complete and review the replacement evidence first.
+
+This narrows the next implementation step: improve the test architecture instead
+of repeatedly rerunning the same incompatible host. It does not waive a gate or
+authorize a new cloud trial.
+
+Official documentation checked today: Docker describes namespace-related syscall
+restrictions and recommends retaining its default
+[seccomp profile](https://docs.docker.com/engine/security/seccomp/). Cloudflare
+documents a Firecracker microVM with a separate kernel/network per instance and
+the [Durable Object Container lifecycle](https://developers.cloudflare.com/containers/concepts/architecture/).
+Those platform statements inform the architecture; actual deployment receipts
+are still required to qualify Kiln's use of it.
+
+## Additive VM qualification candidate
+
+The follow-up keeps the existing Docker job unchanged and adds an installed-package
+evaluator job on an ordinary Ubuntu 22.04 GitHub VM. It compiles Bubblewrap 0.12.0
+from upstream commit `2a76602a8c71f36c1527cf9fc3417d9149822e0c`, verifies the source
+archive SHA-256, and installs dedicated non-setuid, capability-free executables.
+Evaluation runs as the unprivileged runner user. No sysctl, AppArmor, seccomp or
+capability restriction is changed. This job is a candidate until CI provides an
+actual passing receipt; merely choosing the VM does not establish compatibility.
+
+`--isolation-only` selects the separate
+`kiln.nested-evaluator-qualification.v1` receipt. It requires all ten readiness
+invariants, repeatable evaluation, a nonblank CPU preview, deadline/cancellation/
+output limits and successful execution after those limits. It makes no software
+renderer claim. The unchanged Docker job continues testing that renderer and
+continues to fail on unavailable nested namespaces. This addition does not
+replace or waive either the old check or actual Cloudflare isolation qualification.
+
+Focused tests first failed for the missing separate qualification result, then
+passed after implementation. The same shared evaluator checks serve both modes;
+the original combined probe still requires its software-renderer result.
+Local validation passes 3,348 tests with two platform-specific skips, typecheck,
+repository lint, YAML parsing and Bash syntax.
+
+The first actual VM run, [37679591488](https://github.com/instruktlabs/kiln/actions/runs/37679591488),
+failed at `isolation/wrapper-launch` at source `494dee6`. Its exact installed
+archive still matches SHA-256 `98407508d8ec599189851aa0bd8b86313ac3abbd25e6337ac97f8510cc72215b`.
+The runner is non-root (1001), permits unprivileged user namespaces, and reports
+AppArmor user-namespace restriction as zero. No GLB or preview was produced.
+These facts rule out treating Docker alone as the explanation; they do not yet
+identify the failing launch component. The retained evidence is
+`.cache/nested-evaluator-494dee6/`.
+
+A bounded diagnostic now prepares the actual installed evaluator's launch for
+its fixed transport worker and records capped stdout/stderr/fd3 after failure.
+The child retains the evaluator's stripped environment and all restrictions.
+Its receipt is explicitly diagnostic, never qualification. The original failed
+receipt remains authoritative until a later actual run proves the full boundary.
+
+## Confirmed launcher defect
+
+The diagnostic from [run 37680296814](https://github.com/instruktlabs/kiln/actions/runs/37680296814),
+source `75e6682`, reports `bwrap: Unknown option --preserve-fds`. Every required
+executable and the installed transport worker exists. The wrapper exits before
+Node starts, with empty stdout/fd3 and no evaluated artifact. The independent
+Docker namespace diagnostics do not explain this earlier argument-parser failure.
+
+Bubblewrap 0.12.0 already passes inherited descriptors to its command; its monitor
+and namespace-init process close their own extra descriptors separately. See the
+[pinned upstream implementation](https://github.com/containers/bubblewrap/blob/2a76602a8c71f36c1527cf9fc3417d9149822e0c/bubblewrap.c#L3453).
+Kiln explicitly supplies only stdio and its fd3 protocol pipe to the child.
+The fix removes the nonexistent option, preserves every isolation/resource
+restriction, and retains the readiness transport proof. The regression first
+failed against the old launch, then passed with the fix; 23 focused tests,
+typecheck, lint and rebuilt SDK/runtime bundles pass. Full candidate CI remains
+required, including actual Linux transport and all ten readiness invariants.
+
+The invalid option is also present in published source `fda71ac` (1.0.0).
+It prevents the optional nested Linux evaluator from starting. The fix belongs
+to the unpublished candidate; publication will require a separately qualified
+archive and approval. Cloudflare's explicit fresh-VM adapter has a different
+execution boundary and does not use this launcher.
+
+After removing the invalid option, run `37681127385` starts the real Node
+transport successfully and returns the exact fd3 envelope. Its subsequent
+readiness failure is `invariant-namespace`, so wrapper startup is no longer the
+blocking point. The fixed kernel inspection from run `37681948282` records UID
+1001, all five capability sets empty, `NoNewPrivs: 1`, UID map `1001 0 1`, and
+exactly `NODE_ENV`, `NO_COLOR`, `PWD` with `PWD=/app`.
+
+The additional user namespace is how pinned Bubblewrap disables further user
+namespaces; the map's outside UID refers to the intermediate namespace. The old
+probe mistook that UID for the original host UID. The corrected probe requires
+the child's namespace identifier to differ from the trusted parent's, real and
+effective UIDs to equal the non-root caller, and a single-ID mapping matching
+Bubblewrap's supported layout. Root/elevated callers, the parent namespace,
+broad/multiple mappings, changed UIDs and missing parent evidence all fail.
+
+The launch also uses `/usr/bin/env -i` under the existing resource limits to
+remove wrapper-added `PWD` before Node starts. The exact two-variable environment
+invariant remains unchanged. These changes have failing-then-passing focused
+regressions; the actual VM must still pass every invariant and evaluation check.
+
+At source `71aac00`, [run 37682807529](https://github.com/instruktlabs/kiln/actions/runs/37682807529)
+passes all ten readiness invariants through the exact installed archive
+`eedebd4ec4040bc5b0daad41d82f79202a6a2a7d06c5b01ba53c7a14b30cc63e`.
+It then fails the first actual evaluation with `EXECUTION_REJECTED`, producing
+no artifact. The receipt remains failed; readiness alone is not qualification.
+The same fixed box successfully renders through the local packaged Node worker
+(1,912 GLB bytes), which validates the fixture but proves no Linux isolation.
+The CI-only diagnostic now evaluates that fixed box directly inside the unchanged
+boundary and records capped exception details. It accepts no user source and
+does not change the sanitized public evaluator protocol. The retained failed
+evidence is `.cache/nested-evaluator-71aac00/`.
+
+The fixed-fixture diagnostic in [run 37683757970](https://github.com/instruktlabs/kiln/actions/runs/37683757970)
+confirms `ERR_PROTO_ACCESS` inside the installed Khronos validator's startup
+feature detection. The same failure reproduces locally with Node 22.23.3 and the
+isolated launcher's `--disable-proto=throw`. It is a runtime/dependency interaction,
+not an invalid qualification scene or a namespace-permission failure.
+
+The corrected launcher uses Node's documented `--disable-proto=delete`, removing
+the legacy mutation accessor entirely. See the [Node CLI contract](https://nodejs.org/api/cli.html#--disable-protomode).
+Readiness additionally requires that absence and checks generated constructor-chain
+denial. The focused regression derives Node flags from the actual launcher,
+initializes the actual Khronos dependency, validates a rendered GLB and verifies
+that an assigned JSON `__proto__` key cannot mutate the target prototype. It fails
+with the old flags and passes with the fix. No validator bypass, source-policy
+exception or OS/resource restriction change is introduced. Actual VM qualification
+of this corrected candidate is still required.
+
+## Positive installed proof and restricted-host regression
+
+[Run 37684601572](https://github.com/instruktlabs/kiln/actions/runs/37684601572)
+at `5b1094c` passes the complete installed VM qualification: all ten readiness
+invariants, two identical GLB evaluations, a nonblank 128px CPU preview, deadline,
+cancellation, output limits and successful execution after the limits. The
+downloaded archive SHA-256 is
+`ce0d7e182705159d70daa19ab58e8fc063e81a8a43a8e4df203cfb1d88c2878f`.
+Both artifact sizes and digests were independently checked; the 1,912-byte GLB
+hash is `f94d231ed3eb4843a03704872adc3f20b00c2ea24567cb5916407b40a2cf1d40`.
+The CPU image was inspected and shows the expected box. This is VM/SDK evidence,
+not material or Cloudflare qualification. The original Docker job remains failed
+in this preserved run. All 118 focused evaluator/qualification tests pass locally.
+
+With positive evidence established, the Docker job now explicitly requests
+`--expect-unsupported-isolation` and requires a distinct refusal-only receipt.
+It must observe kernel namespace permission denial, readiness `wrapper-launch`,
+and `WORKER_FAILED` for the valid fixed source, producing no artifact. Successful
+readiness/source execution, missing kernel evidence, an authoring rejection or
+a timeout cannot satisfy this test. It still separately requires the complete
+software-renderer fixture under unchanged Docker restrictions. The positive VM
+job remains mandatory for this workflow; no failing positive probe automatically
+switches to the negative mode. Fifteen focused qualification tests pass, including
+the new failing-then-passing refusal cases. Actual CI proof of this revised job
+remains required before its status can be reported as passing.
+
+The revised workflow [37685410198](https://github.com/instruktlabs/kiln/actions/runs/37685410198)
+passes both jobs at `2087faac07e6c86245abd78a55ddfd481bae275d`. Both downloaded
+archives match `ce0d7e182705159d70daa19ab58e8fc063e81a8a43a8e4df203cfb1d88c2878f`.
+The positive VM repeats all nine checks and ten readiness invariants. Docker's
+refusal receipt reports kernel permission denial, `wrapper-launch`, `WORKER_FAILED`
+and no artifact, followed by a separate passed software-Vulkan receipt. The GLB,
+CPU PNG and all six software-view digests were independently verified. Local
+full tests for the runtime correction pass 3,353 tests with two platform skips;
+the later refusal extension separately passes fifteen qualification tests.
+Full package CI subsequently passed all twelve jobs at the same source, including
+Linux and Windows regressions. All seven downloaded installation receipts verify
+against that exact archive; six software-rendered view hashes also verify. This
+resolves the native preflight failure for this candidate without qualifying public
+hosted launch.
diff --git a/docs/reviews/2026-10-07-private-lifecycle-result.md b/docs/reviews/2026-10-07-private-lifecycle-result.md
index 7ed8dcf2..d3dc4f0c 100644
--- a/docs/reviews/2026-10-07-private-lifecycle-result.md
+++ b/docs/reviews/2026-10-07-private-lifecycle-result.md
@@ -72,6 +72,14 @@ returned one numeric zero for an empty interval. No Cron was deployed in this
trial and no alert destination was configured; scheduled-health and delivery
qualification remain open.
+A subsequent separately approved notification test delivered a sample email to
+the owner's business address at 13:41:56 UTC. The temporary alert was disabled
+after inbox verification, with the existing budget alert unchanged. This is
+sample delivery evidence only; automatic triggering, scheduled health and return
+to normal still require qualification. The minimal receipt and disabled-state
+screenshot are `.cache/cloudflare-alert-delivery-receipt.json` and
+`.cache/cloudflare-alert-test-disabled.png`.
+
Provider start-to-stopped intervals totaled 145.923 instance-seconds. At the current
[Container rates](https://developers.cloudflare.com/containers/platform/pricing/),
modeling fully allocated CPU over those intervals gives about **$0.0036** for
diff --git a/docs/reviews/2026-10-07-project-adoption.md b/docs/reviews/2026-10-07-project-adoption.md
new file mode 100644
index 00000000..f07244a4
--- /dev/null
+++ b/docs/reviews/2026-10-07-project-adoption.md
@@ -0,0 +1,164 @@
+# Shared project setup implementation checkpoint
+
+7 October 2026. Development work for the owner's choice to support both existing
+projects and new asset workspaces. The public npm package remains 1.0.0; these
+changes have not been released, merged to main or submitted to a directory.
+
+## Implemented boundary
+
+`kiln-init <directory> --adopt --harness <client>` uses the maintained initializer
+for either destination. `--adopt --check` previews changes without creating a
+directory, project file or recovery journal. The plugin wrapper delegates to the
+same capability and rejects an older pinned engine instead of silently running
+legacy empty-folder setup. The updated development plugin pins `1.1.0-dev.1`;
+published engine 1.0.0 cannot adopt projects.
+
+Schema 2 records multiple client registrations around one program store, owned
+file hashes, and only the configuration entries managed by Kiln. Other servers,
+settings, JSON/JSONC comments, TOML text, large numeric literals and unowned root
+instructions are preserved. Kiln guidance remains available at `.kiln/AGENTS.md`
+and `.kiln/START.md`. Skills use the same maintained sources with client-specific
+discovery paths. Optional compose/batch workflows stay optional.
+
+The complete change plan is checked before one recoverable write transaction.
+Path conflicts, invalid configuration, corrupt metadata and conflicting owned
+edits stop before mutation. Explicit schema 1 adoption preserves saved assets.
+Repeated adoption is idempotent; adding another compatible integration does not
+duplicate the store. Repair changes runtime registrations without refreshing
+copied skills; upgrade handles unchanged managed guidance and reports conflicts.
+`--recover` is a separate operation after interruption.
+
+## Evidence
+
+- Fifteen focused adoption tests pass with 114 assertions. They cover populated
+ and missing directories, existing instructions/servers, read-only previews,
+ repeated setup, adding Codex, legacy migration, runtime relocation, customized
+ skills, OpenCode paths/comments, invalid UTF-8, and malformed or hostile manifest
+ data. New failure cases were observed before their implementation fixes.
+- Twenty-six plugin-wrapper tests pass, including capable-engine delegation,
+ refusal of unsupported adoption and recovery/preview argument handling. The
+ generated plugin remains byte-aligned with its maintained helper and setup skill.
+- An independently installed archive in a Windows temporary directory containing
+ spaces and a non-ASCII character passes actual MCP validation, CPU rendering,
+ saving, source reopening and GLB reads. The Claude registration starts one
+ 17-tool server; after stopping it and adding Codex, its registration starts a
+ new 17-tool server and reads the same program reference and saved revision.
+ Source and GLB bytes are identical, and owner instructions/settings are intact.
+- The archive SHA-256 is
+ `486e26f396632c9a586505cfc313e00e62b6d7942297479a890a0891b1014c2b`.
+ This is an unpublished working-tree archive bearing the existing development
+ package version, not the published 1.0.0 artifact. Local evidence is
+ `.cache/adoption-installed-receipt.json`.
+- The same storage-reuse check now runs in the maintained package smoke test,
+ so candidate OS/Node CI can exercise it. Its full Windows package smoke run
+ passed and the receipt verifier accepted that exact archive. Historical public
+ releases report that adoption is unsupported; a manifest that ships adoption
+ must supply its passing installed proof. Evidence:
+ `.cache/adoption-package-smoke.json`.
+- The full local test run passed 3,338 tests with two platform-specific skips and
+ no failures across 414 files. After adding the receipt-gate regression, the
+ coverage run passed 3,339 tests with two skips, 95.16% function coverage and
+ 92.50% line coverage, above the unchanged ratchet. Toolchain, skill consistency,
+ typechecking and final lint pass.
+- Committed source `225d74ac9cf35950802253aa97275de2f621619a` passed all twelve
+ engine/package jobs in [CI run 37662806886](https://github.com/instruktlabs/kiln/actions/runs/37662806886).
+ Its downloaded archive hashes to
+ `cc620fd544857230d09be232417339b7b9c83cbcab4720abb036008ad028ad4c`.
+ The receipt verifier independently accepted all seven downloaded installation
+ receipts against those bytes: maintainer Linux, the three consumer Node versions,
+ Windows and both macOS architectures. Each reports passing installed project
+ adoption and cross-client storage. Software Vulkan also passed in CI. These
+ checks qualify the development candidate; they do not publish it or establish
+ actual client first-use conversations. The separate legacy Docker isolation
+ preflight remains failed and is not included in this passing CI claim.
+
+Early scratch-probe failures were in the probe: it initially omitted Sharp's
+optional platform package and assumed artifact resource-link blocks were enabled
+by default. The corrected probe uses the normal optional dependency installation
+and the existing readable resource URIs. A later smoke fixture passed an invalid
+empty work-item ID; it now uses a valid synthetic ID. Failed receipts are retained;
+none of these failures justified changing engine behavior or weakening a gate.
+
+## Remaining before release
+
+1. Finish independent review. Cross-platform CI passed at the source above;
+ implementation changes require fresh qualification. Actual model conversations
+ in both advertised clients, for an
+ empty folder and an existing project, remain required. Protocol clients do
+ not prove discovery, trust prompts, duplicate-free instructions or usability.
+2. Qualify the new `1.1.0-dev.1` package and plugin pin, then freeze a release
+ candidate and obtain separate publication approval. Published 1.0.0 is immutable.
+3. Review the updated plugin README and draft privacy notice with the owner.
+ Setup recovery temporarily snapshots project configuration,
+ which may already contain credentials, outside the project. It never prints
+ snapshot contents and removes them after successful setup/recovery. Storage
+ uses filesystem permissions, not encryption. See the recovery review for
+ interrupted cleanup, power-loss and same-user threat-model limitations.
+4. Keep the owner's hold on naming, portal changes, submissions and further
+ outreach. Review the concrete distribution dossier before resuming them.
+
+This does not prove every pair of client configurations is compatible. A pair
+requiring different values for the same MCP entry is rejected before writing.
+Removing integrations is not implemented. Existing-project use also does not
+provide clean-room asset authoring: application context remains visible. The
+separate-workspace path remains available for that purpose.
+
+## Independent review follow-up
+
+The owner-requested distribution audit completed its bounded review of `225d74a`.
+It identified two concrete issues, addressed in the development follow-up:
+
+- Copying a schema 1 OpenCode workspace and adopting the copy left the original
+ absolute skill path alongside the copied one. A new real-Node regression failed
+ with both paths present. Migration now recognizes the old single path only when
+ the complete legacy configuration still matches its recorded hash. The copied
+ workspace uses only its own skills, while the original workspace, saved source
+ and owner files remain unchanged. Repeat adoption is idempotent.
+- The plugin helper limited setup to Claude and Codex even though the shared
+ initializer supports more adapters. Its generated runtime pin now derives the
+ adapter list from the initializer. The helper validates that list before npm
+ installation and delegates configuration to the engine. Older metadata without
+ this list retains its original two-client contract. This does not advertise
+ plugin installation in other clients or prove their complete current workflows.
+
+All 57 focused adoption, wrapper and bundle tests pass with 311 assertions after
+the fixes. Full local tests and coverage each pass 3,346 tests with two
+platform-specific skips; coverage remains 95.16% functions and 92.50% lines.
+Toolchain, skill consistency, typechecking, lint and the redacted patch secret
+scan pass. The package, engine identity and plugin now use `1.1.0-dev.1`, with
+rebuilt runtime bundles and 55 SDK entrypoints. The generated plugin README
+explains adoption and the correct interactive Codex entry; its draft privacy
+notice discloses recovery snapshots and retention.
+
+The follow-up's installed Windows archive has SHA-256
+`48c5c0ddfce1f70543c614d4725ca18bfc68d7bb31c3f3696a88de8fea749f74`.
+Full SDK/CLI/MCP smoke and consumer type checks pass, including project adoption
+and the same saved GLB bytes across Claude/Codex registrations. Its receipt
+verifier accepted `.cache/setup-audit-package-smoke.json`. The smoke ran with an
+allowlist of OS environment variables and empty npm configuration files, without
+provider credentials or model calls. An initial assertion expected the older
+two-field runtime pin; it now checks the full new pin against the installed
+initializer's adapter list. The same archive was used for the successful rerun.
+Committed source `76c869aa7c8637b222b5bdf956fd1e70c3f9d83a` passed all twelve
+engine/package jobs in [CI run 37668542892](https://github.com/instruktlabs/kiln/actions/runs/37668542892).
+Its downloaded CI archive has SHA-256
+`98407508d8ec599189851aa0bd8b86313ac3abbd25e6337ac97f8510cc72215b`.
+All seven downloaded installation receipts independently verify against those
+bytes, including project adoption and shared storage; software Vulkan also
+passes against the same archive. The separate legacy Docker isolation preflight
+still fails. Four external first-use fixtures are prepared from this CI archive:
+new workspace and existing project in each client. Their owner MCP fixtures and
+baseline files pass validation, but no model conversations have run. These are
+test preparations, not completed onboarding evidence.
+Hosted typechecking, all 450 offline tests and the Worker build also pass. The
+version bump required refreshing the generated edge metadata and draft plugin
+version; their protocol/packaging checks caught that drift before qualification.
+The frozen deployment and trial candidates at earlier commits are unchanged.
+
+The audit also identified an unverified OpenCode adapter concern: root
+`opencode.json` is the maintained configuration, while newer client documentation
+describes other JSONC and `.opencode` configuration locations. Their precedence
+and discovery have not been qualified with an installed current client. Record
+the tested client version and resolve conflicting effective configurations before
+claiming support for that workflow. No additional preservation defect was found
+in the bounded review; that is not a complete security or first-use acceptance.
diff --git a/docs/reviews/2026-10-07-project-config-preservation.md b/docs/reviews/2026-10-07-project-config-preservation.md
new file mode 100644
index 00000000..e1d7bbeb
--- /dev/null
+++ b/docs/reviews/2026-10-07-project-config-preservation.md
@@ -0,0 +1,89 @@
+# Existing-project configuration preservation
+
+Status: implementation prerequisite for shared local setup, 7 October 2026.
+This does not yet enable existing-project adoption in `kiln-init`, modify an
+installed user project, or change any published package/plugin.
+
+The [owner-selected local setup plan](../plans/2026-10-07-agnostic-local-setup.md)
+requires existing-project setup without replacing unrelated agent configuration.
+`scripts/workspace-config.mjs` now provides pure JSON/JSONC and TOML merge functions
+for the forthcoming project-adoption transaction. Both return proposed text;
+neither opens files, reads credentials, writes settings or grants trust.
+
+## Evidence
+
+- Twelve initial tests failed against the unimplemented operations. Sixteen
+ focused tests now pass with 73 assertions, including added adversarial cases.
+- JSON edits preserve unrelated source bytes, comments, settings and large-number
+ spelling. They reject duplicate keys, ambiguous parent types, overlapping
+ changes, unsafe paths and conflicting or modified owned entries. Updating an
+ owned entry requires matching the previous value, or the exact desired value
+ for an idempotent repeat.
+- TOML edits preserve text outside an explicitly owned table block. Parsing and
+ semantic comparison check that insertion/replacement cannot change unrelated
+ settings through table context. Marker-like lines inside a multiline string,
+ duplicate/incomplete markers, manual target tables and extra assignments are
+ rejected. A previously existing manual Kiln table needs an explicit ownership
+ migration; this helper does not silently take it over.
+- Malformed input diagnostics omit parser source excerpts and configuration
+ values. Tests use synthetic credential strings to confirm those values are not
+ included in errors. No real credential was used in these tests.
+- Node 22.23.3 independently imported and exercised both functions successfully.
+- The full local suite passed: 3,307 tests passed, two platform-specific tests
+ skipped, no failures. Typechecking, skill consistency, toolchain validation and
+ lint (1,085 files) passed. A registry advisory audit found no known
+ vulnerabilities among 309 packages; that is not a guarantee of absence of
+ vulnerabilities. The subsequent coverage run also passed all 3,307 tests and
+ the existing ratchet: 95.16% functions (minimum 94.00%) and 92.50% lines
+ (minimum 92.10%). Coverage measures `src/`; the script's preservation behavior
+ is proved by its focused tests, not those engine percentages.
+- Runtime bundles rebuilt. The SDK directory replacement encountered a Windows
+ `EPERM` once and restored the prior output; a direct SDK build retry succeeded
+ with all 55 entrypoints and 522 emitted files. No permissions or running user
+ processes were changed to obtain the successful build.
+- Installed Codex 0.160.0 read the generated `.codex/config.toml` entry from a
+ trusted synthetic project and reported an enabled stdio server. Installed
+ Claude Code 2.1.287 read the generated `.mcp.json` and correctly reported
+ **Pending approval**. Both used temporary, empty client configuration homes;
+ the user's global settings and authentication were not changed. These commands
+ inspected configuration only. They made no model call and did not run a Kiln
+ authoring workflow.
+
+The parsers are pinned to registry-verified stable versions:
+`[email protected]` (MIT) and `[email protected]` (BSD-3-Clause). Both declare no
+dependencies. The latter requires Node >=18, within Kiln's existing consumer
+range. They remain separate npm dependencies with their distributed license
+files. No new native component or provider service is introduced.
+
+## Limits and next integration work
+
+This module is not yet connected to the initializer or included in its shipped
+file list. It is not proof that project adoption or multi-agent setup works.
+The filesystem transaction must add containment/link checks, conflict checks
+against fresh file contents, rollback/recovery and owned-state tracking. The
+generator must then route both new-workspace and existing-project setup through
+the shared logic, preserving legacy workspaces and normal client trust prompts.
+
+Complete the adapter projections, skill registration without duplicates, safe
+addition/removal of agent integrations and installed-package tests. Full real
+client onboarding, asset preservation and cross-agent reuse remain release gates.
+No public directory draft or outbound message was changed by this work.
+
+CI at `e76c591` also retriggered the older conditional Docker hosting probe
+because dependencies changed. Its retained receipt failed at
+`isolation / wrapper-launch`, before evaluating source, matching the failure
+phase already recorded in the hosted isolation review. This is an unresolved
+hosting check, not a passing setup or production-isolation receipt. Evidence:
+GitHub run `37650504451`, artifact `11495249713`, and the local copy under
+`.cache/pr156-native-preflight-receipts/receipts/isolation/`. No workflow was
+weakened or failure hidden.
+
+The Windows hosted check at the same commit separately reported `fetch failed`
+from the real Worker-RPC denial request in `resilience.test.mjs:444` (run
+`37650504502`, first attempt). Three exact focused local reproductions passed,
+followed by all 450 local hosted tests. The failure was retained and one rerun of
+only the failed CI job was requested without changing assertions or source.
+Attempt two passed on unchanged source. This is an unreproduced failure, not a
+root-cause fix. All 25 other checks now pass; the separate Docker probe above
+still fails. Log: `.cache/pr156-hosted-windows-failure.log`; local evidence:
+`.cache/resilience-repro-{1,2,3}.log` and `.cache/agnostic-hosted-repro.log`.
diff --git a/docs/reviews/2026-10-07-release-status.md b/docs/reviews/2026-10-07-release-status.md
new file mode 100644
index 00000000..78ed8a61
--- /dev/null
+++ b/docs/reviews/2026-10-07-release-status.md
@@ -0,0 +1,221 @@
+# Kiln release goal status
+
+7 October 2026. This checkpoint distinguishes shipped work, private qualification
+and remaining launch work. The dated research plan remains the scope record;
+older statements within it are not the current execution status.
+
+## New owner decision: private hosted application
+
+The owner selected a separate private hosted application while keeping the engine
+and integrations public. The [migration scope](../plans/2026-10-07-private-hosting-separation.md)
+records the created private `instruktlabs/kiln-hosted` repository, dependency/CI
+work, preservation of public history and the limits of removing already-published
+code. Private PR #1 is now merged with owner approval. Further hosted-only
+PR work belongs in that repository; the
+existing trial approvals remain unanswered and are not supplied by this decision.
+
+The PR sequence below predates this decision. #154/#155 should be preserved in the
+private migration instead of proceeding through the earlier public merge sequence;
+#156's public setup/isolation work must be separated from its hosted changes.
+The owner requested an updated [execution goal](../plans/2026-10-06-v1-execution-goal.md)
+covering the full cycle and a focused-day migration target. GitHub Team is the
+approved plan for protection rules on the new private repository's branches.
+There is no private branch inside the public repository. The owner selected
+monthly billing and completed the upgrade. GitHub's organization API independently
+confirms `plan.name: team`, `seats: 1`, `filled_seats: 1`; checkout showed $4/month
+before tax/usage. The private remote is established; public cleanup is not merged.
+
+The separate `C:/Users/Mattm/X/kiln-hosted` checkout records preserved source from
+`f99f1b8`, with 251 original-source hash records. Private PR #1 at `1d6bd74`
+merged as `e84d79f15d4c143e0855bf57ea1b5709e32dd165`; the merged tree is identical
+to the approved candidate. Independent dependency resolution, typechecking, all
+459 application tests and builds pass locally and on both CI platforms. All five
+CI checks passed, including three native image checks; all 14 production modules
+match across local/Linux/Windows builds. The import secret scan passed and private
+main protections are verified. Two temporary installed-package adapters remain
+documented follow-up API work.
+
+The public cleanup candidate removes the hosting application and its two dedicated
+workflows, relocates public plugin metadata/packaging, and retains generic engine
+checks. It is being qualified in an isolated worktree; public main still contains
+the old folder. The owner accepts historical source remaining visible: use a
+normal cleanup PR without history rewriting, force pushes or release-tag removal.
+
+## Completed
+
+- GitHub Team upgrade for Instrukt Labs, monthly with one seat, completed by the
+ owner and independently verified through the organization API. Private branch
+ protection is configured on the separate private repository.
+- The independent private application import is merged, with passing CI and
+ source/output identity verified. This deploys no public service.
+- GitHub transfer to `instruktlabs/kiln`, with repository/community preservation
+ and the personal-profile pin checked. npm account/organization and publishing
+ protections are established. Cloudflare Workers Paid and R2 Paid were already
+ active; no new subscription purchase was required.
+- Stable `@instruktlabs/[email protected]` is public under `latest`. Registry metadata was
+ rechecked today. Normal install is `npm install @instruktlabs/kiln`. The public
+ GitHub release is [Kiln 1.0.0](https://github.com/instruktlabs/kiln/releases/tag/v1.0.0),
+ at source `fda71ac775750f25390b6ee30082ebc56463edc6`. Its archive digest is
+ recorded in `.github/published-candidate.json`.
+- The published SDK/CLI/MCP package has platform installation evidence. Local
+ plugin foundations and isolated client discovery/protocol checks exist; this
+ is distinct from completion of the newly selected existing-project onboarding.
+- Private Cloudflare trials demonstrate native evaluation, software material
+ rendering, persistence, downloads, account isolation, quotas and bounded VM
+ cleanup. See the [deployed lifecycle receipt](2026-10-07-private-lifecycle-result.md).
+ This is not a public-service launch or a load-capacity claim.
+- Google and organization-owned GitHub OAuth clients exist. Their credentials
+ are stored encrypted outside the repository; live hosted sign-in is unqualified.
+
+## In progress
+
+- Shared setup for existing projects and new workspaces is implemented locally.
+ An installed candidate preserves owner files and reopens the same source,
+ revision and exact GLB across Claude and Codex registrations. Full local tests
+ and all twelve engine/package CI jobs pass at `225d74a`; seven installed
+ receipts were independently checked against the exact CI archive.
+ [Adoption evidence](2026-10-07-project-adoption.md) separates these results
+ from actual client first-use conversations, which remain outstanding.
+- Independent setup review found a copied-OpenCode migration defect and a
+ plugin-helper adapter restriction. Both have focused regressions and fixes in
+ the `1.1.0-dev.1` follow-up. Full local tests, coverage and an installed Windows
+ archive pass. At `76c869a`, all twelve engine/package CI jobs pass and seven
+ downloaded installation receipts verify against the exact CI archive. Real
+ client onboarding remains outstanding; four isolated new/existing-project
+ fixtures are prepared, with no model calls made.
+ The exact plugin installs in isolated Claude/Codex profiles; Codex sees one
+ setup skill alongside the fixture's existing skill and MCP server. The
+ [bounded live onboarding plan](2026-10-07-local-onboarding-qualification.md)
+ awaits its separate model allowance and isolated Codex-profile sign-in.
+ This development version does not replace the published stable package.
+ The newer `2087faa` archive has now passed all seven downloaded installation
+ receipt checks, including project adoption, cross-client saved storage and six
+ software-rendered views. The independently verified archive SHA-256 is
+ `ce0d7e182705159d70daa19ab58e8fc063e81a8a43a8e4df203cfb1d88c2878f`.
+ All twelve package CI jobs now pass at this exact source, including Linux and
+ Windows full tests. These receipts do not replace the outstanding actual-client
+ sessions.
+- Hosted retention and scheduled deletion have a frozen private trial candidate.
+ The maintenance gateway and recovery runbook have offline tests, including a
+ state-preserving local transition, but need provider qualification.
+- A private recovery verification component now checks actual saved bytes against
+ current tenant metadata without storage writes. All 463 hosted tests, three
+ hosting typechecks and repository lint pass. It has no production route, backup
+ capture or restore implementation; full provider recovery remains a launch gate.
+- Public pages, terms, account controls and directory bundles are prepared
+ candidates. They have not been approved as a public service or submitted listing.
+- Current package, plugin, fourteen rebuilt hosted modules and all 103 post-stable
+ commits pass redacted secret scans at `2087faa`. The focused account-flow review
+ identified no new defect in this pass. See the [security record](2026-10-06-v1-security-review.md#7-october-candidate-refresh);
+ live provider sign-in, final image/configuration review and real-client behavior
+ are still separate launch requirements.
+- Recovery scope is awaiting owner alignment: the original plan requires rollback
+ readiness, while the later checklist also adds broader backup and restore
+ qualification. The pending decision distinguishes provider database recovery plus
+ tested code rollback from a new source/GLB backup system. Until answered, the
+ existing checklist remains in force; no new backup storage is provisioned.
+
+## Execution focus after the owner progress review
+
+The owner raised the elapsed time and asked whether process was displacing
+delivery. The core native execution problem now has positive installed evidence;
+all 27 checks at `2087faa` pass. The project is not waiting for another rerun of
+that candidate. It still lacks actual-client onboarding, live hosted identity
+flows, deployed retention/rollback proof and directory submissions.
+
+Stop adding general recovery automation ahead of those flows. The newly started
+gateway code-change helper test was removed before implementation or commit;
+the documented rollback procedure and its required provider rehearsal remain.
+The existing backup-scope question is an owner decision, not evidence that the
+original plan required a new cross-store backup product.
+
+Prioritize the prepared merge and trial handoffs, then test the integrated hosted
+journey and fix only demonstrated launch defects. Keep frozen approval candidates
+unchanged. Reuse passing exact-artifact evidence; rerun affected checks after
+meaningful changes, not merely to refresh a status report. Consolidate the PR
+queue after the approved foundational merge. Final docs and submission dossiers
+follow functioning, verified user journeys.
+
+## Remaining sequence
+
+0. Qualify and approve the public cleanup PR after the verified private merge.
+ Preserve public setup/isolation work and close superseded release PRs only
+ after confirming their content and obtaining the owner's approval.
+1. Finish shared setup qualification and exact package/plugin version selection.
+ Published 1.0.0 cannot gain this new feature in place. Test actual onboarding
+ in both advertised clients, then qualify and approve the new artifact.
+2. Complete deployed retention/Cron, backup/restore and rollback qualification.
+ Prove that recovery retains current revocations and saved bytes.
+3. Complete real Google/GitHub sign-in and account actions, production Google
+ audience/branding, monitoring, representative abuse/load/cost checks, and
+ the final security review of the exact hosted candidate.
+4. Approve the concrete deployment, launch `kiln.instruktlabs.com`, then verify
+ public HTTPS and actual MCP client flows.
+5. Review each directory dossier with the owner: visible name, installation ID,
+ Instrukt Labs publisher ownership, supported clients, skills/tools, executable
+ and privacy declarations, reviewer access and demo evidence. Claude-specific
+ portal changes, naming changes, submissions and further outreach remain on
+ hold for alignment. No directory submission has been completed.
+6. Refresh public README, Troy imagery, site documentation and stale onboarding
+ statements after hosted launch, as the owner requested. Track vendor review
+ separately from successful submission.
+
+## PR sequence and outstanding handoffs
+
+Git ancestry and merged content were checked against current remote PR heads.
+The owner approved #153 and closure of its three superseded PRs. There are now
+three open release PRs:
+
+| PR | Role | Disposition |
+| --- | --- | --- |
+| [#147](https://github.com/instruktlabs/kiln/pull/147) | Initial native execution | Closed as superseded after inclusion in #153 was verified |
+| [#149](https://github.com/instruktlabs/kiln/pull/149) | Initial account controls | Closed as superseded; no separate merge needed |
+| [#150](https://github.com/instruktlabs/kiln/pull/150) | Native startup/isolation qualification | Closed as superseded; no separate merge needed |
+| [#153](https://github.com/instruktlabs/kiln/pull/153) | Integrated hosted foundation | Merged as `6f41a1a`; merged tree is identical to approved `39083d7`; main CI running |
+| [#154](https://github.com/instruktlabs/kiln/pull/154) | Retention and scheduled recovery | Based on main; history reconciled at `7fc5bbb` without changing any file; frozen private trial still uses `37c962e` and awaits its separate $1 allowance |
+| [#155](https://github.com/instruktlabs/kiln/pull/155) | Maintenance and recovery preparation | Review base is #154's branch; restore/provider evidence remains unfinished |
+| [#156](https://github.com/instruktlabs/kiln/pull/156) | Shared setup and isolation fixes | Review base is #155's branch; all 27 checks pass at `2087faa`; actual onboarding remains |
+
+GitHub requires linear main history. The merge-commit attempt was refused; the
+approved squash merge was used without changing branch protections. Main's tree
+`8547cb35133b6efe2a78b20a24f9873e8abb24ab` equals the approved source tree exactly.
+Operations history was then reconciled using that verified common content;
+`7fc5bbb` has the unchanged `37c962e` tree `7802a86fd2fdea78e8a57e0ecb9c16415d5aeec9`.
+No history was force-pushed. The remaining PRs show successive changes for review;
+each still needs explicit approval before its eventual main merge.
+
+The hosted foundation merge deploys and publishes nothing. The pending retention
+trial uses four private Workers with temporary D1/KV/R2, no VMs, provider secrets
+or public route, with a bounded run and identity-checked cleanup. Earlier paid
+trial allowances do not authorize it.
+
+The [preflight alignment review](2026-10-07-native-preflight-alignment.md) records
+the exact Docker/VM failures and distinguishes the optional nested SDK evaluator
+from production's explicit Cloudflare fresh-VM adapter. Actual installed VM
+qualification now passes at `5b1094c`: all ten readiness invariants, deterministic
+GLBs, CPU preview, deadline/cancellation/output bounds and post-limit recovery.
+Archive and artifact hashes were independently checked. Launcher, namespace,
+environment and Khronos-validator compatibility fixes have regressions and rebuilt
+bundles; the optional-adapter fixes remain unpublished. All 118 focused evaluator
+and qualification tests pass; full exact-candidate package CI remains required.
+
+The preserved Docker job still fails in that earlier run. Its replacement requires
+explicit kernel-denial and evaluator-refusal evidence, no artifact, and the unchanged
+trusted software-renderer fixture. At `2087faa`, both the positive VM and restricted
+Docker/renderer jobs pass in run `37685410198`; the two exact archives and all eight
+output artifact hashes were independently verified. Local full tests pass 3,353
+tests with two skips; fifteen qualification tests cover the subsequent refusal
+extension. All twelve package CI jobs now pass, including Linux and Windows full
+tests and all installation jobs. Hosted gateway checks, public-registry install
+checks, private image checks and the website build all pass at the same source:
+27 checks total. No restriction is relaxed and no
+failed positive probe automatically selects the refusal mode. Recovery commit `88ebe58`
+separately passed hosted CI on Linux and Windows; provider restore remains unfinished.
+
+No immediate authentication is required for the local implementation. Later
+provider transitions and final publication/deployment actions will be surfaced
+as concrete handoffs. The contributor's #140, #141 and #142 remain outside today's
+scope for the owner to review separately. The public #153 merge and
+#147/#149/#150 closures have been performed. Separately, private
+`instruktlabs/kiln-hosted` PR #1 is merged with owner approval; public cleanup and
+closures of #154/#155/#156 remain pending.
diff --git a/docs/reviews/2026-10-07-setup-recovery.md b/docs/reviews/2026-10-07-setup-recovery.md
new file mode 100644
index 00000000..a6999282
--- /dev/null
+++ b/docs/reviews/2026-10-07-setup-recovery.md
@@ -0,0 +1,83 @@
+# Recoverable project setup preparation
+
+7 October 2026. Internal implementation checkpoint for the owner-selected
+[shared setup plan](../plans/2026-10-07-agnostic-local-setup.md). This does not
+enable existing-project installation or change the published package.
+
+## Filesystem boundary
+
+`scripts/workspace-transaction.mjs` accepts a bounded list of exact before/after
+file snapshots. It checks all paths and preimages before writing, serializes
+cooperating setup processes, stages complete files beside their destination, and
+writes `.kiln/workspace.json` last. A check creates no files or directories.
+
+Recovery snapshots and a journal live outside the project, under the user's Kiln
+application-data directory by default. They may contain credentials already in
+the project configuration. Snapshot bytes never enter reports or error messages.
+New directories/files request modes 0700/0600 on POSIX; Windows uses the profile
+directory's filesystem permissions. This is temporary recovery storage, not an
+encrypted credential vault. Successful setup or recovery removes these files.
+
+Caught failures restore files only when their contents still match the recorded
+setup state. Conflicting owner edits are retained along with the recovery data.
+Explicit recovery verifies snapshot hashes and every target conflict before
+restoring targets. Traversal, Windows aliases/device names, overlapping file and
+directory targets, linked managed paths, and a changed project-root identity are
+rejected. Cleanup never recursively deletes recovery storage or a project target.
+Unknown recovery files prevent cleanup.
+
+File IDs use bigint filesystem metadata and decimal strings in the journal.
+Testing found Windows IDs that exceed JavaScript's safe integer range; converting
+them through ordinary numbers would make recovery validation unreliable.
+
+## Evidence and limits
+
+- Nine initial tests failed against stubs. Thirteen focused filesystem tests now
+ pass, including a real Node subprocess exiting after its first file write,
+ explicit recovery, concurrent setup exclusion, junction replacement, tampered
+ backups, conflict retention and reversible deletion.
+- Together with the configuration merge tests, 29 focused tests and 137 assertions
+ pass. Evidence: `.cache/workspace-recovery-green.log`.
+- Toolchain checks, skill consistency, typechecking and lint passed. The full
+ local suite passed 3,320 tests, with two platform-specific skips and no failures
+ across 413 files. The separate coverage run also passed all 3,320 tests and the
+ existing ratchet: 95.16% functions (minimum 94.00%) and 92.50% lines (minimum
+ 92.10%). Coverage measures `src/`; the recovery helper is verified by its focused
+ tests, not those engine percentages. Evidence:
+ `.cache/recovery-{check-toolchain,check-skills,typecheck,lint,test,test-coverage}.log`.
+- Recovery covers process interruption, not a claim of atomic multi-file commits
+ across power loss. Files are flushed; directory-entry durability is not proved
+ across every filesystem. An incomplete journal or interrupted recovery lock
+ fails closed and may require manual inspection.
+- These checks protect ordinary setup conflicts. They are not an OS security
+ boundary against a hostile process running as the same user. Users should stop
+ agent/MCP sessions and configuration writers before maintenance. Path checks
+ and atomic renames do not provide a filesystem compare-and-swap primitive.
+
+The helper is not yet imported by the initializer or shipped in `package.json`.
+Next work is the owned project manifest, adapter projections, shared initializer
+integration, legacy migration and installed-package qualification. No release,
+cloud deployment, directory submission or external outreach occurred here.
+
+## Correcting the skill-discovery assumption
+
+Current [Claude Code skill documentation](https://code.claude.com/docs/en/skills)
+documents `.claude/skills` as the project location. It does not advertise
+`.agents/skills`. A fresh-profile probe of installed Claude Code 2.1.287 confirms
+that narrower behavior in both an ordinary folder and a newly initialized Git
+project: `.claude/skills` fixtures appear in session initialization; the distinct
+`.agents/skills` fixture does not. A shared-name fixture appears once.
+
+The Git-project probe stopped immediately after initialization. It used a
+synthetic API key and a loopback API stub, with nonessential traffic disabled;
+the stub saw only an initialization HEAD request. No model request reached a
+provider, and no real authentication or user configuration was used or changed.
+The earlier ordinary-folder probe retried only against the rejecting local stub
+and was stopped at its 20-second deadline. Neither probe is a successful model
+conversation or onboarding acceptance test.
+
+Receipts: `.cache/claude-skill-discovery.json` and
+`.cache/claude-skill-discovery-git.json`. The old claim in `docs/harnesses.md` that
+this binary loads both directories is not sufficient evidence for a shared
+registry. Keep client discovery paths in their adapters, reuse the same skill
+sources, and qualify discovery and duplicates in each actual client.
diff --git a/hosting/AGENTS.md b/hosting/AGENTS.md
deleted file mode 100644
index f636f689..00000000
--- a/hosting/AGENTS.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# Private hosted service
-
-This package has its own npm lockfile. Cloud dependencies and hosting modules must
-not enter the engine's published package. Keep the OAuth gateway, tenant Worker and
-native evaluator separate; only the gateway receives identity-provider credentials.
-
-For changes here, use the pinned root maintainer tools. First install the root
-dependencies with `bun install --frozen-lockfile` and rebuild the engine with
-`node scripts/build-runtime.mjs all`; the integration fixture imports that actual
-Node bundle. Then run from this directory:
-
-```sh
-npm ci --ignore-scripts
-npm run typecheck
-npm test
-npm run build
-```
-
-The `Hosted gateway checks` workflow runs these gates on Linux and Windows.
-Local workerd fixtures do not establish live OAuth, native evaluation, provider
-isolation or production costs. Test helpers and fault controls must not appear in
-production bundles. Derive MCP tools from the engine registry; do not duplicate
-schemas here. See the root guide for TDD, publication authority and secret handling.
diff --git a/hosting/DEPLOYMENT.md b/hosting/DEPLOYMENT.md
deleted file mode 100644
index dadb82fe..00000000
--- a/hosting/DEPLOYMENT.md
+++ /dev/null
@@ -1,148 +0,0 @@
-# Hosted deployment preparation
-
-This prepares the complete service locally. It does not provision resources,
-upload images, store credentials, configure DNS or deploy a Worker. The generated
-configuration exposes no HTTP route, workers.dev address or preview URL. It is
-not a launch approval or proof that production is ready.
-
-## Build a reviewable candidate
-
-Use the pinned maintainer Node toolchain and installed `hosting/` dependencies.
-Copy `deployment.example.json` to an ignored local manifest. Its placeholders are
-intentionally invalid. Fill it only with verified non-secret resource IDs,
-account-owned registry digests and reviewed numeric quotas. Never add a client
-secret or token; unknown fields are rejected without echoing their values.
-The example's nine-request compute limits are for qualification planning, not public
-launch quotas or a VM-start allowance. A paid run needs its own bounded candidate
-and approval, including child starts and cleanup.
-
-`requestLimits` declares separate edge and account rate-limit namespaces and
-per-minute thresholds. Choose distinct positive integer namespace IDs that are
-unused elsewhere in this Cloudflare account; the provider shares counters across
-Workers with the same namespace. Verify that inventory before deployment. The
-example's 600 ingress requests per route class and 120 authenticated MCP/download
-requests per account are candidate thresholds for qualification, not accepted
-public quotas. Each window is 60 seconds. These are approximate per-location
-limits, separate from the durable compute/storage budgets.
-
-From the repository root:
-
-```sh
-node hosting/scripts/prepare-deployment.mjs \
- --manifest .cache/hosted-deployment-input.json \
- --output .cache/hosted-deployment-candidate
-```
-
-The parent directory must already exist inside `.cache`; the output must be new.
-Existing or partial outputs are never overwritten. The command bundles actual
-production entrypoints, checks their dependency boundaries and exported classes,
-copies all numbered D1 migrations, and records SHA-256 hashes. The receipt records
-the source commit and whether the checkout was dirty. A dirty receipt cannot be
-treated as exact-release source qualification. It also does not attest that the
-specified cloud resources exist, belong to this deployment, or contain the
-expected image bytes; verify those separately before deployment.
-
-Outputs include Cloudflare Build Output plus six equivalent `*.wrangler.json`
-files and `deployment-receipt.json`. Both use pinned `@cloudflare/[email protected]`.
-Its API is currently unstable, so changes require renewed validation. The Wrangler
-conversion corrects only local DO self-bindings; cross-Worker bindings retain their
-explicit target. Use a tested CLI and `--no-bundle` to deploy the reviewed bytes.
-Wrangler `deploy --dry-run --no-bundle --config <file>` checks configuration locally;
-it does not verify remote bindings, image availability, secrets or permissions.
-
-## Service boundaries
-
-| Role | Private capabilities | Public entrypoint |
-| --- | --- | --- |
-| Gateway | Account D1, OAuth KV, edge/account rate limits, four provider secret names, owning tenant DOs, `KilnCompute` | None in prepared output |
-| Tenant | Private R2 and tenant SQLite quotas, saved assets/materials, downloads and retirement | None |
-| Admission | Global admission SQLite and native request DOs | None |
-| Request | Tenant storage, fresh evaluation/render DOs and three host-bound interceptors | None |
-| Evaluation | Pinned software image, evaluator DO and whole-VM cleanup | None |
-| Render | Pinned software image, renderer DO and whole-VM cleanup | None |
-
-Only the gateway declares `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`,
-`GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`; their values must be provisioned
-through the provider's secret mechanism, never committed or copied into this
-manifest. No gateway binding exposes `KilnComputeControl`; a separately authorized
-private operator is needed to pause/resume and inspect admission.
-
-Coordinator/evaluation/render use immutable account-owned registry references.
-The runtime selects the established `standard-1` coordinator and `standard-2`
-child profiles, deadlines and disabled native internet access. The manifest cannot
-choose arbitrary entrypoints, internet settings or instance classes. SSH and
-Container logs remain disabled. Application resource identity and runtime network
-denial still require provider readback and a real trial.
-
-Gateway URLs may contain OAuth codes or private download capabilities. The
-prepared Workers disable persistent invocation logs and traces and request query
-redaction. These settings do not establish a complete observability plan or
-absence of provider-managed operational data. The gateway's Analytics Engine
-binding emits only explicit aggregate fields, and preparation hashes six proposed
-alert queries in `monitoring-candidate.json`. Ingestion, account eligibility,
-thresholds and alert delivery remain launch gates. See [operations](OPERATIONS.md)
-for the schema, retention, expected volume and qualification sequence.
-
-The gateway now limits fixed route classes before OAuth or database work, then
-limits verified accounts across MCP clients and browser downloads before storage
-or native dispatch. No IP, bearer token, cookie, source or arbitrary URL enters a
-counter key. Denial returns 429 with a 60-second retry suggestion; missing or
-failed bindings return 503. Local tests cover these boundaries and real local
-binding exhaustion. No production binding or threshold is deployed yet. Coarse
-ingress exhaustion can temporarily deny every user in the affected route class
-and location; representative load and abuse qualification must assess that
-availability tradeoff. It does not prevent billed Worker invocations or provide
-an exact worldwide request ceiling.
-
-## Ordered deployment and launch gates
-
-1. Qualify the exact source in CI and record the engine archive, coordinator image,
- software image, every Worker/config hash, migrations and resource inventory.
- Provision approved isolated resources separately and read their ownership back.
-2. Apply the D1 migrations to the intended database, after checking identity
- uniqueness and backup/restore handling. Configure provider clients with exact
- approved callback URLs and secret bindings only on the gateway.
-3. Deploy tenant, evaluation and render, then request, admission and gateway, in
- that dependency order. Read back all external namespace/service links. Deploy
- retirement-aware services before accepting deletion; drain older work first.
-4. The gateway configuration includes an every-minute Cron Trigger. Read back the
- deployed trigger and verify recovery after an interrupted deletion. Track the
- oldest pending job, failures and unresolved writes; the source handler alone
- does not prove that scheduled recovery operates.
-5. Complete bounded private qualification of the newer evaluator identity,
- materials, browser downloads, link/unlink/delete, quotas, retention and cleanup.
- Verify live Google/GitHub consent and real MCP clients separately. The earlier
- `c755434` receipt covers only its recorded code and scope.
- The [gateway preflight stage](probe/GATEWAY_PREFLIGHT.md) locally exercises
- the prepared six-Worker topology with synthetic accounts and paused native
- admission. It is a component of the next trial, not live qualification or
- authorization to reuse the prior allowance.
-6. Before public exposure, qualify ingress abuse protection, representative
- load/costs, operational alerts, backup retention/restore, privacy/support pages
- and rollback. Cloudflare's edge rate-limit binding is local and approximate;
- it must not replace global compute admission or be represented as a billing
- cap. Review public quotas and the final cost model with the owner.
- Exercise streamed oversized/unauthenticated/rate-limited requests followed by
- ordinary requests through the real public gateway. Verify client-visible
- 401/413/429 behavior and continued availability; local workerd early-response
- reset reports are not deployed acceptance evidence.
-7. Prepare the exact gateway route change at `kiln.instruktlabs.com` for approval.
- Do not infer permission from preparation or an earlier private-trial allowance.
- Following approved deployment, verify deployed identity, live lifecycle and
- two-user separation before directory submission.
-
-Rollback must preserve primary account revocation and permanent tenant retirement.
-Do not restore pre-deletion code or a backup that reactivates retired accounts;
-pause access and reconcile first. Existing private data must never be silently
-replaced with fresh namespaces to obtain a passing check.
-
-The next private combined candidate is prepared with `--private-lifecycle`; its
-fixed eight-Worker topology, bounds and cleanup procedure are documented in
-[NATIVE_LIFECYCLE.md](probe/NATIVE_LIFECYCLE.md). That mode has no provider secrets
-or public routes and cannot serve as a production launch configuration.
-
-Current references:
-[Cloudflare configuration](https://developers.cloudflare.com/workers/wrangler/configuration/),
-[Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/),
-[Rate-limit scope and accuracy](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/),
-[Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/).
diff --git a/hosting/OPERATIONS.md b/hosting/OPERATIONS.md
deleted file mode 100644
index ee15560a..00000000
--- a/hosting/OPERATIONS.md
+++ /dev/null
@@ -1,121 +0,0 @@
-# Hosted operations and alert qualification
-
-This is implemented locally, not deployed or monitored yet. The complete
-deployment builder emits a gateway `OPERATIONS` Analytics Engine binding and a
-hashed `monitoring-candidate.json`. Its six alert queries are candidates for
-provider validation; none has an enabled destination or delivery receipt.
-
-## Data collected
-
-Only the gateway writes the dataset named `<deployment_prefix>_ops`, replacing
-hyphens with underscores. It records one explicit point per completed HTTP
-handler and two points after each scheduled recovery run. No request/response
-object, body, arbitrary URL, IP, identity, credential, exception or download ticket
-is passed to Analytics Engine. Invocation logs, traces and Container logs remain
-disabled. This does not describe all provider-managed operational records.
-
-Every point has `blob1 = kiln.ops.v1` and `double1 = 1`. Remaining columns are:
-
-| Kind / index | blob2 | blob3 | blob4 | double2 | double3 | double4 | double5 |
-| --- | --- | --- | --- | --- | --- | --- | --- |
-| `http` | http | fixed route class | HTTP status | elapsed ms | unused | unused | unused |
-| `health:deletion` | health | deletion | ok/unavailable | pending jobs | oldest age ms | jobs at least 15 minutes old | recovery handler succeeded: 1/0 |
-| `health:compute` | health | compute | ok/unavailable | paused: 1/0 | active requests | pending cleanup | concurrency limit |
-
-Route classes reuse the bounded ingress categories. HTTP elapsed time ends when
-the handler returns its Response; it does not measure complete browser download
-or model response latency. HTTP 200 does not prove a successful MCP tool result,
-artifact quality or rendering fidelity. Provider CPU/VM/storage usage remains
-separate cost evidence.
-
-Deletion health reads primary D1 using indexed phase selection. Compute health is
-a read-only RPC returning aggregate admission state, with no tenant IDs or pause
-control. Both reads run independently with two-second deadlines. Failed or invalid
-reads emit `unavailable` and numeric `-1`, never healthy zero. Failed recovery or
-unavailable component health also fails the scheduled invocation with a fixed
-message. A telemetry write failure cannot change authorization, returned bytes or
-cleanup. Missing telemetry must be caught by external heartbeat alerts.
-
-The write API is asynchronous; a successful local call is not proof of ingestion.
-Cloudflare documents three-month retention and adaptive sampling. Keep these
-aggregate records distinct from the saved-asset and seven-day unsaved policies.
-[Writing points](https://developers.cloudflare.com/analytics/analytics-engine/get-started/),
-[retention](https://developers.cloudflare.com/analytics/analytics-engine/limits/).
-
-## Alert candidates
-
-The builder emits six queries scoped to the exact account and
-`events.analyticsEngine.<dataset>`, each returning one numeric `value`. They use
-a five-minute lookback, proposed one-minute evaluation and hourly repeat interval.
-
-| Candidate | Trigger | Initial operator action |
-| --- | --- | --- |
-| Deletion heartbeat | No healthy successful recovery observation | Check Cron Trigger, deployed version, D1 and ingestion availability |
-| Compute heartbeat | No available compute observation | Check binding and admission state; preserve active cleanup evidence |
-| Deletion overdue | An observation reports a deletion at least 15 minutes old | Inspect the private recovery job and phase; do not claim completed deletion |
-| Compute cleanup | At least three observations report pending cleanup | Pause expensive work through the private operator; investigate VM shutdown |
-| Gateway errors | At least five HTTP 5xx responses | Separate upstream identity/storage/native failures before changing limits |
-| Gateway rejections | At least 100 HTTP 429 responses | Inspect legitimate demand versus abuse; preserve compute quotas |
-
-These are initial tuning proposals, not an SLA. Counts in sampled data are
-estimates, and the cleanup observations need not be consecutive. Heartbeat
-queries intentionally aggregate without grouping: an empty interval must yield
-zero rather than no result. Confirm that behavior in the actual query preview.
-
-The current Cloudflare Custom Alerts beta supports account-scoped Analytics SQL
-queries. This dialect automatically applies supported sample weights; do not
-paste legacy Analytics Engine queries with `_sample_interval` into it. Catalog,
-plan access and query validation still need live verification for this account.
-[Custom Alerts](https://developers.cloudflare.com/notifications/notification-available/#custom-alerts-beta),
-[Analytics SQL dataset rules](https://developers.cloudflare.com/analytics/sql-api/datasets/#workers-analytics-engine-datasets).
-
-Before public launch:
-
-1. Read back the gateway dataset binding and recurring trigger. Deploy the
- admission health RPC before the gateway that calls it. Missing old RPC support
- is an unavailable observation, not a passing health check.
-2. Query the account catalog with `cf analytics sql introspection get --account-tag <account-id>`
- using authorized Account Analytics Read access. Discover the exact dataset
- after a bounded synthetic request and scheduled invocation produce points.
- For SQL queries that already contain `accountTag`, do not also pass a request
- scope: the current API rejects duplicated tenancy predicates. Use timezone-aware
- ISO 8601 literals for fixed timestamp windows.
-3. Preview each prepared query and verify normal, unavailable, empty-window and
- delayed-deletion cases. Tests currently validate the local schema and query
- construction, not remote query execution or sampling behavior.
-4. Configure an owner-approved operational destination and these thresholds in
- Custom Alerts. Read back the enabled settings and prove both alert and recovery
- delivery. Never assume a configured query will notify anyone. No operational
- email or webhook has been sent by this implementation.
-5. Also configure provider billing/usage alerts and an independent public endpoint
- check. A Cloudflare-wide outage can affect both service and Cloudflare alerts.
- Provider alerts do not impose a spending cap. Keep private pause/restore and
- retirement-safe rollback procedures available during an outage.
-
-## Expected telemetry volume
-
-At one successful scheduled run per minute, the two health points total 86,400
-per 30-day month, plus one point per HTTP invocation that reaches a response.
-For example, one million HTTP requests yields about 1.0864 million points.
-Six alert queries every minute would be 259,200 evaluations per 30-day month;
-confirm Custom Alerts entitlement and charging separately from the data API.
-
-Cloudflare currently publishes 10 million included monthly writes and one million
-read queries for Workers Paid, then $0.25/million writes and $1/million reads;
-the page also says charging has not started yet. Treat those as planning rates,
-not proof of the account's bill. Verify current billing at deployment and include
-other datasets' usage. [Pricing](https://developers.cloudflare.com/analytics/analytics-engine/pricing/).
-
-## Private ingestion evidence, October 7
-
-The account catalog exposed `events.analyticsEngine.kiln_private_lifecycle_v1_ops`
-after the approved lifecycle trial. A scoped query returned the expected fixed HTTP
-route/status categories, including 401, 404, 413 and 429. All six prepared alert
-queries executed successfully. Their empty five-minute windows returned a numeric
-zero row, so heartbeat absence can produce a threshold signal rather than no row.
-The private candidate deliberately had no Cron; this does not prove successful
-scheduled health ingestion, Custom Alerts eligibility, notifications or recovery
-delivery. No alert was created or message sent by these read-only checks.
-
-Receipts are `analytics-*.json` under `.cache/lifecycle-cleanup-4b3dc62/`.
-See the [trial result](../docs/reviews/2026-10-07-private-lifecycle-result.md).
diff --git a/hosting/README.md b/hosting/README.md
deleted file mode 100644
index 052807ad..00000000
--- a/hosting/README.md
+++ /dev/null
@@ -1,960 +0,0 @@
-# Hosted Kiln
-
-This private package contains the hosted service's Worker code and native storage adapters. It is not shipped
-inside `@instruktlabs/kiln` and introduces no cloud dependency into the engine.
-It is not deployed or ready for public traffic. Native provider qualification,
-native dispatch, deployed storage, operational quotas and launch checks remain open.
-
-The [deployment guide](DEPLOYMENT.md) prepares the six-service configuration,
-immutable bundles and migrations locally without creating resources or public routes.
-
-## Local checks
-
-Use the repository's Node 22.23.3 and npm 12.2.0 maintainer toolchain:
-
-```sh
-bun install --frozen-lockfile
-node scripts/build-runtime.mjs all
-cd hosting
-npm ci --ignore-scripts
-npm run typecheck
-npm test
-npm run build
-```
-
-The tests execute the Worker in workerd through the pinned Miniflare package.
-Its 5.x API is currently alpha; the exported v4 option converter supplies the
-documented simulation bindings. Tests replace GitHub responses with fixed identities
-and Google responses with locally signed OIDC fixtures. Routing tests use a recording backend; storage tests use the production
-tenant Worker with real simulated SQLite and R2 bindings. A combined test connects
-both production Workers and verifies authenticated two-user downloads and reconnects.
-Separate test-only fault injection covers late upload acknowledgement and failed
-cleanup. A fixed trusted fixture also runs the actual bundled Node engine against
-the production storage Worker: validate, read, edit, CPU render, saved revisions,
-restore/export and retrieval from a fresh host after storage eviction. Material
-closures survive an export/import and exact offline GLB rebuild. Unexpected external fetches fail. No model,
-real identity provider or cloud deployment is used. These tests do not establish
-untrusted native isolation, deployed persistence, global KV consistency or production capacity.
-
-The separate gateway, tenant, native source-client, native asset-client and native MCP bundles,
-with input/hash/import receipts, are written to
-`../.cache/hosted-worker/`. `build` performs no upload, resource provisioning or
-deployment. `Hosted gateway checks` runs the same checks on Linux and Windows.
-
-## Provider-neutral accounts
-
-`src/accounts.ts` defines a provider-neutral account lookup contract and a D1
-adapter. `migrations/0001_accounts.sql` owns the identity index. Verified canonical
-issuer/subject pairs map to random permanent Kiln IDs; email, provider tokens and
-profile names are not stored or used to merge accounts. Registering an identity
-and its new account is one transaction. Each operation starts a primary-backed
-session, independent of caller bookmarks. Disabled/deleting accounts cannot obtain
-a replacement account through ordinary sign-in.
-
-The workerd tests exercise concurrent first sign-ins, unique issuer/subject pairs,
-rollback after an injected identity-write failure and current account-state reads.
-They do not establish cross-region deployment behavior. Both provider adapters now
-resolve this directory before issuing Kiln grants. Every protected-resource token
-validation, authorization-code exchange and refresh checks the current primary
-account state and authorization epoch. Missing/disabled/deleting accounts and old
-epochs fail closed; database outages return unavailable rather than permitting
-cached access. Account lifecycle mutations must increment the epoch atomically.
-Browser sessions, direct sign-in and explicit identity linking now have local
-qualification. Deployed account/connection controls and completed asset deletion
-remain required before launch.
-Only verified server-side provider adapters may call this contract. The JSON
-interface under `test/` exists solely for local tests and is not a public API.
-
-### Browser account access
-
-`/account` renders sign-in or the current account's linked provider names. Direct
-sign-in and MCP authorization share the verified Google/GitHub adapters and exact
-provider callbacks. Direct sign-in does not register a synthetic MCP client or
-issue MCP tokens. Its `kb1_` state selects a separate D1 transaction namespace;
-the state and an independent browser cookie must both match before a provider
-exchange. D1 atomically consumes the transaction, including cancellation. Stored
-state and cookie bindings are hashed with the service origin and their purpose.
-PKCE verifiers and nonces remain server-side for at most ten minutes. The table
-admits at most 4,096 pending transactions and opportunistically removes expired
-rows. This storage bound does not replace the required public rate/admission limits.
-
-Successful verified callbacks issue a new `__Host-kiln-session` cookie with Secure,
-HttpOnly, SameSite=Lax and Path=/, never Domain. D1 stores only its SHA-256 verifier,
-with a separate CSRF value, account ID and authorization epoch. Sessions expire
-after 30 minutes idle or 24 hours absolute, whichever comes first. Each successful
-read atomically renews only the idle deadline and checks the current primary account
-state/epoch. Fresh sign-in revokes that browser's previous session; at most eight
-sessions remain per account. Rotation at the cap preserves the other seven devices.
-
-Logout requires a same-origin POST, a bounded form and that session's CSRF value.
-It revokes only the browser session; it deliberately leaves MCP connections and
-other devices intact. Browser cookies cannot authorize `/mcp`, and MCP bearer
-tokens cannot authorize account pages. No account selection comes from a form or
-URL. Session issuance accepts only verified server-side identities. A recent
-callback is not proof of a fresh password/MFA challenge. The explicit linking and
-deletion flows below confirm provider control with separate purpose-bound state.
-
-Migrations `0003_browser_sessions.sql` and `0004_browser_logins.sql` add these
-tables. Workerd tests cover expiry, rotation, concurrent callbacks, cross-provider
-and cross-browser rejection, SQL rollback, storage bounds and logout/connection
-separation. The account page uses a nonce-restricted style block and a Google-
-provided button image embedded locally; see [asset provenance](assets/README.md).
-Local desktop/375px layout checks establish presentation only, not live provider
-authentication or final launch acceptance. Privacy pages, full account controls
-and the branded MCP consent experience remain open.
-
-### Connected-app controls
-
-Migrations `0005_connections.sql` and `0006_account_actions.sql` add independently
-revocable MCP connections and purpose-bound confirmation transactions. A connection
-becomes active through one atomic primary-D1 claim during authorization-code
-exchange. Every resource request and refresh checks its current account, epoch,
-client and connection state after the OAuth library's token validation. Stale KV
-records cannot replay an exchanged code or re-enable a revoked connection.
-Connections expire after 30 days; at most 32 pending/active connections are admitted
-per account. Expired pending connections are retired after ten minutes.
-
-`/account` lists connections and accepts a same-origin, CSRF-protected disconnect
-form. Confirmation requires the current browser session, an independent action
-cookie, one-use state, PKCE and a freshly verified identity already linked to that
-account. Google also verifies the OIDC nonce. The primary SQL revocation commits
-before optional OAuth KV cleanup; other connections remain usable. The browser
-session rotates after confirmation. This blocks subsequent requests; it does not
-cancel already admitted computation. Public rate/admission controls remain required.
-
-Both providers' `prompt=select_account` asks the user to choose an account; it
-does not prove a new password or MFA challenge. Sources:
-[GitHub OAuth](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps),
-[Google OIDC](https://developers.google.com/identity/openid-connect/openid-connect).
-Identity linking uses its separate purpose-bound flow below. This disconnect flow
-must not be repurposed to merge or delete accounts.
-
-Local workerd checks cover concurrent callbacks, cancellation, expiry, copied
-state, wrong identities, revoked sessions, forged forms, hostile client names,
-oversized requests and retained access by another connection. Layout checks use
-synthetic identities only. Live provider confirmation, cross-region denial and
-production migration/rollback remain unqualified.
-
-### Explicit sign-in method changes
-
-Migration `0008_identity_actions.sql` adds separate linking transactions, a unique
-provider-per-account constraint and bounded account security activity. Apply it
-before the new gateway. It leaves existing accounts and identity keys intact;
-preflight the uniqueness constraint against any existing database before migration.
-The earlier gateway can run with these additive tables, but rollback must preserve
-committed identity changes and authorization epochs, not restore an old database.
-
-`/account/identity` accepts only a bounded, same-origin, CSRF-protected form from a
-current browser session. Adding a method confirms an existing provider first,
-then authenticates the new provider using a new state, cookie, PKCE verifier and
-nonce. Each phase expires after five minutes and is atomically consumed before
-provider I/O. Both callbacks are tied to the original session and current account
-epoch. Account, session and confirmed-identity checks run again inside the final
-database transaction. An identity owned by another account is refused; email is
-never compared, and existing libraries cannot be merged.
-
-Removing a method confirms control of the other method that will remain. The last
-method cannot be removed, including concurrent requests from different browsers.
-Each successful change updates the identity, appends a security event, increments
-the account epoch and revokes all browser sessions atomically. Existing MCP access
-and refresh credentials fail their primary state checks even if provider KV still
-contains the old grants; those records expire under their existing TTL. Users sign
-in again and reconnect their apps. Already admitted jobs are not cancelled by this
-change. The permanent account ID and asset/usage namespace stay unchanged.
-
-The UI explains these effects before confirmation and shows the latest 20 security
-events. Events record provider, action and time, without tokens, email or IP address.
-Pending intents are capped at four per account and 4,096 globally. These limits do
-not replace public rate limits. Session deletion cascades to pending confirmations.
-The success page and activity list are **in-app notices only**, as selected by the
-owner for v1. Out-of-band security email and verified contact collection are deferred,
-not implemented or qualified. Provider confirmation can reuse an existing provider
-session; it is not evidence of a fresh password or MFA challenge. No assurance-level
-certification is claimed.
-
-Workerd fixtures exercise real gateway, provider validators and D1 transactions
-with mocked upstream providers: both link directions, stable account ownership,
-foreign-identity refusal, cancellation, expiry, replay, concurrent callbacks,
-concurrent unlink, database rollback, revocation during provider I/O, old access
-and refresh denial, CSRF/origin/bounds and hashed transaction storage. Live OAuth,
-provider UI and external notification delivery remain launch work. Sources checked
-6 October 2026:
-[OWASP federated linking](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#secure-federated-account-linking),
-[NIST federation account management](https://pages.nist.gov/800-63-4/sp800-63c.html),
-[D1 transactions](https://developers.cloudflare.com/d1/worker-api/d1-database/#batch).
-
-### Account deletion
-
-The account page requires explicit acknowledgement and confirmation through a
-linked Google/GitHub identity. The bounded same-origin POST starts a five-minute,
-one-use flow bound to the current browser session, account epoch and provider.
-Cancellation leaves the account unchanged; an unrelated identity cannot confirm
-deletion. The callback rechecks account/session ownership after provider I/O.
-It then atomically creates a durable D1 deletion job, sets the account to
-`deleting`, increments its epoch, revokes connections and removes browser sessions.
-No external cleanup begins before that transaction commits. Old access and refresh
-tokens are denied by primary account state, including during retries.
-
-The cleanup order is verified compute retirement, storage retirement, OAuth grant
-cleanup, then identity/account removal. `KilnCompute.retireTenant`
-durably denies new work and waits for cancellation of the selected account's
-coordinator and children. Unknown cleanup keeps its admission slot and recovery
-alarm. Other accounts continue; global usage counters retain already-admitted
-costs. An opaque account-derived deny record survives eviction and pause/resume.
-
-The tenant's private `/internal/account-deletion` accepts only an empty POST from
-the owning service binding. The native coordinator's storage allowlist rejects
-that administrative path. Retirement removes download tickets and saved revision
-metadata, denies all normal tenant operations and purges the exact R2 prefix in
-bounded batches. Durable markers retain unresolved uploads: an HTTP timeout or an
-empty bucket listing does not establish that a write cannot arrive later. A
-settled put or matching committed immutable R2 bytes permits cleanup. A crash
-with neither kind of evidence remains pending with daily recovery; it must be
-reported as incomplete and escalated, never silently declared erased. Earlier
-ordinary maintenance cannot discard those markers or recreate state after purge.
-
-`purged` requires zero unresolved writes, zero artifact rows and a final empty R2
-listing. It removes the storage alarm but preserves the small permanent deny
-record. Already-delivered files cannot be recalled. These checks concern active
-application storage; provider backups/retention need their separate launch policy.
-Use the deletion controller only after every compute/storage instance runs this
-contract and older uploads have drained. Rolling back to code that ignores these
-records after accepting a deletion would be unsafe; pause service instead.
-
-`D1AccountDeletions` leases each phase for 60 seconds. Recovery admits at most
-four phases within a 25-second work budget; external steps have a maximum
-20-second deadline. Incomplete cleanup retries after a minute; errors back off
-to at most an hour. Expired leases can be recovered; replaced leases cannot
-advance another worker's job. Grant cleanup uses the pinned OAuth library's
-public helpers, up to four grants per step, and clears known D1 grant IDs only
-after revocation acknowledges them. Identity/account removal and completion are
-one guarded transaction. Errors never record provider responses or exception text.
-
-The private status page requires a random HttpOnly receipt cookie; D1 stores only
-its purpose-bound hash. A support reference cannot read the receipt. Completed
-receipts lose their account mapping and expire after seven days; the browser
-cookie has a 30-day upper bound to cover pending cleanup. A returning user gets
-a new empty account, never the retired tenant. Completion means removal from the
-active service. Already-downloaded copies cannot be recalled. Eventually
-consistent OAuth KV records or concurrent, already-authorized token writes may
-outlive inventory cleanup but cannot restore access. Access-token records expire
-after 15 minutes and refresh-token records after 30 days. Provider backups need
-separate retention disclosure and a restore procedure that preserves revocation.
-
-Apply additive migration `0009_account_deletion.sql` after the earlier account
-migrations and deploy retirement-aware compute/storage before the gateway.
-The gateway provides a scheduled recovery handler and a bounded immediate attempt
-after confirmation. Production must configure and verify a recurring Cron Trigger
-(initially every minute), monitor old pending jobs and escalate unresolved writes.
-No trigger or public deployment has been created by these source changes.
-
-Local workerd tests exercise real gateway/D1/OAuth-helper/tenant/R2 cleanup with
-mocked upstream identity exchange and a no-VM compute fixture, including old-token
-denial, another account's continued access and fresh sign-in after deletion.
-Fault tests cover rollback, stale proofs, callbacks, lease takeover, actual
-deadline/late completion, late writes, unknown acknowledgements, failed R2
-deletion, eviction/retry, overlapping maintenance, prefix isolation and bounded
-orphan batches. Live provider deletion, scheduled recovery, operations escalation
-and public retention disclosures remain launch gates. References:
-[D1 transactions](https://developers.cloudflare.com/d1/worker-api/d1-database/#batch),
-[Scheduled handlers](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/),
-[KV consistency](https://developers.cloudflare.com/kv/concepts/how-kv-works/),
-[R2 consistency](https://developers.cloudflare.com/r2/reference/consistency/),
-[R2 durability](https://developers.cloudflare.com/r2/reference/durability/),
-[Durable Object alarms](https://developers.cloudflare.com/durable-objects/api/alarms/).
-
-## Native HTTP adapter
-
-`src/native-mcp.ts` serves the installed engine's registry through the MCP SDK's
-Streamable HTTP handler, including stateless compatibility for the 2025 protocols.
-The gateway preserves the current protocol's `mcp-method` and `mcp-name` headers.
-Both boundaries reject a supplied browser Origin other than the configured public
-origin. The native endpoint accepts only its fixed private hostname and path and
-refuses forwarded credentials or caller-selected tenant headers.
-
-The production loader first verifies the installed isolated evaluator. Failure
-leaves the host unavailable; there is no trusted execution fallback. Each request
-gets a fresh engine context with the native ProgramStore and AssetLibrary adapters.
-The outside container controller must bind storage to one verified tenant; it has
-not been implemented or qualified on Cloudflare. No public native port is opened.
-
-Admission defaults to one active request, with a 1 MiB request bound, 120-second
-whole-request deadline and 64 MiB streamed response ceiling. Evaluation has a
-60-second maximum deadline. These are implementation bounds, not measured launch
-capacity or global quotas. Disconnects and response cancellation abort storage
-and evaluation. An evaluator that has not settled keeps its occupied slot even
-after the HTTP response ends; the future controller must enforce process cleanup.
-
-The local HTTP tests run real registry tools against the production storage Worker:
-validate, CPU render, save, restore and exact source retrieval after reconnect.
-They also check protocol compatibility, cross-tenant denial, cancellation, stalled
-bodies, response limits and refusal of an unqualified evaluator. They deliberately
-use a fixed trusted render fixture and do not establish provider isolation.
-
-## Authorization and tenant routing
-
-`src/worker.ts` combines the OAuth authorization server and protected resource
-server using `@cloudflare/[email protected]`. Their logical roles remain
-separate. The canonical resource is `PUBLIC_ORIGIN + /mcp`; origin is operator
-configuration, never a forwarded header. HTTP origins other than that configured
-HTTPS origin are refused.
-
-The Worker serves resource/issuer discovery, client registration, browser consent,
-authorization-code exchange, refresh and revocation. Client ID Metadata Documents
-are enabled; the deployed Worker must set `global_fetch_strictly_public` to bound
-their network fetches. Dynamic registration is retained for client compatibility.
-Registration and other public endpoints still need operational admission limits
-before deployment.
-
-The owner selected Google and GitHub sign-in for free hosted v1 access, private
-saved assets and personal quotas; email can follow. The local package needs no
-Kiln account. GitHub requests no repository scopes, uses upstream S256 PKCE and
-resolves the immutable user ID for every login. Google uses `[email protected]`
-for discovery, code exchange, nonce/issuer/audience/expiry checks and application-level
-signature verification. It requests `openid profile`, uses S256 PKCE, rejects a
-foreign `azp`, and canonicalizes Google's two documented issuer spellings. Network
-responses are bounded and redirects/foreign endpoint origins are refused. Upstream
-access/ID tokens are discarded at the adapter boundary; only verified issuer/subject
-pairs enter the account directory. Login names and email never select a tenant.
-
-The gateway needs `ACCOUNTS` bound to D1 with all numbered migrations applied, plus
-`GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GITHUB_CLIENT_ID` and
-`GITHUB_CLIENT_SECRET`. Register exact `/oauth/google/callback` and
-`/oauth/github/callback` URLs under the configured `PUBLIC_ORIGIN`, using separate
-test and production provider apps. Google OAuth branding now exists in testing
-mode; no live database or provider client secret has been provisioned by this
-implementation. Existing prototype provider-derived grants
-are deliberately invalid; no deployed user migration is being claimed. See the
-[authentication architecture review](../docs/plans/2026-10-05-v1-publication-plan.md#authentication-architecture-review-6-october)
-for the selected provider-independent boundary, library comparison, KV consistency
-limits and required deployed checks. Equal email addresses never imply permission
-to merge accounts or libraries.
-
-Launch requires a clearly branded Kiln / Instrukt Labs connection page, a verified
-service domain, a plain explanation of the granted access, privacy/support links
-and usable disconnect/deletion controls. The current minimal consent page is not
-the accepted launch design. Verify actual provider consent, denied
-and cancelled sign-in, token expiry/revocation and cross-user access on the deployed
-service. Local fixtures are not acceptance of that end-user experience or its
-deployed security. Keep provider credentials only in the gateway's secret bindings;
-never send them to an evaluator, log them or store them with artifacts.
-
-Consent names the requesting client, verified domain when available, callback
-host, scopes and loopback warning. The library binds consent and upstream state
-to HttpOnly, Secure browser cookies; the form additionally checks its exact
-origin. Client-supplied strings are escaped. The page forbids scripts and framing.
-`src/login-intents.ts` adds atomic D1 claims after the library's browser validation:
-one consent choice per handle, and one callback per origin/state/provider/purpose
-intent. The database stores hashes, not raw state, verifier or nonce. Consent claims
-last one day (longer than the library's ten-minute transaction); upstream intents
-last ten minutes. Indexed cleanup removes at most 128 expired rows per write.
-Replayed stale KV snapshots and concurrent D1 claims are exercised locally.
-The `kiln:use` scope permits the engine's asset lifecycle, including deletion;
-`offline_access` permits a renewable connection with a fixed 30-day lifetime.
-Access tokens expire after 15 minutes. Revocation uses the advertised endpoint.
-Production KV propagation means the local revocation test does not promise
-instant global revocation; this needs explicit operational qualification.
-
-Verified permanent Kiln account IDs alone select a Durable Object, using a versioned
-hash of the configured Kiln origin and account ID. Reconnecting through another
-client selects the same tenant. Different provider identities are separate until
-an explicit linking flow is implemented; matching email or subject strings do not
-merge their accounts.
-Bearer tokens, cookies, session ids, caller tenant headers and program references
-cannot choose the object. Only bounded MCP transport headers and request bodies
-cross the private binding. The tenant backend must still authorize all references
-inside its own storage; this gateway does not treat an opaque reference as access.
-
-The resource handler currently forwards `/mcp` and authenticated downloads at
-`/mcp/artifacts/<opaque-id>`. It defines no tools: the native backend must derive
-its MCP surface from the engine registry. API bodies are bounded to 1 MiB while
-reading; OAuth bodies to 16 KiB, with a ten-second read deadline. Resource URLs
-reject query parameters, including bearer credentials. Responses are not cached,
-and application error responses omit raw exceptions and upstream responses.
-
-## Required deployment bindings
-
-| Binding | Purpose |
-| --- | --- |
-| `PUBLIC_ORIGIN` | `https://kiln.instruktlabs.com`; final environment must verify ownership/TLS |
-| `OAUTH_KV` | Dedicated OAuth records, separate from user artifacts |
-| `GITHUB_CLIENT_ID` | Dedicated identity app's id |
-| `GITHUB_CLIENT_SECRET` | Worker secret; never source, CI output or a browser variable |
-| `TENANTS` | Private namespace of the separate tenant Worker; not a public evaluator endpoint |
-
-Keep OAuth and GitHub secrets out of that separate tenant Worker and all evaluator
-containers. Final deployment configuration must bind the real reviewed resources;
-there is deliberately no deploy command or fabricated namespace id here.
-
-The tenant Worker requires a SQLite-backed `KilnTenant` namespace, private R2
-`ARTIFACTS` binding and positive integer `STORAGE_MAX_BYTES`, `STORAGE_MAX_OBJECTS`
-and `STORAGE_MAX_GROUPS` limits. The test limits are fixtures, not launch quotas.
-Its default HTTP handler returns 404; private operations are available only through
-the Durable Object binding. Neither identity secrets nor OAuth KV are bound to it.
-
-## Artifact storage boundary
-
-Each tenant owns SQLite records and an isolated R2 key prefix. Uploads stream to R2
-with an exact declared length, SHA-256 check and 64 MiB per-object ceiling. An
-atomic reservation counts in-progress uploads against byte and object quotas before
-external storage starts. A sixty-second deadline covers the stream and R2
-acknowledgement. Timed-out or failed writes never become readable; cleanup retains
-their quota reservation until object deletion succeeds. A late acknowledgement can
-only trigger cleanup. Private declarations use safe basenames and known media types.
-
-Unsaved bytes expire seven days after upload, and reads do not extend that clock.
-Immutable saved groups atomically pin their file inventory until deletion. Group
-metadata counts toward the tenant byte quota; a separate group-count ceiling also
-bounds small-record growth. Repeating an identical save is idempotent; reusing an
-active logical key with different contents is refused. Keys are database values,
-never filesystem paths. A group deletion removes only files with no other saved
-group reference. Server-generated blob and group ids are never reused.
-
-Downloads require a live record in the selected tenant, not possession of an id.
-They recheck access after the external read and validate stored length/checksum
-metadata. Responses stream bytes as private attachments with no caching. Bearer
-authorization is required through the gateway; browser-friendly download tickets
-and the engine's `assetDownloadUrls` adapter are not implemented yet.
-
-Alarms expire unsaved rows, retry deletion and reconcile aged orphan R2 objects in
-bounded batches within one tenant prefix. Daily reconciliation remains scheduled
-after ordinary artifact deletion to catch late interrupted writes. Account deletion
-must retire its alarm only after outstanding work and cleanup have completed;
-that owner/account lifecycle and its operating costs still need qualification.
-
-This storage layer now supplies the engine's `ProgramStore` and `AssetLibrary`
-contracts as described below. The standalone MaterialLibrary and production native
-dispatch remain open. The private `/mcp`
-endpoint deliberately returns 503 until native integration is configured and
-qualified. Evaluation and registry-derived tools must be connected
-and tested before declaring H2/H3 done.
-
-Storage references: [SQLite Durable Objects](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/),
-[R2 Worker API](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/).
-
-## Durable source references
-
-`HostedProgramStore` implements the existing engine interface and imports its
-portable `src/program-store.ts` reference/Unicode/size helpers directly. It creates
-no cloud dependency in that module or the published package. Hosted CI also runs
-when this shared module changes. The tenant bundle includes the exact helper source
-in its input/hash receipt; it does not import the renderer or native evaluator.
-
-Canonical references remain `sha256:<digest>`. The host emits the engine's supported
-full-digest `p_<64 hex characters>` handle, avoiding an indefinitely growing alias
-table and preventing an expired prefix from being reassigned. It does not resolve
-unissued shorter prefixes. References are opaque identifiers, not access tokens;
-every lookup searches only the current tenant's retained source bytes.
-
-Source is valid Unicode encoded as exact UTF-8, including a leading BOM when
-authored, and is limited to the engine's existing 1 MiB bound. Use a byte-preserving
-decoder when bridging this API: ordinary `Response.text()` can strip that BOM.
-Every read verifies bytes against the engine's canonical reference. An idempotent
-put also verifies the existing source and does not repair corruption silently.
-Concurrent identical puts share one upload. After object eviction, the durable
-content index resolves the same artifact without relying on the in-memory map.
-
-The source store shares file/object quotas with GLBs and other tenant artifacts.
-Quota exhaustion never evicts existing work. Identical puts and reads do not renew
-expiry; explicit resubmission after expiry creates a fresh retained copy. A saved
-group can pin its source artifact until deletion. Source stats count live distinct
-source snapshots, whereas total tenant usage also includes other files and pending
-cleanup. The `retention` property tells tool callers about the seven-day unsaved
-lifetime; `eviction: none` means no capacity-driven eviction.
-
-The private binding serves source creation, reads and stats at `/internal/programs`
-and `/internal/programs/<reference>`. Source creation returns its reference and
-artifact id. Saved asset records currently retain their own exact source artifact;
-cross-adapter source deduplication is not implemented.
-These paths are not public gateway endpoints or new MCP tools. The native client
-and its engine integration tests are described below. Production native dispatch,
-and the complete deployed edit/render/save/reconnect flow remain open.
-
-## Native source client
-
-`NativeProgramStore` implements the same engine contract over bounded HTTP. It
-accepts no tenant selector, credentials or configurable URL. Its only destination
-is `http://kiln-storage.internal/internal/programs`; redirects and cookies are
-disabled. A future controller must register a scoped outbound interceptor for
-that hostname and select the tenant outside the container. Cloudflare documents
-virtual-host HTTP access to Worker bindings and `interceptOutboundHttp` on the
-Durable Object Container API. The intended container configuration disables Internet
-access and permits only this intercepted hostname. This integration still needs
-implementation and testing on the provider.
-[Worker connections](https://developers.cloudflare.com/containers/configuration/workers-connections/),
-[Container API](https://developers.cloudflare.com/containers/api/durable-object-container/).
-
-The client rejects malformed references and source before sending, verifies
-returned source hashes and exact UTF-8 bytes, and bounds streamed source to 1 MiB
-and response metadata to 2 KiB. Its configurable deadline defaults to 15 seconds
-and includes both response headers and body reads. Request cancellation must be
-supplied from the native host's per-request context. It cancels stalled reads,
-cleans up late responses and returns fixed errors instead of network diagnostics,
-upstream bodies or caller-supplied abort reasons. Reads never create an authority
-to access another tenant's source.
-
-The six native-client checks include actual registry tools with a fixed trusted
-fixture, source preservation after editing, new host construction, storage eviction,
-cross-tenant denial, integrity failures, size limits, deadlines and cancellation.
-This fixture explicitly uses `trusted-local`; it is test code excluded from production
-bundles. The production host still requires `evaluator-required` and qualified
-isolation. `/mcp` remains unavailable until that host is configured and qualified.
-The client uses standard Fetch types in a separate TypeScript check; Worker code
-continues to use the Cloudflare runtime types.
-
-## Private evaluator client
-
-`createNativeEvaluatorPort` speaks the published SDK's versioned evaluator
-protocol over `http://kiln-evaluator.internal/evaluate`. It accepts no URL, tenant
-selector or credentials. The SDK owns request construction, response identity,
-GLB and QA validation. This client applies the private host's ceilings: 60 seconds,
-4 MiB request/GLB and 8 MiB response. Invalid controls fail before dispatch;
-larger valid caller allowances are clamped to these limits.
-
-Storage, evaluation and rendering share bounded stream/cancellation handling, but have
-separate fixed origins, paths and allowed headers. Network diagnostics, abort
-reasons and upstream bodies do not become public errors. A failure never selects
-an in-process fallback. Tests exercise the real MCP render/save/reconnect flow
-through this protocol using a fixed trusted evaluator fixture; that fixture is
-not cloud isolation evidence.
-
-The provider controller binds this intercepted hostname to a fresh job and retains
-global admission until verified VM destruction. The complete deployed flow still
-needs qualification. A returned HTTP timeout does not prove cleanup. The
-existing default native loader still fails closed on missing nested isolation;
-no production configuration or public endpoint is enabled by this client.
-
-`evaluation-worker` supplies a private `KilnEvaluationJob` Durable Object and
-returns 404 from its default HTTP handler. Its private request handler admits
-only the fixed evaluation route, bounded JSON and numeric execution limits;
-request reading consumes the same deadline. It delegates execution and its alarm
-to `ContainerEvaluationJob`, awaiting its verified cleanup before returning output.
-No source, identity, executable or image selector is accepted through headers.
-The native client and this handler are exercised together with the actual SDK
-codec. The externally tenant-bound dispatcher and global admission controller are
-implemented below; end-to-end provider qualification and deployment remain open.
-
-The private evaluation DO also exposes `cancel()` to its parent dispatcher. One
-controller lives for the DO instance, so cancellation reaches an evaluation still
-waiting to claim its durable record. A cancelled child that has not arrived gets
-a permanent terminal record; later delivery cannot start it after object eviction.
-For active work, the cancellation flag and immediate recovery alarm are persisted,
-then the caller waits for confirmed whole-VM cleanup. Failed cleanup keeps the
-record unfinished and schedules recovery. Repeated cancellation and its alarm
-share the pending cleanup. The parent must retain admission whenever cancellation
-fails or its acknowledgement is lost. These cases have local adversarial tests;
-the new parent-cancellation RPC still needs provider qualification.
-
-## Private software rendering
-
-`createNativeRenderPort` sends only a self-contained GLB and validated view options
-to `http://kiln-renderer.internal/render`. It accepts no URL, source program,
-tenant, image or credential selector. The versioned response must match the exact
-request ID, GLB digest, view count, camera values, dimensions and presentation rig.
-Only the fixed software Vulkan backend is admitted. Engine `captureViewsViaPort`
-continues to own PNG validation, its deadline and truthful CPU degradation; this
-transport never implements a second fallback policy.
-
-The private limits are 4 MiB GLB, 6 MiB request, 20 MiB wire response, 12 MiB PNG
-bytes, 1,024 pixels per dimension and 3,145,728 pixels across requested images.
-The MCP host admits 8,388,608 pixels including grid composition and a 12 MiB
-capture output. The render deadline is 30 seconds, bounded further by the parent
-deadline. This is a qualification candidate, not a measured production latency
-promise; the earlier six-view provider fixture took 13,286 ms including cleanup.
-
-`render-worker` exposes only the private `KilnRenderJob` DO. It shares evaluation's
-HTTP limits, one-use durable lifecycle, cancellation fence, alarm recovery and
-whole-VM destruction through fixed host profiles. `RENDERS` must bind this class;
-its immutable named image is `renderer`. `EVALUATIONS` remains a separate binding
-with image `kiln`. No request can select the profile or executable. The renderer
-runs `/opt/kiln/render.mjs` as `1000:1000` with networking disabled and no secrets.
-Its input and self-contained GLB are checked before graphics initialization. The
-entry explicitly selects the pinned Mesa ICD because native exec does not inherit
-the image's environment.
-
-Local Docker qualification exercises that actual entry and installed port, producing
-eight independently decoded PNGs across three backdrops, a beauty image and an
-exact camera. Real workerd loopback/RPC tests verify host-owned routing and reject
-forged identity fields. These do not qualify the integrated Cloudflare path. See
-[the image procedure](container/README.md#one-shot-software-render-entry).
-
-## Private request dispatcher
-
-`request-worker` adds one `KilnNativeRequest` Durable Object per admitted MCP
-request. Its private `run` RPC accepts the verified tenant hash and an absolute
-deadline of at most 120 seconds. The tenant and child-job inventory remain in
-Durable Object storage, outside the coordinator VM. That VM starts offline from
-the pinned `coordinator` image with only the public origin in its environment.
-Readiness and image readback precede sending the bounded MCP request.
-
-Three fixed HTTP interceptors use host-configured loopback binding props to select
-the request object. Storage RPCs select the tenant from its durable record; URLs,
-headers and body fields cannot choose it. The storage route allowlist excludes
-administrative operations. This uses the documented Container interception API
-and Worker loopback props. Local workerd checks exercise the actual RPCs, tenant
-storage and object eviction, including cross-account source denial. Deliberate
-HTTP errors are converted to responses before RPC serialization, which does not
-preserve their custom JavaScript prototype.
-
-Each request admits at most one active child evaluation or render and eight
-children in total. Every child ID and kind is persisted before dispatch and receives at most the
-remaining parent deadline. A child's cancellation acknowledgement is required
-before another child can start. Completion or cancellation first closes the
-durable request to new work, then confirms destruction of the coordinator and
-all registered children, routing cancellation by their persisted kind. Unknown cleanup retains the record and a recovery alarm;
-late delivery is refused through the child's durable cancellation fence. Parent
-responses are bounded to 32 MiB and withheld until cleanup completes.
-
-The default Worker route remains 404. The gateway uses the private admission
-binding described below and returns 503 for native calls when it is absent. No production
-configuration, public route or new Cloudflare job is enabled by these modules.
-Provider qualification must test the coordinator/interceptor/child flow together;
-local state-machine and workerd tests do not establish that live boundary.
-
-Sources: [Container API](https://developers.cloudflare.com/containers/api/durable-object-container/),
-[loopback binding props](https://developers.cloudflare.com/workers/runtime-apis/context/#specifying-ctxprops-when-using-ctxexports),
-[RPC Request and Response transport](https://developers.cloudflare.com/workers/runtime-apis/rpc/#readablestream-writablestream-request-and-response).
-
-## Shared compute admission
-
-`admission-worker` owns one global `KilnAdmission` SQLite Durable Object. The
-gateway receives only a named `KilnCompute` service binding as `NATIVE_COMPUTE`;
-that entrypoint always selects `global-v1`. It cannot accept a caller-selected
-admission object or expose operator controls. Artifact downloads continue through
-tenant storage without starting compute. The authenticated edge path below serves
-metadata and helper discovery without a coordinator or compute reservation.
-
-An admitted request reserves one coordinator and at most one active child VM.
-One request per account and the configured global concurrency limit are enforced
-atomically with per-account minute/day and global day/month attempt counters.
-Counters use UTC calendar windows. Failed admitted work consumes its attempt;
-rejected work does not. There is no queue of unbounded pending requests.
-429 responses include `Retry-After`. Required settings have no implicit defaults:
-
-| Setting | Meaning |
-| --- | --- |
-| `COMPUTE_MAX_CONCURRENT` | Concurrent request trees; implementation ceiling 16 |
-| `COMPUTE_TENANT_PER_MINUTE` | Admitted requests per account per UTC minute |
-| `COMPUTE_TENANT_PER_DAY` | Admitted requests per account per UTC day |
-| `COMPUTE_GLOBAL_PER_DAY` | All admitted requests per UTC day |
-| `COMPUTE_GLOBAL_PER_MONTH` | All admitted requests per UTC month |
-| `COMPUTE_DEADLINE_MS` | Absolute request lifetime, at most 120,000 ms |
-
-These are configuration controls, not adopted launch quotas or an invoice cap.
-Provider measurements must include both VM types, cold starts, retries, and
-non-compute services. The global ceiling is a validation bound, not demonstrated
-capacity. Launch values and total capacity still require measurement.
-
-The reservation and recovery alarm commit together before the parent RPC. A
-deadline or disconnect triggers out-of-band parent cancellation. Admission is
-released only after the parent confirms whole-tree cleanup, including children
-and its durable fence against late requests. Unknown cleanup suppresses output,
-retains capacity, and schedules another recovery attempt. Eviction and elapsed
-time never free a slot by themselves. Expired usage counters are cleaned in
-bounded batches. No OAuth credentials or source content enter admission storage.
-
-The separate private `KilnComputeControl` binding exposes pause/resume and
-aggregate status. Bind it only to an authenticated operator service. Pause is
-durable, rejects new compute and attempts cancellation of every active request;
-unconfirmed cleanup remains visible in `pendingCleanup` and retains its slot.
-Resuming does not bypass those reservations or reset usage counters.
-
-Local workerd tests cover the actual SQLite/RPC boundary, concurrent admission,
-quota rollover, operator separation, eviction/recovery, stalled calls and a
-response/cancellation race. The race test reproduced a discarded response body
-left open and now verifies its closure. No new cloud qualification is implied.
-Implementation follows the current [SQLite transaction contract](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/#transaction)
-and [alarm contract](https://developers.cloudflare.com/durable-objects/api/alarms/).
-Production configuration and the final deployment remain open. A bounded private
-integration at `c755434` passed the render/save/reopen/export lifecycle, tenant
-denial and quota rejection; see the
-[qualification receipt](../docs/reviews/2026-10-06-hosted-integration-receipt.json).
-That evidence does not qualify later changes or a public service.
-
-For a reviewed private integrated probe, `scripts/build-integrated-probe.mjs`
-emits both Cloudflare Build Output and `wrangler.json`, pointing to the same
-compiled module. Use the generated Wrangler configuration with `--no-bundle`;
-a `--dry-run` validates locally before any approved deployment. The tested
-Wrangler version is `4.147.0`. `cf 1.0.0-beta.12` converts same-Worker Durable
-Object bindings into external `script_name` references and rejects the Container
-bindings. The Wrangler output uses local bindings while preserving exports,
-images, quotas and disabled public routing. The script only builds local files;
-it does not provision or deploy anything, and rebuilding creates a new candidate
-that must be qualified separately.
-
-## Authenticated edge discovery
-
-After the same OAuth scope, account and connection checks used by native calls,
-the gateway serves initialization, protocol discovery, tool/resource lists and
-static `kiln_discover` queries directly in the Worker. Ping, notifications, malformed
-JSON and unknown tool names also stay on that path. No storage or native service is
-available to its handler. Source operations, resource reads and live capabilities
-still go through shared admission. Routing inspects the bounded JSON body; a
-forged `mcp-method` header cannot turn metadata into native execution. Both paths
-use the maintained MCP handler, with stateless legacy compatibility. HTTP responses
-remain `no-store`; protocol cache hints apply only to fixed public definitions.
-
-`node hosting/scripts/edge-manifest.mjs --write` captures metadata from the actual
-engine server with the hosted storage surface. Its sentinels throw if any host
-service is invoked. The build checks the committed snapshot; it never silently
-updates it. The actual native HTTP fixture independently checks every tool schema,
-resource, template and initialization field against that snapshot. Helper results
-and validation diagnostics are compared with the engine host. The Worker imports
-only the pure discovery algorithm/schema and a generated catalog, not the Node
-engine, renderer or evaluator. The `workerd` build condition selects the MCP SDK's
-Worker-compatible schema validator without runtime code generation.
-
-The independent installed-image workflow uses `npm run build -- --native-only`.
-That path builds only the private Node adapters, without loading checkout engine
-bundles or generated edge metadata. An isolated-checkout test verifies it with no
-`dist/` or `lib/`; the normal build still requires metadata parity. This preserves
-the image workflow's qualification against the published npm archive.
-
-Real workerd tests cover modern discovery, legacy initialization, malformed
-messages, forged routing headers, missing native bindings and primary-database
-revocation despite retained OAuth KV records. No authentication or compute quota
-is bypassed for operations that require native execution. Provider startup/cost
-measurements and final hosted-specific instructions remain launch checks; the
-current instructions deliberately match the published engine verbatim.
-
-Sources: [MCP discovery](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2026-07-28/server/discover.mdx),
-[Cloudflare stateless MCP guidance](https://developers.cloudflare.com/agents/model-context-protocol/guides/remote-mcp-server/).
-
-## Private Node host
-
-`native-host` adapts the MCP Fetch handler through the maintained
-`@modelcontextprotocol/node` adapter. It listens only inside the coordinator VM
-on port 3000, requires the fixed `kiln-native.internal` Host and exposes a minimal
-`/_ready` route. Header/body bounds, an upload deadline and client-disconnect
-propagation precede the MCP handler's own execution and response limits. A chunked
-body flood may close the socket before the adapter can deliver its 413 response;
-either outcome must occur before MCP dispatch.
-
-`container/serve.mjs` requires an exact HTTPS public origin and selects the explicit
-remote evaluator profile. Missing private storage or evaluation services fail
-closed; they never enable in-process source evaluation. The default local loader
-still retains its separate isolation requirements. Neither profile is an automatic
-fallback for the other.
-
-Build and qualify the minimal image through
-[the container instructions](container/README.md#private-mcp-coordinator-image).
-Local Docker evidence establishes installed MCP startup, protocol compatibility
-and request rejection. It does not establish Cloudflare routing or tenant
-isolation. The outside dispatcher must bind the storage/evaluation interceptors,
-retain admission through all child-job cleanup and destroy the coordinator VM.
-
-## Native saved assets
-
-New saves through the Container profile record
-`build.engine: cloudflare-container:sha256:<image digest>`. The outside controller
-inspects the running evaluator image and only releases its digest with the exact
-output after whole-VM cleanup succeeds. The coordinator requires this private
-response header and the SDK's validated evaluator response. A request-local,
-bounded proof map binds the digest to exact source and GLB hashes; saving different
-bytes or missing proof fails before uploading assets. The evaluator's stdout,
-authored source and caller request headers cannot select this identity.
-
-The digest identifies the immutable evaluator image, including its installed
-engine, dependencies and Node runtime. It is descriptive build provenance, not a
-portable signature or a guarantee that imported metadata is trustworthy. Imports
-preserve their original provenance without attaching a fresh-host claim. Existing
-historical `source-development:unverified` records are not rewritten.
-
-Deploy the updated private evaluation controller before a coordinator that
-requires the identity header. Older coordinators ignore the additional response
-header; a new coordinator fails closed against an older controller. Qualify both
-exact artifacts together before production or rollback. Local tests cover this
-contract; the previous `c755434` provider trial predates it.
-
-`NativeAssetLibrary` implements the engine's existing collection, save, read, list,
-import and export contract. Its `project` collection is workspace storage, not
-project membership; `library` is a second user-owned destination. Asset and revision
-ids remain collection-qualified. No extra MCP tool or schema is introduced.
-The actual registry's `kiln_save`, `kiln_assets` restore/list and `kiln_export` are
-exercised through this adapter in the local fixture.
-
-The adapter uses the published SDK's record verifier and material resolver; GLB,
-source, preview, manifest and any required editable material closure are separate
-quota-counted artifacts. Native bundles retain external imports of the three public
-SDK modules, which the eventual image must install at the same qualified version.
-Workers own tenancy, quotas and atomic revision indexing; they do not import the
-native engine or decide whether an asset is structurally valid.
-
-Saving a new revision requires a parent when the asset already exists. The Worker
-checks the parent or absence of prior revisions in the same transaction as pinning
-the inventory, including competing saves. Imports retain immutable revisions and
-unknown provenance, can carry a revision without its ancestors, and are idempotent
-when the existing record is identical. Every input is validated before an import
-writes anything; commits are atomic per revision, not per batch. A later network
-failure can leave earlier imported revisions saved, so retries use the same ids.
-
-Each batch is limited to 100 revisions and 64 MiB including manifests and material
-closures; each manifest is limited to 1 MiB. Lists page the private index in groups
-of 32, and the native result is bounded to 10,000 manifests and 64 MiB. These are
-implementation ceilings, not measured public usage quotas.
-
-Failed saves attempt an independently bounded cleanup of acknowledged staging
-files. The Worker checks saved pins atomically, so a lost commit acknowledgement
-cannot cause cleanup to delete the committed revision. An unacknowledged upload,
-a process crash or failed cleanup can leave unsaved bytes charged until the normal
-seven-day expiry/recovery path removes them. `deleteRevision` is a host UI/account
-operation; it preserves copies in other collections. Whole-account deletion is
-implemented above; its deployed lifecycle remains unqualified.
-
-Embedded material records are retained and verified using the SDK's canonical
-dependency semantics. An injected MaterialLibrary receives the closure on import.
-A textured fixture rebuilds the exported/imported GLB byte-for-byte without its
-original library. This does not qualify software rendering or native isolation on
-Cloudflare.
-
-Source restoration, MCP source reads, reviewed saves and CLI rebuild observations
-preserve a leading UTF-8 BOM. Otherwise restoring an asset could change the exact
-source bytes and its program reference; focused engine tests cover those paths.
-
-## Durable material adapter
-
-`NativeMaterialLibrary` implements the published SDK's immutable material import,
-list and read contract over private tenant storage. The Worker owns the fixed
-`materials/<materialId>/<revisionHash>` index and pins the exact manifest and PNG
-inventory under the existing artifact quotas. The native SDK verifies identity,
-PNG bytes, dimensions and procedural recipe/output hashes. Provenance URLs remain
-metadata and are never fetched.
-
-Imports validate and snapshot the complete batch before any write. The host limits
-each batch to 100 distinct revisions, 64 MiB including manifests and 16 million
-decoded pixels (16 * 1024 * 1024); the SDK's per-record limits also apply. Commits
-are atomic per revision. A later failure can leave earlier revisions saved; retry
-with the same identities. Concurrent identical imports are idempotent and discard
-losing staging files. A lost commit acknowledgement cannot delete pinned bytes.
-Unacknowledged uploads or failed cleanup remain quota-counted until normal expiry.
-
-Lists page 32 records at a time and verify manifest identities without decoding
-all PNGs. Exact reads verify the complete material record. Saved records survive
-the seven-day unsaved expiry. Local tests cover fresh hosts and Durable Object
-eviction, account separation, concurrent imports, corruption, quota exhaustion,
-multi-page listing, caller mutation and partial failures.
-
-The native MCP host injects this library into the engine and asset imports. Its
-fifteen tools include the registry-owned `kiln_material`; edge metadata is generated
-from that same configured registry. A standalone workspace binding resolves each
-call's explicit `materialDependencies` before evaluation. Nested operations inherit
-pins unless `projectId: null` resets the binding; overlapping operations use separate
-async contexts. Revisions and hashes must agree, and the host does not infer a
-project from the `project` collection. Hosted project/review stores are not supplied
-or advertised; explicit project selection reports that limitation.
-
-Each invocation resolves at most sixteen pinned materials within the SDK's payload
-byte/pixel budgets. The existing private evaluator transport additionally limits
-the serialized evaluation request, including source and embedded material bytes,
-to 4 MiB. Large dependency closures can therefore exceed the hosted transport limit
-even when individual saved materials are valid. They fail closed; no dependencies
-are silently dropped or replaced. Private request dispatch permits only the exact
-material index routes and continues to bind the tenant outside the coordinator VM.
-
-The MCP fixture creates, lists and reads a material, renders with explicit pins,
-saves and exports an asset across fresh hosts, and rejects another account before
-evaluation. After deletion of the live material entry, copying the saved asset to
-another collection reinstalls its embedded material closure, preserves GLB bytes
-and supports a fresh render. Installed-image checks also verify the material tool,
-binding schema and preset discovery against the exact public package. These are
-local qualification; deployed Cloudflare material workflows remain unverified.
-
-## Private browser downloads
-
-The native host supplies the published engine's `assetDownloadUrls` hook. Saved
-revision summaries return `/downloads/<ticket>/<filename>` links for their exact
-GLB, source, manifest, preview and material closure when present. `kiln_assets`
-with `action: 'get'` can issue fresh links. No public tool schema is changed.
-
-Links require a current browser session for the owning Kiln account. The gateway
-derives the same private tenant as MCP from the primary-backed account identity;
-the URL never selects a tenant or R2 object. An anonymous visitor sees the branded
-Google/GitHub sign-in form. Migration `0007_browser_login_return.sql` stores a
-strictly validated relative download path in the one-use browser transaction.
-Callbacks use that stored destination, never a callback query parameter. Apply
-all numbered migrations before deploying the gateway. Rollback to the preceding
-gateway can leave the additive column in place.
-
-Each random ticket lasts ten minutes, is stored only as a hash, and permits at
-most 32 transfer attempts across its files, including HEAD and failed reads.
-There are at most 128 unexpired tickets per tenant; issuance and redemption are
-atomic. This fixed metadata ceiling is separate from the artifact-byte quota.
-Expired rows are reclaimed on issuance, maintenance and tenant alarms. Links do
-not extend artifact retention, and deleting the selected revision invalidates
-its links even if another revision pins the same bytes. Ticket limits return 429;
-they do not delete saved work. Browser requests do not start a compute VM.
-
-The gateway rechecks the browser session after storage awaits, and storage
-rechecks ticket expiry and the saved revision before returning bytes. Responses
-use attachment disposition, no-store, no-referrer and nosniff. Foreign Origins
-and cross-origin embedding are denied while ordinary top-level link navigation
-is allowed. Browser credentials never enter the tenant Worker or native host.
-
-Local tests exercise the actual MCP save/reopen output, browser gateway, D1
-sessions, SQLite tenant index and R2 downloads for two accounts. Separate mocked
-provider exchanges verify both sign-in continuations, replay denial and hostile
-redirect rejection. This proves local integration, not live provider sign-in or
-Cloudflare delivery. The coordinator image must be rebuilt for this host change;
-the separately prepared `c755434` trial retains its original bundle and images.
-
-The redirect and request-context boundaries follow the checked
-[OAuth security BCP](https://www.rfc-editor.org/rfc/rfc9700.html#section-4.11)
-and [Fetch Metadata guidance](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Fetch_metadata).
-
-## Operational monitoring
-
-Operational monitoring is described in [OPERATIONS.md](OPERATIONS.md). The gateway
-emits explicit response counters/timing and scheduled deletion/compute health;
-raw request data and user identities are excluded. Preparation includes alert
-candidates, but no deployed ingestion or notification delivery is qualified yet.
-
-## Request abuse protection
-
-Both edge and account rate-limit bindings are required on the gateway. Before
-OAuth, D1 or body processing, requests share bounded route-class counters. After
-authentication, MCP calls and browser downloads share a hash of the permanent
-Kiln account and origin, independent of client, token and network address. Counter
-keys never contain bearer tokens, cookies, IP addresses, source or download URLs.
-Exhaustion returns a private 429 response with `Retry-After: 60`. A missing,
-malformed, failing or stalled binding fails closed with 503.
-
-These bindings provide approximate, per-Cloudflare-location abuse protection.
-They do not replace durable compute admission or storage quotas, and cannot cap
-the hosting bill. Coarse route limits also affect legitimate users sharing a
-location when exhausted. The deployment manifest makes both namespaces and
-thresholds explicit; qualification and public thresholds remain to be reviewed
-and tested on the provider. No rate-limit configuration has been deployed.
-
-Before launch, complete native isolation on the actual Cloudflare provider,
-tenant engine/storage integration, two-user asset/download denial tests, retention,
-admission/cancellation and cost controls, identity-provider setup, live client
-connections, support/privacy pages and exact deployed identity verification.
-
-Sources checked 6 October 2026:
-[Cloudflare OAuth library](https://github.com/cloudflare/workers-oauth-provider),
-[MCP authorization](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization),
-[GitHub OAuth flow](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps).
-
-## Public plugin preparation
-
-`plugin/` contains the source for the hosted OpenAI submission candidate. It is
-separate from `plugins/kiln-engine`, the published local setup plugin. From the
-repository root, using the pinned maintainer Node, package a fresh output directory:
-
-```sh
-node hosting/scripts/package-public-plugin.mjs .cache/public-plugin-draft
-```
-
-The output contains a complete `plugin/` folder, `kiln-engine-draft.zip` and a
-receipt with source/file/archive hashes. Shared authoring references and the
-existing icon are copied during packaging, so do not upload the source folder
-directly. The packager refuses an existing output directory and includes only its
-explicit file list. It never contacts a provider or publishes anything.
-
-The draft has one remote MCP connection, a hosted workflow skill, listing metadata
-and five positive/three negative review cases. Its receipt always says
-`submissionReady: false`: offline packaging cannot establish live OAuth, endpoint
-availability, review-account access, demo evidence or portal acceptance. Keep
-reviewer credentials outside the repository and ZIP. See the
-[directory preflight](../docs/reviews/2026-10-07-directory-preflight.md) for the
-remaining qualification and submission steps.
diff --git a/hosting/assets/README.md b/hosting/assets/README.md
deleted file mode 100644
index d54cc659..00000000
--- a/hosting/assets/README.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# Sign-in branding
-
-`src/google-button.ts` embeds an unmodified Google-provided PNG so sign-in pages
-need no third-party image, font or script request. It is not a Kiln-owned logo.
-Google's brand restrictions continue to apply; the repository's MIT license does
-not grant rights to Google's trademarks.
-
-- Guidance: https://developers.google.com/identity/branding-guidelines
-- Downloaded 6 October 2026: https://developers.google.com/static/identity/images/signin-assets.zip
-- ZIP member: `Android + Web/PNG @2x/Light/Theme=Light, Show text=Yes, Shape=Square, [email protected]`
-- Original: 360 × 80 pixels, 6,007 bytes.
-- SHA-256: `fdd355abc194d6acc0837c9b5e8a3170d6ae07dfeb85a63d3eb4b7fbfc2bb63f`.
-
-The button preserves the image's aspect ratio. Its accessible name matches the
-rendered text. GitHub's adjacent button has the same size and visual weight.
-No Google Identity Services script is necessary for the server-side OIDC flow.
diff --git a/hosting/container/Dockerfile b/hosting/container/Dockerfile
deleted file mode 100644
index 908f405b..00000000
--- a/hosting/container/Dockerfile
+++ /dev/null
@@ -1,15 +0,0 @@
-# Private per-job CPU image. Build only the four-file context in README.md.
-FROM node:22.23.3-trixie-slim@sha256:154ba2f4d6fec323d28e4f4bb86bba4677f1223391a1979cf521304e03a98dfa
-RUN npm install --global [email protected] --ignore-scripts --no-audit --no-fund
-WORKDIR /opt/kiln
-COPY candidate.tgz candidate.sha256 ./
-RUN sha256sum -c candidate.sha256 \
- && npm init -y \
- && npm install ./candidate.tgz --omit=dev --include=optional --ignore-scripts --no-audit --no-fund \
- && dpkg-query -W > os-packages.txt \
- && node --version > node-version.txt
-COPY evaluate.mjs ./
-# User IDs are defense in depth only; Cloudflare's durable_object scheduling
-# grants processes root capabilities. The fresh offline microVM is the boundary.
-USER node
-CMD ["/usr/bin/sleep", "infinity"]
diff --git a/hosting/container/Dockerfile.host b/hosting/container/Dockerfile.host
deleted file mode 100644
index a1a6db51..00000000
--- a/hosting/container/Dockerfile.host
+++ /dev/null
@@ -1,14 +0,0 @@
-# Private coordinator image. Never build with the repository or secrets as context.
-FROM node:22.23.3-trixie-slim@sha256:154ba2f4d6fec323d28e4f4bb86bba4677f1223391a1979cf521304e03a98dfa
-RUN npm install --global [email protected] --ignore-scripts --no-audit --no-fund
-WORKDIR /opt/kiln
-COPY candidate.tgz candidate.sha256 package.json package-lock.json ./
-RUN sha256sum -c candidate.sha256 \
- && npm ci --omit=dev --include=optional --ignore-scripts --no-audit --no-fund \
- && dpkg-query -W > os-packages.txt \
- && node --version > node-version.txt
-COPY native-mcp.mjs native-host.mjs serve.mjs ./
-ENV KILN_RENDER=cpu
-USER node
-EXPOSE 3000
-CMD ["node", "/opt/kiln/serve.mjs"]
diff --git a/hosting/container/Dockerfile.software b/hosting/container/Dockerfile.software
deleted file mode 100644
index 607a874a..00000000
--- a/hosting/container/Dockerfile.software
+++ /dev/null
@@ -1,24 +0,0 @@
-# Private per-job software-rendering candidate. Use the six-file context from README.md.
-FROM node:22.23.3-trixie-slim@sha256:154ba2f4d6fec323d28e4f4bb86bba4677f1223391a1979cf521304e03a98dfa
-# Trixie's Mesa supports the shader features required by the packaged Dawn renderer.
-RUN apt-get update && apt-get install -y --no-install-recommends \
- mesa-vulkan-drivers libvulkan1 ca-certificates \
- && rm -rf /var/lib/apt/lists/*
-RUN npm install --global [email protected] --ignore-scripts --no-audit --no-fund
-WORKDIR /opt/kiln
-COPY candidate.tgz candidate.sha256 ./
-RUN sha256sum -c candidate.sha256 \
- && npm init -y \
- && npm install ./candidate.tgz --omit=dev --include=optional --ignore-scripts --no-audit --no-fund \
- && dpkg-query -W > os-packages.txt \
- && node --version > node-version.txt \
- && set -- /usr/share/vulkan/icd.d/lvp_icd*.json \
- && test "$#" -eq 1 && test -f "$1" \
- && ln -s "$1" /opt/kiln/lvp-icd.json
-COPY evaluate.mjs ./
-COPY native-render.mjs render.mjs ./
-ENV VK_ICD_FILENAMES=/opt/kiln/lvp-icd.json
-ENV KILN_RENDER=cpu
-# The VM, outside deadline and network policy enforce isolation, not this UID.
-USER node
-CMD ["/usr/bin/sleep", "infinity"]
diff --git a/hosting/container/README.md b/hosting/container/README.md
deleted file mode 100644
index ea3b3efa..00000000
--- a/hosting/container/README.md
+++ /dev/null
@@ -1,207 +0,0 @@
-# Private evaluation image
-
-Current qualification: the exact stable software image and per-job controller
-passed the twelve fixed Cloudflare cases in [the resilience record](../probe/RESILIENCE.md).
-The earlier preparation notes below retain their narrower evidence. Production
-dispatch, representative load and costs remain open. The separate MCP coordinator
-image described below has local Docker proof only.
-
-This is the CPU-only image for the explicit Cloudflare per-job adapter. It opens
-no network listener. A private Durable Object starts a fresh VM from an immutable
-digest with internet disabled, executes `evaluate.mjs` with piped input/output,
-and destroys the entire VM before accepting a result. Do not run arbitrary user
-source with this entry on the workstation or in the trusted MCP coordinator.
-
-Build a minimal context containing exactly four files:
-
-- This `Dockerfile` and `evaluate.mjs`.
-- The qualified installed-package archive renamed `candidate.tgz`.
-- `candidate.sha256`, containing its approved SHA-256, two spaces, and
- `candidate.tgz`.
-
-Never use the checkout, an authored workspace, credential directories or all of
-`.cache` as the Docker build context. Build for `linux/amd64`. The build verifies
-the supplied archive and installs dependencies without lifecycle scripts. Retain
-the final image digest, `/opt/kiln/package-lock.json`, `/opt/kiln/os-packages.txt`
-and `/opt/kiln/node-version.txt`; the npm archive alone does not pin transitive
-dependencies or establish the image's identity. The base image digest is shared
-with the existing native preflight. The Linux image build and deterministic
-installed-package fixture passed in [CI run 37479877969](https://github.com/instruktlabs/kiln/actions/runs/37479877969).
-The RC image's runtime manifest subsequently passed the fixed evaluation and
-basic provider-boundary checks in [the qualification record](../probe/QUALIFICATION.md).
-Rendering, adversarial resource limits, recovery and production routing remain
-unqualified.
-
-The production controller now requires both `running === false` and a `null`
-inspection after `destroy()` before releasing output or deleting its watchdog.
-Destruction and inspection share a five-second budget. Unknown or failed readback
-keeps the job unfinished for durable recovery. This follows the documented
-[Container API shutdown contract](https://developers.cloudflare.com/containers/api/durable-object-container/).
-Regression tests first reproduced accepted output after an unconfirmed shutdown,
-then passed with the verification in place, including a stalled inspection and
-recovery after an initially failed readback. All 136 hosted tests, three hosted
-typechecks, five bundle checks and root typecheck/lint passed locally. This
-controller passed exact-source Linux/Windows hosted checks in
-[run 37525915541](https://github.com/instruktlabs/kiln/actions/runs/37525915541).
-Live failure-path qualification remains open.
-
-The entry's byte limits and engine schema validation are defensive transport
-checks. A JavaScript timer, Linux user ID and the engine's local VM implementation
-are not security boundaries. Cloudflare must enforce the no-network policy and
-the outside controller must enforce admission, deadlines and destruction. The VM
-must contain no provider credentials, user account records, other tenants' files,
-R2 mounts, reusable source or snapshots. Treat every byte returned by it as
-untrusted, including QA claims, filenames and diagnostics.
-
-Before production routing, qualify the exact deployed image and Worker pair:
-fixed native fixtures and CPU images, blocked internet/metadata/localhost access,
-cross-job filesystem isolation, descendants and infinite-loop deadlines, output
-floods, cancellation during startup and execution, memory exhaustion, controller
-restart/alarm recovery, and confirmed container destruction. Run only fixed
-adversarial fixtures in this private probe, with bounded concurrency, compute,
-cost and teardown. Record cold starts and billed resources separately from engine
-compute time. The old Bubblewrap adapter remains fail-closed and has no automatic
-fallback to this entry.
-
-## Software-rendering candidate
-
-`Dockerfile.software` extends the four-file evaluator context with the built
-`native-render.mjs` and `render.mjs`, for exactly six files. It adds Mesa's software
-Vulkan implementation. Copy it into the context as `Dockerfile`.
-Build with `--platform linux/amd64 --provenance=false` to retain the directly
-addressable runtime manifest. The final immutable image digest, rather than the
-Dockerfile alone, identifies installed OS and npm dependencies. No probe script,
-credential, network listener or storage mount is included in the image.
-
-The exact main `1.0.0` archive (`6ed3d6b9...1508`) was installed locally in image
-`sha256:84a0fa62bcffa010b9ac1c5f2f0e2cf9045a9cdb6407f621e8049e6a37f9de99`.
-With networking disabled, all capabilities dropped, no privilege escalation,
-two CPUs and a 4 GiB memory limit, the real entry produced the same 1,912-byte
-GLB twice and its CPU preview passed at 128 pixels. The packaged renderer also
-produced six textured views across all three backdrops using llvmpipe/Mesa
-25.0.7 and Vulkan; each view retained red and green texture evidence. Temporary
-test containers were removed. These are local functionality checks, not
-Cloudflare isolation, throughput or cost measurements.
-
-The image lock SHA-256 is
-`fdcb5cd754cdb78de52eb530efb9a993a30c8742e83c939103edc6112fd77ba1`.
-The diagnostic worktree retains its inventories, exact image, CPU GLB/PNG and six
-software images under `.cache/stable-software-image/`. CI now builds both image
-variants using the explicitly recorded public package and tests the installed
-entry; the software variant additionally runs the packaged renderer fixture.
-While that public record still names the RC, CI does not qualify the stable
-archive by implication. A prepared, reviewed provider trial is still required
-before uploading or running this new stable image on Cloudflare.
-
-Both CI image variants passed at source `b34d56f` in
-[run 37526078285](https://github.com/instruktlabs/kiln/actions/runs/37526078285).
-That run uses the public RC archive and therefore complements, rather than
-replaces, the exact-stable local receipt above. The stable image's retained npm
-lock also returned zero known findings in an `npm audit --omit=dev` on 6 October.
-No cloud resource was created for this image preparation.
-
-## One-shot software render entry
-
-The current software image includes `/opt/kiln/render.mjs`, a fixed one-shot
-producer selected only by `KilnRenderJob`. The private coordinator sends GLB bytes
-and view options through the versioned renderer port. The entry validates the
-request and self-contained GLB before loading graphics, explicitly selects the
-pinned Mesa ICD, emits bounded JSON and exits. It opens no listener and receives
-no source program, tenant information, storage binding or credentials.
-
-After building the hosting bundles, put `.cache/hosted-worker/native-render.mjs`
-and `hosting/container/render.mjs` into the otherwise unchanged minimal software
-context. Verify the built file against `native-render-build.json`. Build for
-Linux AMD64 without provenance, then run:
-
-```sh
-node hosting/scripts/smoke-native-render.mjs kiln-software-entry:local-v1
-```
-
-The script creates and removes one uniquely named offline local container with
-two CPUs, 4 GiB memory, 128 PIDs, dropped capabilities and no privilege escalation.
-The fixed trusted fixture is passed over stdin, without a workspace mount. It
-exercises the actual renderer entry through the installed private port and decodes
-eight 128px PNGs: six views across three backdrops, a beauty image and an explicit
-camera view. Each retains red/green material evidence. Request identity, exact
-camera metadata and malformed-input rejection are checked. The entry succeeds
-without inheriting the image's Vulkan environment. CI runs the same check.
-
-Local final image manifest
-`sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24`
-passes this procedure with the exact published stable archive. Its dependency
-lock remains `fdcb5cd754cdb78de52eb530efb9a993a30c8742e83c939103edc6112fd77ba1`.
-Receipts, PNGs, inventories and the six-file context receipt are retained under
-`.cache/software-render-entry/final-qualification/` and its parent directory.
-The test container's removal was independently read back. No cloud upload or
-execution occurred. The newly integrated coordinator/render job path still needs
-provider qualification; the earlier twelve-case trial used the historical image.
-
-## Private MCP coordinator image
-
-`Dockerfile.host` serves the installed package's actual MCP factory through the
-private Node adapter. Unlike the evaluator image, it has a private port 3000
-listener. Its explicit remote evaluator profile sends source only to the outside
-controller's fixed evaluation endpoint. It contains no identity-provider secrets,
-tenant identifier, storage mount or public route. `KILN_PUBLIC_ORIGIN` is its only
-application setting and must be an exact HTTPS origin.
-
-From the checkout root, using the pinned Node/npm tools:
-
-```sh
-npm run build --prefix hosting
-node hosting/scripts/prepare-native-host.mjs /path/to/qualified-kiln-1.0.0.tgz
-cd .cache/native-host-image/context
-npm install --package-lock-only --ignore-scripts --no-fund
-cd ../../..
-docker build --platform linux/amd64 --provenance=false --tag kiln-native-host:local .cache/native-host-image/context
-node hosting/scripts/smoke-native-host.mjs kiln-native-host:local
-```
-
-The preparer requires an empty directory inside this checkout's `.cache`, verifies
-the archive against `.github/published-candidate.json` and copies the checked
-runtime bundles, entrypoint and Dockerfile. Its seven-file context becomes eight
-files after lock generation. Never expand the build context to include the repo,
-credentials or other caches. Retain the generated lock and inventories: separate
-builds can resolve different transitive dependencies and have different image
-digests even when the package archive is identical.
-
-The qualification script creates one disposable local container with networking
-disabled, a read-only filesystem, non-root user, dropped capabilities and bounded
-memory/CPU. It checks readiness, modern tool discovery, legacy initialization,
-foreign-host/credential rejection and failure without private services. No host
-port is published. The script removes its uniquely named container and saves
-identities, inventories and the result under `.cache/native-host-image/qualification`.
-CI runs the same procedure without registry publication or Cloudflare access.
-
-Two additional installed-package checks exercise the private evaluation adapter
-with a fixed trusted source and synthetic controller headers: the accepted result
-retains its own image identity, and an otherwise valid response without identity
-fails closed. These are protocol checks inside the offline coordinator fixture;
-they do not prove provider execution or isolation. The current private controller
-must supply the verified evaluator digest before the newer coordinator can run.
-
-Local image `sha256:5402d67069e8b5c9d355e4f49b9ae92d353171b381d27496f85f5794adf95d75`
-passed all six checks with the exact published 1.0.0 archive and fourteen registry
-tools. Its retained dependency lock SHA-256 is
-`f635b9ba48046e4fdb265eb980df55cf1303c4bc0fd109db477ef870ef0b273f`.
-Both the hosting lock and generated image lock reported zero known npm audit
-findings. This image has not been uploaded or qualified on Cloudflare. Storage,
-child evaluation/render dispatch and global admission are now implemented and
-locally tested; the combined deployed path remains an end-to-end qualification
-requirement. The historical coordinator image above predates render-port injection
-and must not be used as the integrated launch candidate.
-
-The render-enabled coordinator was rebuilt locally as manifest
-`sha256:029c4fba6f0521a5a18c9dde364d07b5ffc076fe4d988358868950de40134b66`.
-Its exact stable archive, unchanged dependency lock and all six coordinator checks
-pass. The receipt is `.cache/native-host-render/qualification/receipt.json`.
-It has not been uploaded to Cloudflare.
-
-The browser-download host change has a separate locally qualified coordinator:
-`sha256:2f85a87cb48e360e9de3994d898413695a87c11b3d9f39f466fbf9d88c090d34`.
-Its receipt is `.cache/native-host-download/qualification/receipt.json`; the
-published archive and dependency lock are unchanged and all six offline checks
-pass. The uniquely named test container's absence was independently verified.
-This does not replace the immutable image in the pending `c755434` Cloudflare
-trial, and neither image has been qualified for public launch.
diff --git a/hosting/container/evaluate.mjs b/hosting/container/evaluate.mjs
deleted file mode 100644
index 0a5bbc24..00000000
--- a/hosting/container/evaluate.mjs
+++ /dev/null
@@ -1,33 +0,0 @@
-// Private one-shot entry for an externally isolated VM, never a public server.
-// The outside Durable Object owns admission, network policy and the hard deadline.
-// This process has no provider credentials, tenant storage or reusable state.
-const MAX_INPUT = 4 * 1024 * 1024;
-const MAX_OUTPUT = 8 * 1024 * 1024;
-
-try {
- const input = Buffer.alloc(MAX_INPUT);
- let size = 0;
- for await (const chunk of process.stdin) {
- if (size + chunk.byteLength > MAX_INPUT) throw new Error('Input limit');
- input.set(chunk, size);
- size += chunk.byteLength;
- }
- const request = new TextDecoder('utf-8', { fatal: true }).decode(input.subarray(0, size));
- const { evaluateEvaluatorRequestV2 } = await import('@instruktlabs/kiln/evaluator');
- const response = await evaluateEvaluatorRequestV2(
- request,
- {},
- {
- maxResponseBytes: MAX_OUTPUT,
- deadlineMs: 60_000,
- },
- );
- if (Buffer.byteLength(response) > MAX_OUTPUT) throw new Error('Output limit');
- await new Promise((resolve, reject) => {
- process.stdout.write(response, (error) => (error ? reject(error) : resolve()));
- });
-} catch {
- // Never echo the request, filesystem paths, dependency diagnostics or a stack.
- process.stderr.write('Kiln evaluator input or execution failed.\n');
- process.exitCode = 1;
-}
diff --git a/hosting/container/render.mjs b/hosting/container/render.mjs
deleted file mode 100644
index d7697eb3..00000000
--- a/hosting/container/render.mjs
+++ /dev/null
@@ -1,59 +0,0 @@
-// One bounded request in a disposable software-rendering VM. No source execution,
-// storage, provider credentials or listening server is exposed by this entry.
-try {
- const { decodeRenderRequest, encodeRenderResult, RENDER_LIMITS } = await import(
- './native-render.mjs'
- );
- const bytes = Buffer.alloc(RENDER_LIMITS.requestBytes);
- let length = 0;
- for await (const chunk of process.stdin) {
- if (length + chunk.byteLength > bytes.byteLength) throw new Error('Input limit');
- bytes.set(chunk, length);
- length += chunk.byteLength;
- }
- const input = decodeRenderRequest(bytes.subarray(0, length));
- const engine = new URL(import.meta.resolve('@instruktlabs/kiln'));
- const service = (name) => new URL(`../render-service/src/${name}.mjs`, engine).href;
- const { validateSelfContainedGlb } = await import(service('glb-input'));
- const { validateRenderMode } = await import(service('contract'));
- const { glb, ...options } = input.request;
- validateSelfContainedGlb(glb, { maxGlbBytes: RENDER_LIMITS.glbBytes });
- validateRenderMode({
- views: options.viewDirs,
- size: options.size,
- beauty_size: options.beautySize,
- cameras: options.cameras,
- width: options.width,
- height: options.height,
- lighting_preset_id: options.lightingPresetId,
- backdrop: options.backdrop,
- });
- // Cloudflare exec does not inherit image environment variables. Select the
- // reviewed software ICD here, never from request fields or ambient GPU choice.
- process.env.VK_ICD_FILENAMES = '/opt/kiln/lvp-icd.json';
- await import(service('register-hooks'));
- const { initRenderer, renderGlb } = await import(service('renderer'));
- const gpu = await import(service('gpu'));
- await initRenderer({ allowSoftware: true });
- const device = await gpu.acquireGpu();
- if (device.software !== true || device.backend !== 'vulkan')
- throw new Error('Unexpected renderer');
- const result = await renderGlb(glb, options);
- const output = encodeRenderResult(input, {
- ...result,
- rendererId: device.rendererId,
- backend: device.backend,
- software: true,
- });
- gpu.markGpuShutdown();
- device.device.destroy();
- await new Promise((resolve, reject) =>
- process.stdout.write(output, (error) => (error ? reject(error) : resolve())),
- );
- process.exit(0);
-} catch {
- await new Promise((resolve) =>
- process.stderr.write('Kiln software render input or execution failed.\n', resolve),
- );
- process.exit(1);
-}
diff --git a/hosting/container/serve.mjs b/hosting/container/serve.mjs
deleted file mode 100644
index 234605f9..00000000
--- a/hosting/container/serve.mjs
+++ /dev/null
@@ -1,29 +0,0 @@
-// Private, tenant-bound coordinator. Authored source executes only through the
-// fixed remote evaluator; the outside controller owns identity and VM lifetime.
-try {
- const origin = process.env.KILN_PUBLIC_ORIGIN;
- const parsed = new URL(origin);
- if (parsed.protocol !== 'https:' || parsed.origin !== origin) throw new Error('Invalid origin');
- const { createNativeMcpHandler, loadContainerMcpRuntime } = await import('./native-mcp.mjs');
- const { createNativeHttpServer } = await import('./native-host.mjs');
- const handler = createNativeMcpHandler(await loadContainerMcpRuntime(), {
- publicOrigin: origin,
- maxConcurrent: 1,
- });
- const server = createNativeHttpServer(handler);
- await new Promise((resolve, reject) => {
- server.once('error', reject);
- server.listen(3000, '0.0.0.0', resolve);
- });
- const stop = () => {
- void handler.close();
- server.close(() => process.exit(0));
- server.closeAllConnections();
- setTimeout(() => process.exit(1), 5000).unref();
- };
- process.once('SIGTERM', stop);
- process.once('SIGINT', stop);
-} catch {
- process.stderr.write('Kiln native host startup failed.\n');
- process.exitCode = 1;
-}
diff --git a/hosting/deployment.example.json b/hosting/deployment.example.json
deleted file mode 100644
index f588070b..00000000
--- a/hosting/deployment.example.json
+++ /dev/null
@@ -1,32 +0,0 @@
-{
- "account": "REPLACE_WITH_VERIFIED_ACCOUNT_ID",
- "prefix": "kiln-qualification-v1",
- "origin": "https://kiln.instruktlabs.com",
- "database": {
- "id": "REPLACE_WITH_VERIFIED_D1_ID",
- "name": "kiln-qualification-v1-accounts"
- },
- "oauthKv": "REPLACE_WITH_VERIFIED_KV_ID",
- "bucket": "kiln-qualification-v1-artifacts",
- "requestLimits": {
- "edge": { "namespace": "REPLACE_WITH_UNIQUE_POSITIVE_INTEGER", "perMinute": 600 },
- "account": { "namespace": "REPLACE_WITH_DIFFERENT_POSITIVE_INTEGER", "perMinute": 120 }
- },
- "images": {
- "coordinator": "REPLACE_WITH_VERIFIED_ACCOUNT_REGISTRY_DIGEST",
- "software": "REPLACE_WITH_VERIFIED_ACCOUNT_REGISTRY_DIGEST"
- },
- "compute": {
- "maxConcurrent": 1,
- "tenantPerMinute": 9,
- "tenantPerDay": 9,
- "globalPerDay": 9,
- "globalPerMonth": 9,
- "deadlineMs": 120000
- },
- "storage": {
- "maxBytes": 67108864,
- "maxObjects": 256,
- "maxGroups": 64
- }
-}
diff --git a/hosting/migrations/0001_accounts.sql b/hosting/migrations/0001_accounts.sql
deleted file mode 100644
index f4398c8c..00000000
--- a/hosting/migrations/0001_accounts.sql
+++ /dev/null
@@ -1,16 +0,0 @@
-CREATE TABLE kiln_accounts (
- id TEXT PRIMARY KEY NOT NULL,
- state TEXT NOT NULL DEFAULT 'active' CHECK (state IN ('active', 'disabled', 'deleting')),
- authorization_epoch INTEGER NOT NULL DEFAULT 1 CHECK (authorization_epoch > 0),
- created_at INTEGER NOT NULL
-);
-
-CREATE TABLE kiln_identities (
- issuer TEXT NOT NULL,
- subject TEXT NOT NULL,
- account_id TEXT NOT NULL REFERENCES kiln_accounts(id),
- created_at INTEGER NOT NULL,
- PRIMARY KEY (issuer, subject)
-);
-
-CREATE INDEX kiln_identities_by_account ON kiln_identities(account_id);
diff --git a/hosting/migrations/0002_login_intents.sql b/hosting/migrations/0002_login_intents.sql
deleted file mode 100644
index b496a5fb..00000000
--- a/hosting/migrations/0002_login_intents.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-CREATE TABLE kiln_consent_claims (
- handle_hash TEXT PRIMARY KEY,
- expires_at INTEGER NOT NULL
-);
-CREATE INDEX kiln_consent_expiry ON kiln_consent_claims(expires_at);
-
-CREATE TABLE kiln_login_intents (
- id TEXT PRIMARY KEY,
- state_hash TEXT NOT NULL UNIQUE,
- provider TEXT NOT NULL CHECK(provider IN ('google', 'github')),
- purpose TEXT NOT NULL CHECK(purpose = 'sign-in'),
- expires_at INTEGER NOT NULL
-);
-CREATE INDEX kiln_login_expiry ON kiln_login_intents(expires_at);
diff --git a/hosting/migrations/0003_browser_sessions.sql b/hosting/migrations/0003_browser_sessions.sql
deleted file mode 100644
index e5d296c3..00000000
--- a/hosting/migrations/0003_browser_sessions.sql
+++ /dev/null
@@ -1,12 +0,0 @@
-CREATE TABLE kiln_browser_sessions (
- token_hash TEXT PRIMARY KEY NOT NULL,
- account_id TEXT NOT NULL REFERENCES kiln_accounts(id),
- account_epoch INTEGER NOT NULL CHECK (account_epoch > 0),
- authenticated_at INTEGER NOT NULL,
- expires_at INTEGER NOT NULL,
- idle_expires_at INTEGER NOT NULL DEFAULT 0,
- csrf TEXT NOT NULL
-);
-
-CREATE INDEX kiln_browser_sessions_by_account ON kiln_browser_sessions(account_id, authenticated_at);
-CREATE INDEX kiln_browser_sessions_by_expiry ON kiln_browser_sessions(expires_at);
diff --git a/hosting/migrations/0004_browser_logins.sql b/hosting/migrations/0004_browser_logins.sql
deleted file mode 100644
index 44e00f18..00000000
--- a/hosting/migrations/0004_browser_logins.sql
+++ /dev/null
@@ -1,9 +0,0 @@
-CREATE TABLE kiln_browser_logins (
- state_hash TEXT PRIMARY KEY NOT NULL,
- binding_hash TEXT NOT NULL UNIQUE,
- provider TEXT NOT NULL CHECK(provider IN ('google', 'github')),
- verifier TEXT NOT NULL,
- nonce TEXT NOT NULL,
- expires_at INTEGER NOT NULL
-);
-CREATE INDEX kiln_browser_logins_by_expiry ON kiln_browser_logins(expires_at);
diff --git a/hosting/migrations/0005_connections.sql b/hosting/migrations/0005_connections.sql
deleted file mode 100644
index 6b7ed4c3..00000000
--- a/hosting/migrations/0005_connections.sql
+++ /dev/null
@@ -1,17 +0,0 @@
-CREATE TABLE kiln_connections (
- id TEXT PRIMARY KEY NOT NULL,
- account_id TEXT NOT NULL REFERENCES kiln_accounts(id),
- account_epoch INTEGER NOT NULL CHECK(account_epoch > 0),
- client_id TEXT NOT NULL,
- client_name TEXT NOT NULL,
- client_domain TEXT,
- redirect_uri TEXT NOT NULL,
- scope TEXT NOT NULL,
- state TEXT NOT NULL DEFAULT 'pending' CHECK(state IN ('pending','active','revoked')),
- grant_id TEXT,
- created_at INTEGER NOT NULL,
- expires_at INTEGER NOT NULL,
- UNIQUE(account_id, grant_id)
-);
-CREATE INDEX kiln_connections_by_account ON kiln_connections(account_id, created_at);
-CREATE INDEX kiln_connections_by_expiry ON kiln_connections(expires_at);
diff --git a/hosting/migrations/0006_account_actions.sql b/hosting/migrations/0006_account_actions.sql
deleted file mode 100644
index b2593ace..00000000
--- a/hosting/migrations/0006_account_actions.sql
+++ /dev/null
@@ -1,15 +0,0 @@
-CREATE TABLE kiln_account_actions (
- state_hash TEXT PRIMARY KEY NOT NULL,
- binding_hash TEXT NOT NULL UNIQUE,
- session_hash TEXT NOT NULL REFERENCES kiln_browser_sessions(token_hash) ON DELETE CASCADE,
- account_id TEXT NOT NULL REFERENCES kiln_accounts(id),
- account_epoch INTEGER NOT NULL,
- provider TEXT NOT NULL CHECK(provider IN ('google','github')),
- purpose TEXT NOT NULL CHECK(purpose='disconnect'),
- target TEXT NOT NULL,
- verifier TEXT NOT NULL,
- nonce TEXT NOT NULL,
- expires_at INTEGER NOT NULL
-);
-CREATE INDEX kiln_account_actions_by_account ON kiln_account_actions(account_id);
-CREATE INDEX kiln_account_actions_by_expiry ON kiln_account_actions(expires_at);
diff --git a/hosting/migrations/0007_browser_login_return.sql b/hosting/migrations/0007_browser_login_return.sql
deleted file mode 100644
index 707c8cb1..00000000
--- a/hosting/migrations/0007_browser_login_return.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE kiln_browser_logins ADD COLUMN return_to TEXT NOT NULL DEFAULT '/account';
diff --git a/hosting/migrations/0008_identity_actions.sql b/hosting/migrations/0008_identity_actions.sql
deleted file mode 100644
index f59705ce..00000000
--- a/hosting/migrations/0008_identity_actions.sql
+++ /dev/null
@@ -1,32 +0,0 @@
--- One identity from each supported provider per Kiln account. Existing sign-in
--- registration creates one identity and never merges accounts.
-CREATE UNIQUE INDEX kiln_identity_provider_by_account ON kiln_identities(account_id, issuer);
-
-CREATE TABLE kiln_identity_actions (
- state_hash TEXT PRIMARY KEY NOT NULL,
- binding_hash TEXT NOT NULL UNIQUE,
- session_hash TEXT NOT NULL REFERENCES kiln_browser_sessions(token_hash) ON DELETE CASCADE,
- account_id TEXT NOT NULL REFERENCES kiln_accounts(id),
- account_epoch INTEGER NOT NULL,
- purpose TEXT NOT NULL CHECK(purpose IN ('link','unlink')),
- phase TEXT NOT NULL CHECK(phase IN ('confirm','target')),
- provider TEXT NOT NULL CHECK(provider IN ('google','github')),
- target TEXT NOT NULL CHECK(target IN ('google','github')),
- confirmer TEXT NOT NULL CHECK(confirmer IN ('google','github')),
- confirmed_subject TEXT,
- confirmed_at INTEGER,
- verifier TEXT NOT NULL,
- nonce TEXT NOT NULL,
- expires_at INTEGER NOT NULL
-);
-CREATE INDEX kiln_identity_actions_by_account ON kiln_identity_actions(account_id);
-CREATE INDEX kiln_identity_actions_by_expiry ON kiln_identity_actions(expires_at);
-
-CREATE TABLE kiln_account_events (
- id TEXT PRIMARY KEY NOT NULL,
- account_id TEXT NOT NULL REFERENCES kiln_accounts(id),
- kind TEXT NOT NULL CHECK(kind IN ('link','unlink')),
- provider TEXT NOT NULL CHECK(provider IN ('google','github')),
- created_at INTEGER NOT NULL
-);
-CREATE INDEX kiln_account_events_by_account ON kiln_account_events(account_id, created_at);
diff --git a/hosting/migrations/0009_account_deletion.sql b/hosting/migrations/0009_account_deletion.sql
deleted file mode 100644
index 609c2f34..00000000
--- a/hosting/migrations/0009_account_deletion.sql
+++ /dev/null
@@ -1,31 +0,0 @@
-CREATE TABLE kiln_deletion_actions (
- state_hash TEXT PRIMARY KEY NOT NULL,
- binding_hash TEXT NOT NULL UNIQUE,
- session_hash TEXT NOT NULL REFERENCES kiln_browser_sessions(token_hash) ON DELETE CASCADE,
- account_id TEXT NOT NULL REFERENCES kiln_accounts(id),
- account_epoch INTEGER NOT NULL,
- provider TEXT NOT NULL CHECK(provider IN ('google','github')),
- verifier TEXT NOT NULL,
- nonce TEXT NOT NULL,
- expires_at INTEGER NOT NULL
-);
-CREATE INDEX kiln_deletion_actions_by_account ON kiln_deletion_actions(account_id);
-CREATE INDEX kiln_deletion_actions_by_expiry ON kiln_deletion_actions(expires_at);
-
--- The row and primary access revocation are created in one transaction. Completed
--- receipts retain no account/identity mapping and are pruned after seven days.
-CREATE TABLE kiln_deletions (
- id TEXT PRIMARY KEY NOT NULL,
- account_id TEXT UNIQUE REFERENCES kiln_accounts(id) ON DELETE SET NULL,
- receipt_hash TEXT NOT NULL UNIQUE,
- phase TEXT NOT NULL CHECK(phase IN ('compute','storage','grants','identity','complete')),
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL,
- retry_at INTEGER NOT NULL,
- lease_token TEXT,
- lease_until INTEGER NOT NULL DEFAULT 0,
- attempts INTEGER NOT NULL DEFAULT 0,
- completed_at INTEGER
-);
-CREATE INDEX kiln_deletions_by_retry ON kiln_deletions(phase,retry_at,lease_until);
-CREATE INDEX kiln_deletions_by_expiry ON kiln_deletions(completed_at);
diff --git a/hosting/package-lock.json b/hosting/package-lock.json
deleted file mode 100644
index 038a5ca6..00000000
--- a/hosting/package-lock.json
+++ /dev/null
@@ -1,1982 +0,0 @@
-{
- "name": "@instruktlabs/kiln-hosted",
- "version": "1.0.0-rc.1",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "name": "@instruktlabs/kiln-hosted",
- "version": "1.0.0-rc.1",
- "dependencies": {
- "@cloudflare/workers-oauth-provider": "1.2.1",
- "@modelcontextprotocol/node": "2.1.1",
- "@modelcontextprotocol/server": "2.3.0",
- "oauth4webapi": "3.8.8"
- },
- "devDependencies": {
- "@cloudflare/config": "0.23.0",
- "@cloudflare/workers-types": "5.20261006.1",
- "esbuild": "0.28.1",
- "miniflare": "5.20261001.0-alpha",
- "typescript": "7.0.2"
- }
- },
- "node_modules/@cloudflare/config": {
- "version": "0.23.0",
- "resolved": "https://registry.npmjs.org/@cloudflare/config/-/config-0.23.0.tgz",
- "integrity": "sha512-oE0S7X54esZmJHr9hhCoqODR+yTxxkSYWCLtRiItQdPs0gQuqYw9a13zChhK+8DmdCUJIFBsMAR6t+mfu8g+9w==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "zod": "4.4.3"
- }
- },
- "node_modules/@cloudflare/config/node_modules/zod": {
- "version": "4.4.3",
- "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
- "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
- "dev": true,
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/colinhacks"
- }
- },
- "node_modules/@cloudflare/workerd-darwin-64": {
- "version": "1.20261001.1",
- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261001.1.tgz",
- "integrity": "sha512-4cgSgDf28JSw/P5Dj5GCS59hzVqS5XnmGAWNkvYHLI6ODU9idGaMMNEuhJXDkEG/lsABmlVlnCgsdh2VbKWepw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=16"
- }
- },
- "node_modules/@cloudflare/workerd-darwin-arm64": {
- "version": "1.20261001.1",
- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261001.1.tgz",
- "integrity": "sha512-8ulAWruEVouNmEIsQsy9WSSCS9zkLu93W2MTwp5esiFyoPp05BNSVFIFsYSPi1pkFmBBd7fsnwMpbLkaJLaVPQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=16"
- }
- },
- "node_modules/@cloudflare/workerd-linux-64": {
- "version": "1.20261001.1",
- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261001.1.tgz",
- "integrity": "sha512-kZbTZJGrhsMOdqZ2BIybjaBRLZjYsRLWj7mcNw/6Y3hodOhp5MrNzcz4iWGwNVWwyIV+7Pl+/LX5VcgnRqdHOg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16"
- }
- },
- "node_modules/@cloudflare/workerd-linux-arm64": {
- "version": "1.20261001.1",
- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261001.1.tgz",
- "integrity": "sha512-oOk3Zj6k/8oP0FJgZBWDn7+BqbsqIMEMaV95pulHPVbwVu4wYoLfQq2hp0vkbCNsCFLqZb7cqixXdrwD54ZIow==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16"
- }
- },
- "node_modules/@cloudflare/workerd-windows-64": {
- "version": "1.20261001.1",
- "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261001.1.tgz",
- "integrity": "sha512-uRxm5W4VyBkoSaoP1BfOuH0873tE+vxsknF4sab6/5YIRvIAufChq3QDp+zlAn67PuGPGcn7W8QraA0t4ucmOQ==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=16"
- }
- },
- "node_modules/@cloudflare/workers-oauth-provider": {
- "version": "1.2.1",
- "resolved": "https://registry.npmjs.org/@cloudflare/workers-oauth-provider/-/workers-oauth-provider-1.2.1.tgz",
- "integrity": "sha512-5bw7JJI9Nd4ArHfNnvTF8H2OpSbA2GbqTmX80ly47h7dR+atgjFsn9Wfz+biKlAKClTEUYE0KAr791RkED41VA==",
- "license": "MIT"
- },
- "node_modules/@cloudflare/workers-types": {
- "version": "5.20261006.1",
- "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-5.20261006.1.tgz",
- "integrity": "sha512-5OclwQK1d8f5LCPvOlyldC3ryKLUa4nLXegcgPZeUxAPudczQ9xujJDdpS2Tenp7JqbBLW3OgGciHJmuc7QShg==",
- "dev": true,
- "license": "MIT OR Apache-2.0"
- },
- "node_modules/@cspotcode/source-map-support": {
- "version": "0.8.1",
- "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
- "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@jridgewell/trace-mapping": "0.3.9"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@emnapi/runtime": {
- "version": "1.11.3",
- "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
- "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@esbuild/aix-ppc64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
- "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "aix"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/android-arm": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
- "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/android-arm64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
- "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/android-x64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
- "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/darwin-arm64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
- "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/darwin-x64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
- "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/freebsd-arm64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
- "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/freebsd-x64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
- "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-arm": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
- "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-arm64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
- "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-ia32": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
- "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
- "cpu": [
- "ia32"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-loong64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
- "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
- "cpu": [
- "loong64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-mips64el": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
- "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
- "cpu": [
- "mips64el"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-ppc64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
- "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-riscv64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
- "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
- "cpu": [
- "riscv64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-s390x": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
- "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
- "cpu": [
- "s390x"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-x64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
- "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/netbsd-arm64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
- "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/netbsd-x64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
- "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/openbsd-arm64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
- "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/openbsd-x64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
- "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/openharmony-arm64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
- "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "openharmony"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/sunos-x64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
- "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "sunos"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/win32-arm64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
- "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/win32-ia32": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
- "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
- "cpu": [
- "ia32"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/win32-x64": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
- "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@hono/node-server": {
- "version": "1.19.17",
- "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.17.tgz",
- "integrity": "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==",
- "license": "MIT",
- "engines": {
- "node": ">=18.14.1"
- },
- "peerDependencies": {
- "hono": "^4"
- }
- },
- "node_modules/@img/colour": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
- "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@img/sharp-darwin-arm64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",
- "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-darwin-arm64": "1.3.4"
- }
- },
- "node_modules/@img/sharp-darwin-x64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",
- "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-darwin-x64": "1.3.4"
- }
- },
- "node_modules/@img/sharp-freebsd-wasm32": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",
- "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "dependencies": {
- "@img/sharp-wasm32": "0.35.5"
- },
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-darwin-arm64": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",
- "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "darwin"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-darwin-x64": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",
- "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "darwin"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-linux-arm": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",
- "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "linux"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-linux-arm64": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",
- "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "linux"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-linux-ppc64": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",
- "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "linux"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-linux-riscv64": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",
- "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",
- "cpu": [
- "riscv64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "linux"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-linux-s390x": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",
- "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",
- "cpu": [
- "s390x"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "linux"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-linux-x64": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",
- "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "linux"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",
- "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "libc": [
- "musl"
- ],
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "linux"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-libvips-linuxmusl-x64": {
- "version": "1.3.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",
- "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "libc": [
- "musl"
- ],
- "license": "LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "linux"
- ],
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-linux-arm": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",
- "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-linux-arm": "1.3.4"
- }
- },
- "node_modules/@img/sharp-linux-arm64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",
- "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-linux-arm64": "1.3.4"
- }
- },
- "node_modules/@img/sharp-linux-ppc64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",
- "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-linux-ppc64": "1.3.4"
- }
- },
- "node_modules/@img/sharp-linux-riscv64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",
- "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",
- "cpu": [
- "riscv64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-linux-riscv64": "1.3.4"
- }
- },
- "node_modules/@img/sharp-linux-s390x": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",
- "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",
- "cpu": [
- "s390x"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-linux-s390x": "1.3.4"
- }
- },
- "node_modules/@img/sharp-linux-x64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",
- "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "libc": [
- "glibc"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-linux-x64": "1.3.4"
- }
- },
- "node_modules/@img/sharp-linuxmusl-arm64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",
- "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "libc": [
- "musl"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-linuxmusl-arm64": "1.3.4"
- }
- },
- "node_modules/@img/sharp-linuxmusl-x64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",
- "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "libc": [
- "musl"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-libvips-linuxmusl-x64": "1.3.4"
- }
- },
- "node_modules/@img/sharp-wasm32": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",
- "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",
- "dev": true,
- "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
- "optional": true,
- "dependencies": {
- "@emnapi/runtime": "^1.11.3"
- },
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-webcontainers-wasm32": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
- "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",
- "cpu": [
- "wasm32"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "dependencies": {
- "@img/sharp-wasm32": "0.35.5"
- },
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-win32-arm64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",
- "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0 AND LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-win32-ia32": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",
- "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",
- "cpu": [
- "ia32"
- ],
- "dev": true,
- "license": "Apache-2.0 AND LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": "^20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@img/sharp-win32-x64": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",
- "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0 AND LGPL-3.0-or-later",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- }
- },
- "node_modules/@jridgewell/resolve-uri": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
- "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=6.0.0"
- }
- },
- "node_modules/@jridgewell/sourcemap-codec": {
- "version": "1.6.0",
- "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
- "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/@jridgewell/trace-mapping": {
- "version": "0.3.9",
- "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
- "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@jridgewell/resolve-uri": "^3.0.3",
- "@jridgewell/sourcemap-codec": "^1.4.10"
- }
- },
- "node_modules/@modelcontextprotocol/core": {
- "version": "2.3.0",
- "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.0.tgz",
- "integrity": "sha512-09BHFaNVBe5pB2AhzCfLj0cqmsKLERvZQ4FblzP90UMGLaXVqdZPByFjURwsUYCmxonUW2yAwgTTvle+8O2/8w==",
- "license": "Apache-2.0",
- "dependencies": {
- "zod": "^4.2.0"
- },
- "engines": {
- "node": ">=20"
- }
- },
- "node_modules/@modelcontextprotocol/node": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.1.1.tgz",
- "integrity": "sha512-EY92OAXN2xYL7tNS/MVsWJW1v8VHAPwl9B4Ca3pCrjmvqyC+S1C/6UHsMxF2GoFPraS5Yyg56vFz9brVpFojMA==",
- "license": "Apache-2.0",
- "dependencies": {
- "@hono/node-server": "^1.19.9",
- "hono": "^4.11.4"
- },
- "engines": {
- "node": ">=20"
- },
- "peerDependencies": {
- "@modelcontextprotocol/server": "^2.3.0"
- }
- },
- "node_modules/@modelcontextprotocol/server": {
- "version": "2.3.0",
- "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.0.tgz",
- "integrity": "sha512-+6b0LdsQLmHsvS7J6sQJ4weTpzUn61fU1JKS+321/+IyDYoHW5CR2Tgqcs6GgAAQvlesCo6yX3xttgmx+XGtJw==",
- "license": "Apache-2.0",
- "dependencies": {
- "@modelcontextprotocol/core": "2.3.0",
- "zod": "^4.2.0"
- },
- "engines": {
- "node": ">=20"
- }
- },
- "node_modules/@poppinss/colors": {
- "version": "4.1.6",
- "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",
- "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "kleur": "^4.1.5"
- }
- },
- "node_modules/@poppinss/dumper": {
- "version": "0.6.5",
- "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz",
- "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@poppinss/colors": "^4.1.5",
- "@sindresorhus/is": "^7.0.2",
- "supports-color": "^10.0.0"
- }
- },
- "node_modules/@poppinss/exception": {
- "version": "1.2.3",
- "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz",
- "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/@sindresorhus/is": {
- "version": "7.2.0",
- "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",
- "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=18"
- },
- "funding": {
- "url": "https://github.com/sindresorhus/is?sponsor=1"
- }
- },
- "node_modules/@speed-highlight/core": {
- "version": "1.2.24",
- "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz",
- "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==",
- "dev": true,
- "license": "CC0-1.0"
- },
- "node_modules/@typescript/typescript-aix-ppc64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
- "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "aix"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-darwin-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
- "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-darwin-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
- "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-freebsd-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
- "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-freebsd-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
- "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-arm": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
- "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
- "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-loong64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
- "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
- "cpu": [
- "loong64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-mips64el": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
- "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
- "cpu": [
- "mips64el"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-ppc64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
- "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-riscv64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
- "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
- "cpu": [
- "riscv64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-s390x": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
- "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
- "cpu": [
- "s390x"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-linux-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
- "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-netbsd-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
- "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-netbsd-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
- "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-openbsd-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
- "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-openbsd-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
- "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-sunos-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
- "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "sunos"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-win32-arm64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
- "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/@typescript/typescript-win32-x64": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
- "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/cookie": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
- "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=18"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/detect-libc": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
- "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
- "dev": true,
- "license": "Apache-2.0",
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/error-stack-parser-es": {
- "version": "1.0.5",
- "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",
- "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==",
- "dev": true,
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/antfu"
- }
- },
- "node_modules/esbuild": {
- "version": "0.28.1",
- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
- "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
- "dev": true,
- "hasInstallScript": true,
- "license": "MIT",
- "bin": {
- "esbuild": "bin/esbuild"
- },
- "engines": {
- "node": ">=18"
- },
- "optionalDependencies": {
- "@esbuild/aix-ppc64": "0.28.1",
- "@esbuild/android-arm": "0.28.1",
- "@esbuild/android-arm64": "0.28.1",
- "@esbuild/android-x64": "0.28.1",
- "@esbuild/darwin-arm64": "0.28.1",
- "@esbuild/darwin-x64": "0.28.1",
- "@esbuild/freebsd-arm64": "0.28.1",
- "@esbuild/freebsd-x64": "0.28.1",
- "@esbuild/linux-arm": "0.28.1",
- "@esbuild/linux-arm64": "0.28.1",
- "@esbuild/linux-ia32": "0.28.1",
- "@esbuild/linux-loong64": "0.28.1",
- "@esbuild/linux-mips64el": "0.28.1",
- "@esbuild/linux-ppc64": "0.28.1",
- "@esbuild/linux-riscv64": "0.28.1",
- "@esbuild/linux-s390x": "0.28.1",
- "@esbuild/linux-x64": "0.28.1",
- "@esbuild/netbsd-arm64": "0.28.1",
- "@esbuild/netbsd-x64": "0.28.1",
- "@esbuild/openbsd-arm64": "0.28.1",
- "@esbuild/openbsd-x64": "0.28.1",
- "@esbuild/openharmony-arm64": "0.28.1",
- "@esbuild/sunos-x64": "0.28.1",
- "@esbuild/win32-arm64": "0.28.1",
- "@esbuild/win32-ia32": "0.28.1",
- "@esbuild/win32-x64": "0.28.1"
- }
- },
- "node_modules/hono": {
- "version": "4.13.13",
- "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz",
- "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==",
- "license": "MIT",
- "engines": {
- "node": ">=16.9.0"
- }
- },
- "node_modules/kleur": {
- "version": "4.1.5",
- "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
- "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/miniflare": {
- "version": "5.20261001.0-alpha",
- "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261001.0-alpha.tgz",
- "integrity": "sha512-GaimS5mSIOMyvd16ga+e1/QkI8cmp3z35QPHFex0DktqNQf2RVZQwMPQXdyoUreUiFP/0Gpe2MoQInTyMAD5xA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@cspotcode/source-map-support": "0.8.1",
- "sharp": "0.35.4",
- "undici": "7.29.1",
- "workerd": "1.20261001.1",
- "ws": "8.21.0",
- "youch": "4.1.0-beta.10"
- },
- "engines": {
- "node": ">=22.0.0"
- }
- },
- "node_modules/oauth4webapi": {
- "version": "3.8.8",
- "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz",
- "integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/panva"
- }
- },
- "node_modules/semver": {
- "version": "7.8.5",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
- "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
- "dev": true,
- "license": "ISC",
- "bin": {
- "semver": "bin/semver.js"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/sharp": {
- "version": "0.35.5",
- "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
- "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
- "dev": true,
- "license": "Apache-2.0",
- "dependencies": {
- "@img/colour": "^1.1.0",
- "detect-libc": "^2.1.2",
- "semver": "^7.8.5"
- },
- "engines": {
- "node": ">=20.9.0"
- },
- "funding": {
- "url": "https://opencollective.com/libvips"
- },
- "optionalDependencies": {
- "@img/sharp-darwin-arm64": "0.35.5",
- "@img/sharp-darwin-x64": "0.35.5",
- "@img/sharp-freebsd-wasm32": "0.35.5",
- "@img/sharp-libvips-darwin-arm64": "1.3.4",
- "@img/sharp-libvips-darwin-x64": "1.3.4",
- "@img/sharp-libvips-linux-arm": "1.3.4",
- "@img/sharp-libvips-linux-arm64": "1.3.4",
- "@img/sharp-libvips-linux-ppc64": "1.3.4",
- "@img/sharp-libvips-linux-riscv64": "1.3.4",
- "@img/sharp-libvips-linux-s390x": "1.3.4",
- "@img/sharp-libvips-linux-x64": "1.3.4",
- "@img/sharp-libvips-linuxmusl-arm64": "1.3.4",
- "@img/sharp-libvips-linuxmusl-x64": "1.3.4",
- "@img/sharp-linux-arm": "0.35.5",
- "@img/sharp-linux-arm64": "0.35.5",
- "@img/sharp-linux-ppc64": "0.35.5",
- "@img/sharp-linux-riscv64": "0.35.5",
- "@img/sharp-linux-s390x": "0.35.5",
- "@img/sharp-linux-x64": "0.35.5",
- "@img/sharp-linuxmusl-arm64": "0.35.5",
- "@img/sharp-linuxmusl-x64": "0.35.5",
- "@img/sharp-webcontainers-wasm32": "0.35.5",
- "@img/sharp-win32-arm64": "0.35.5",
- "@img/sharp-win32-ia32": "0.35.5",
- "@img/sharp-win32-x64": "0.35.5"
- },
- "peerDependenciesMeta": {
- "@types/node": {
- "optional": true
- }
- }
- },
- "node_modules/supports-color": {
- "version": "10.2.2",
- "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",
- "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=18"
- },
- "funding": {
- "url": "https://github.com/chalk/supports-color?sponsor=1"
- }
- },
- "node_modules/tslib": {
- "version": "2.8.1",
- "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
- "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
- "dev": true,
- "license": "0BSD",
- "optional": true
- },
- "node_modules/typescript": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
- "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
- "dev": true,
- "license": "Apache-2.0",
- "bin": {
- "tsc": "bin/tsc"
- },
- "engines": {
- "node": ">=16.20.0"
- },
- "optionalDependencies": {
- "@typescript/typescript-aix-ppc64": "7.0.2",
- "@typescript/typescript-darwin-arm64": "7.0.2",
- "@typescript/typescript-darwin-x64": "7.0.2",
- "@typescript/typescript-freebsd-arm64": "7.0.2",
- "@typescript/typescript-freebsd-x64": "7.0.2",
- "@typescript/typescript-linux-arm": "7.0.2",
- "@typescript/typescript-linux-arm64": "7.0.2",
- "@typescript/typescript-linux-loong64": "7.0.2",
- "@typescript/typescript-linux-mips64el": "7.0.2",
- "@typescript/typescript-linux-ppc64": "7.0.2",
- "@typescript/typescript-linux-riscv64": "7.0.2",
- "@typescript/typescript-linux-s390x": "7.0.2",
- "@typescript/typescript-linux-x64": "7.0.2",
- "@typescript/typescript-netbsd-arm64": "7.0.2",
- "@typescript/typescript-netbsd-x64": "7.0.2",
- "@typescript/typescript-openbsd-arm64": "7.0.2",
- "@typescript/typescript-openbsd-x64": "7.0.2",
- "@typescript/typescript-sunos-x64": "7.0.2",
- "@typescript/typescript-win32-arm64": "7.0.2",
- "@typescript/typescript-win32-x64": "7.0.2"
- }
- },
- "node_modules/undici": {
- "version": "7.29.1",
- "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz",
- "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=20.18.1"
- }
- },
- "node_modules/workerd": {
- "version": "1.20261001.1",
- "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261001.1.tgz",
- "integrity": "sha512-d/SIYHFO0PT/wiFZg8in4NpRIxYuFwslX1HdylOtWkBIIUmSpkGFhK820cV84XACFylwJ48xuRoWW/8DWDPsPQ==",
- "dev": true,
- "hasInstallScript": true,
- "license": "Apache-2.0",
- "bin": {
- "workerd": "bin/workerd"
- },
- "engines": {
- "node": ">=16"
- },
- "optionalDependencies": {
- "@cloudflare/workerd-darwin-64": "1.20261001.1",
- "@cloudflare/workerd-darwin-arm64": "1.20261001.1",
- "@cloudflare/workerd-linux-64": "1.20261001.1",
- "@cloudflare/workerd-linux-arm64": "1.20261001.1",
- "@cloudflare/workerd-windows-64": "1.20261001.1"
- }
- },
- "node_modules/ws": {
- "version": "8.21.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
- "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=10.0.0"
- },
- "peerDependencies": {
- "bufferutil": "^4.0.1",
- "utf-8-validate": ">=5.0.2"
- },
- "peerDependenciesMeta": {
- "bufferutil": {
- "optional": true
- },
- "utf-8-validate": {
- "optional": true
- }
- }
- },
- "node_modules/youch": {
- "version": "4.1.0-beta.10",
- "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz",
- "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@poppinss/colors": "^4.1.5",
- "@poppinss/dumper": "^0.6.4",
- "@speed-highlight/core": "^1.2.7",
- "cookie": "^1.0.2",
- "youch-core": "^0.3.3"
- }
- },
- "node_modules/youch-core": {
- "version": "0.3.3",
- "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz",
- "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@poppinss/exception": "^1.2.2",
- "error-stack-parser-es": "^1.0.5"
- }
- },
- "node_modules/zod": {
- "version": "4.6.5",
- "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
- "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/colinhacks"
- }
- }
- }
-}
diff --git a/hosting/package.json b/hosting/package.json
deleted file mode 100644
index eee42875..00000000
--- a/hosting/package.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "name": "@instruktlabs/kiln-hosted",
- "version": "1.0.0-rc.1",
- "private": true,
- "type": "module",
- "scripts": {
- "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json && tsc --noEmit -p tsconfig.probe.json",
- "test": "node --test test/*.test.mjs",
- "build": "node scripts/build.mjs"
- },
- "dependencies": {
- "@cloudflare/workers-oauth-provider": "1.2.1",
- "@modelcontextprotocol/node": "2.1.1",
- "@modelcontextprotocol/server": "2.3.0",
- "oauth4webapi": "3.8.8"
- },
- "overrides": {
- "miniflare": {
- "sharp": "0.35.5"
- }
- },
- "devDependencies": {
- "@cloudflare/config": "0.23.0",
- "@cloudflare/workers-types": "5.20261006.1",
- "esbuild": "0.28.1",
- "miniflare": "5.20261001.0-alpha",
- "typescript": "7.0.2"
- }
-}
diff --git a/hosting/probe/CUSTOM_STARTUP.md b/hosting/probe/CUSTOM_STARTUP.md
deleted file mode 100644
index 201b39a8..00000000
--- a/hosting/probe/CUSTOM_STARTUP.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Minimal custom-registry startup control
-
-The managed-image control in [STARTUP.md](STARTUP.md) passed and consumed the
-third of five approved jobs. This completed candidate consumed one more job,
-leaving one. Do not rerun it. It did not repeat the managed control or expand
-the $1 allowance.
-
-Use the documented source of the managed image, official Node 24.20.0 on Debian
-Trixie slim, copied to the account's private Cloudflare registry. Its Linux AMD64
-manifest is pinned to
-`sha256:a747ad80c8a161b650d79a6da9c422005b91148b18b8d2c669eb5a0b7c07e600`.
-No Dockerfile, package install, Kiln code, user files or credentials are added.
-This tests custom-registry image resolution separately from engine image content.
-The prior Kiln image is an OCI index; that difference is a hypothesis to investigate,
-not an established incompatibility or a reason to strip release provenance.
-
-The image is configured through Wrangler's named `images.control` map and selected
-through `ctx.container.images.control`, as documented. The same controller retains
-one job, uses standard-2 with Internet disabled, runs the fixed version/UID/GID
-command, validates output/image identity, and destroys the whole instance. The
-configured-image path rejects absent, mutable or external-registry references.
-It accepts no image, command, source or job ID through RPC.
-
-The resources are Worker/application `kiln-private-custom-startup`, one job
-namespace, and registry repository `kiln-startup-control` with tag
-`node24-20261006`. Both HTTP entrypoints return 404; routes, workers.dev and preview
-URLs are disabled. The local operator is loopback-only and rejects browser origins
-and nonempty bodies. Do not deploy the operator.
-
-Use pinned Wrangler 4.147.0 for configuration and deployment, and cf
-1.0.0-beta.12 for registry/resource operations. Verify the pushed manifest digest
-matches the pinned image before deploying. Before invoking once, read back the
-uploaded Worker bytes, image map, private URL flags and deployment identity.
-Keep separate startup, output and teardown phase evidence. Stop after a failure;
-do not change the job ID or recreate the namespace to retry.
-
-The 60-second deadline, five-second cleanup budget and recovery alarm are unchanged.
-At the researched rates, 65 fully busy standard-2 seconds cost approximately
-$0.00233 in Container CPU/memory/disk before allowances, plus other service charges.
-The image transfer/storage is additional. This is not an invoice or dollar cap.
-
-After retaining evidence, stop the operator and remove only this application,
-Worker, namespace and registry image. Read back absence. A pass establishes the
-minimal custom-image path only; it does not qualify Kiln or hostile-source isolation.
-
-Source: [Cloudflare image management](https://developers.cloudflare.com/containers/guides/image-management/).
-
-## Completed private control
-
-Source `2c605257b8990a3bb9c9f0fffb5a9abc45092bc3` passed on 6 October 2026 at
-18:59:29 UTC. Its uploaded JavaScript matched SHA-256
-`84b82608d9baa9ea59cc49c56a5c34c66dc9482e22af14f5219c54945316ba7e`.
-The read-back image map matched the pinned custom registry reference above,
-both public URL flags were false, and the version advertised no URLs. Local Docker
-and the deployed fixed command both returned Node `v24.20.0` with UID/GID `0:0`.
-
-Output completed after 7,000 ms and awaited whole-instance destruction/inspection
-after 7,102 ms. The instance API separately reported stopped with exit code zero.
-These are one cold control's elapsed timings, not billed CPU or Kiln performance.
-A repeated RPC returned exactly the retained record without a new job.
-
-The operator was stopped; application, Worker, namespace and registry image were
-removed. Application/namespace lists, Worker 404, registry listing and absence of
-the local listener verified cleanup. Receipts remain in the diagnostic worktree's
-ignored `.cache/startup-custom-trial/`. Four of five approved jobs have now been
-attempted; one remains. No production deployment or support follow-up occurred.
-
-The candidate passed 129 hosted tests, all hosted typechecks/builds, root
-typecheck/lint, 3,290 root tests (two platform skips), Wrangler dry run and redacted
-source/bundle scans. Its hosted CI run is
-[37515318317](https://github.com/instruktlabs/kiln/actions/runs/37515318317).
-
-Wrangler explicitly prepared the image and waited for readiness before deployment.
-The earlier cf prebuilt deployment receipt also records the same preparation and
-ready transition; an omitted preparation step is therefore not supported as an
-explanation. The remaining image-index/content/controller differences require the
-unchanged Kiln-image control, still without importing the engine.
diff --git a/hosting/probe/GATEWAY_PREFLIGHT.md b/hosting/probe/GATEWAY_PREFLIGHT.md
deleted file mode 100644
index e8d482d5..00000000
--- a/hosting/probe/GATEWAY_PREFLIGHT.md
+++ /dev/null
@@ -1,66 +0,0 @@
-# Private gateway qualification stage
-
-This is a locally qualified component of the next combined provider trial, not
-a deployed trial or a renewed spending allowance. The earlier `c755434` trial
-is complete and its allowance remains consumed.
-
-`gateway-preflight.ts` runs thirteen fixed checks through the actual gateway,
-OAuth helper, primary D1 account/connection authority, tenant SQLite/R2 storage,
-and admission service. It first pauses native admission and leaves it paused.
-Discovery runs on the gateway; no step submits a native tool call. The current
-entrypoint is a local test fixture only. A private operator deployment, bounded
-execution/observation procedure and updated native phase still need preparation.
-
-The local fixture derives service and resource bindings from `deploymentConfig`,
-then bundles all six production Worker entrypoints separately. It adapts declared
-DO exports to local namespace registration. It does not attach Container images,
-deliver Analytics Engine points or run Cron Triggers. The default HTTP handler
-on the separate test driver returns 404.
-
-| Check | Evidence required |
-| --- | --- |
-| Fresh resources | Empty accounts, OAuth KV and artifact bucket; refuse existing data |
-| Pause native | Actual control RPC reports paused admission with no active work or pending cleanup |
-| Metadata | Protected-resource metadata names the configured MCP audience |
-| Synthetic accounts | Distinct permanent accounts, real registered clients, PKCE code exchange and primary connection activation |
-| Anonymous denial | Unauthenticated MCP receives 401 |
-| Edge discovery | A valid token can list the actual advertised MCP tools while compute is paused |
-| Oversized denial | An authenticated oversized body receives 413, followed by a successful ordinary request |
-| Storage fixture | Fixed routing-test files retained through the private tenant API and a download ticket issued |
-| Bearer isolation | Owner receives exact source bytes; another account with a forged tenant header cannot read them |
-| Browser isolation | Owner session receives exact bytes; another browser session is denied and an anonymous HEAD receives 401 |
-| Connection revocation | Primary D1 revokes the owner's app connection while its OAuth token remains in KV |
-| Revoked token denial | Old bearer and refresh credentials are rejected; the separate owner browser session still works |
-| Other account | Its MCP discovery still works and it still cannot read the owner's file |
-
-The synthetic identity module refuses any origin other than
-`https://kiln-private-qualification.invalid` and requires the explicit
-`isolated-synthetic-v1` mode. This origin is used only inside service-bound
-requests, with no DNS or public route. No Google/GitHub application, provider
-credential or upstream exchange is involved. Synthetic account subjects are
-fixture labels, not claims about actual GitHub users. The helper bypasses
-upstream identity verification to set up the private fixture; the unchanged
-gateway still verifies the resulting OAuth credentials and primary state.
-
-Credentials remain inside the invocation. The durable receipt contains only
-stage names, outcomes and compute-pause state; no account IDs, cookies, tokens,
-download capabilities, source, response bodies or exceptions. A transaction
-claims the sequence once before any setup. Repeated or concurrent calls read
-that record; they cannot recreate accounts or retry a partial run. A process
-interruption may leave a `running` receipt and temporary fixture data. That is
-an incomplete run, not permission to reset its namespaces and start again.
-
-Failure tests exercise a misbound gateway database, refusal of nonempty D1/KV/R2,
-and refusal of the production origin. Failures stop at their first case and
-retain a redacted receipt. Native admission remains paused once this stage has
-touched it. These checks do not prove that a remotely supplied binding belongs
-to the intended environment; independent inventory/readback is still required.
-
-The stored files are manually seeded routing fixtures, not engine output. This
-stage does **not** qualify rendering, engine save/provenance, materials, Google
-or GitHub consent, browser account-action confirmation, deletion, retention,
-scheduled recovery, approximate limiter behavior under load, alert delivery or
-public-client transport. Those remain explicit parts of the combined trial and
-launch verification. In particular, VM ceilings, response/evidence budgets,
-deadlines, cleanup and exact-image receipts must be reviewed before requesting
-another cloud execution allowance.
diff --git a/hosting/probe/INTEGRATED.md b/hosting/probe/INTEGRATED.md
deleted file mode 100644
index 1125dbb1..00000000
--- a/hosting/probe/INTEGRATED.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# Private integrated MCP trial
-
-Prepared on 6 October 2026. **Not deployed or authorized to run.** All 22 earlier
-approved jobs are consumed. This candidate needs a separate owner approval after
-its exact-source Linux and Windows hosted checks pass.
-
-## What this qualifies
-
-One fixed sequence through production admission, the installed MCP coordinator,
-host-owned HTTP interceptors, fresh evaluator/renderer VMs and private tenant
-storage. The scene is a public red/green textured cube and blue metallic sphere.
-It contains no user content, provider credentials or OAuth clients.
-
-| Step | Required result |
-| --- | --- |
-| Render | Actual MCP `kiln_render`, 1x1 preset at its default size, full-material fidelity and image content |
-| Save | Exact retained source saved with the default material preview |
-| Restore | A fresh coordinator restores the exact saved revision/program reference |
-| Source | Exact authored source recovered through a fresh request |
-| Export | The saved revision exports successfully |
-| GLB | Saved GLB resource has the binary glTF header |
-| Manifest | Saved identity and full-material preview metadata agree |
-| Other account source | The second synthetic account cannot read the first account's source |
-| Other account GLB | The second synthetic account cannot read the first account's GLB |
-| Quota | The tenth request receives HTTP 429 without starting a coordinator |
-
-Nine requests can be admitted. The normal fixture is expected to start nine
-coordinators, two evaluators and two renderers. The separate durable allowance
-permits **at most nine coordinator, four evaluator and four renderer starts**
-(17 total). A failed start consumes its claim; no refund, reset or replay can
-start additional work. Requests run sequentially with one active child per parent.
-Any failed assertion stops the sequence. Terminal cleanup closes the allowance
-and pauses production admission. A private operator can also stop it early.
-
-The saved manifest's engine identity is recorded, not accepted as verified
-provenance. The native host currently lacks an injected evaluator identity and
-may report `source-development:unverified`. That is a separate launch blocker.
-This trial does not qualify OAuth, account controls, public downloads, production
-load, settled billing or vendor submissions.
-
-## Immutable candidate and privacy
-
-- Coordinator image: `sha256:029c4fba6f0521a5a18c9dde364d07b5ffc076fe4d988358868950de40134b66`.
-- Evaluation/render image: `sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24`.
-- Both install the exact published `@instruktlabs/[email protected]` archive.
-- Worker: `kiln-private-integrated-v1`; three Container applications append
- `-coordinator`, `-evaluation` and `-render`.
-- Seven SQLite Durable Object classes; one disposable private R2 bucket,
- `kiln-private-integrated-v1-evidence`.
-- Worker SHA-256: `3ff536d4e99b8ee348d2a55e5a0de58ca04895643f53ccba4a68cf5ee570312a`.
-- No public route, workers.dev address, preview URL, trigger, SSH or Container logs.
- The default HTTP handler returns 404. Operator methods require a private service
- binding. Native internet access is disabled; only the three host-owned loopback
- routes are intercepted.
-- Coordinator uses `standard-1`, with a 120-second parent deadline. Evaluation
- and rendering use `standard-2`, with 60- and 30-second deadlines respectively.
- Whole-instance destruction must be acknowledged before releasing results/capacity.
-- Two fixed synthetic tenant IDs, 64 MiB storage each. Evidence has an independent
- 64 MiB aggregate cap and 8 MiB per-response cap. Raw responses are written only
- to the disposable private bucket; control receipts retain hashes and outcomes.
-
-## Cost proposal
-
-Propose a **separate $1 trial allowance**, not another subscription or a
-provider-enforced spending cap. The existing Workers Paid account is reused.
-
-At full allocated CPU for every deadline, the maximum listed starts imply
-1,080 coordinator-seconds, 240 evaluator-seconds and 120 renderer-seconds.
-Using current published rates, these total approximately **$0.036 in Container
-compute, memory and disk before included allowances**, excluding startup/cleanup
-overrun and other meters. Thirty extra seconds per instance adds about $0.0142.
-The $1 proposal leaves room for Workers, Durable Objects, R2, image storage and
-operating overhead. It is an estimate, not a measured invoice or an assurance
-against a provider cleanup failure; such a failure stops the trial and requires
-operator cleanup and a provider-state readback.
-
-Sources checked 6 October: [Container pricing](https://developers.cloudflare.com/containers/platform/pricing/)
-and [instance types](https://developers.cloudflare.com/containers/platform/limits/).
-CPU is billed for active usage; memory/disk use allocated capacity. This estimate
-deliberately assumes full CPU utilization and does not consume a claimed remaining
-free allowance.
-
-## Local preparation and evidence
-
-`hosting/scripts/build-integrated-probe.mjs` compiles locally with the installed
-Cloudflare configuration schemas and verifies `[email protected]`. It requires an
-explicit account ID, output path under the repository's `.cache`, and cf package
-metadata path. It neither provisions resources nor uploads/deploys anything.
-The prepared output and receipt are under `.cache/integrated-provider/`.
-
-The native MCP tests exercise the complete fixed sequence with a fresh host per
-request and real local tenant storage. Their injected image port verifies the
-contract, not rendering fidelity. Separately, the immutable installed renderer
-and coordinator images have real offline Docker receipts in the image guide.
-Neither substitutes for the proposed provider trial.
-
-The actual local Worker/RPC/SQLite/R2 fixture checks 404 public behavior, a missing
-Container result, exact evidence retention, closed allowance, paused admission,
-zero live reservations and replay after durable-object eviction. An initial test
-exposed an unread RPC body on early native rejection that prevented eviction;
-closing that body fixes it. A second regression verifies cancellation when the
-diagnostic allowance itself rejects a request before dispatch. Both defects were
-observed failing before the fixes. The full 270-test hosted suite, three hosted
-typechecks and twelve production bundles pass locally; an additional configuration
-test passes against the generated private deployment. Exact-source CI remains required.
-
-## Approved-run procedure
-
-1. Obtain the owner's approval for this exact candidate and bounded allowance.
-2. Upload the two immutable image manifests and verify their remote config/layers.
- Create only the named temporary bucket, then deploy the prepared configuration
- with the verified cf CLI. Read back deployed JavaScript, image identity,
- Container settings, namespace bindings and absence of public routes/triggers.
-3. Bind a localhost-only operator to `KilnIntegratedControl`. Trigger `runFixed`
- once. A timeout is an observation timeout, not permission to start another run.
- Poll the retained record; do not recreate/reset its namespaces on failure.
-4. Retrieve the case responses and independently decode images and GLB, compare
- exact source and metadata, and inspect the rendered fixture. Record timing,
- actual VM count, provider state, budget claims and cleanup outcomes.
-5. Replay the private RPC only to verify the retained result and unchanged claim
- count. If interrupted, call `stop` and verify all instances stopped; do not
- interpret an unfinished run as acceptance.
-6. Retain receipts locally, remove only this trial's instances/applications,
- Worker and seven namespaces, delete its bucket contents and bucket, and remove
- its temporary registry references. Verify absence in the provider APIs and
- stop the localhost operator/remove its temporary registry login. Do not delete
- unrelated account resources or assume a delete response proves cleanup.
-
-Record the exact deployed source, results and cleanup readbacks here after the
-approved run. Production launch remains a separate candidate and approval.
diff --git a/hosting/probe/KILN_STARTUP.md b/hosting/probe/KILN_STARTUP.md
deleted file mode 100644
index 386cdb4d..00000000
--- a/hosting/probe/KILN_STARTUP.md
+++ /dev/null
@@ -1,70 +0,0 @@
-# Unchanged Kiln-image startup control
-
-The managed and minimal custom-registry controls passed. This completed candidate
-consumed the fifth and final job of the original $1 trial. No jobs remain.
-Do not retry it by changing the name or recreating its namespace.
-
-Use the existing `kiln-evaluation:rc1-local` image unchanged, including its original
-OCI index, Node 22.23.3 runtime, installed public RC, entrypoint and `USER node`.
-Its immutable digest is
-`sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a`.
-Do not rebuild, change the user, strip provenance or select another platform digest.
-Re-push these existing bytes to the private registry and verify the returned digest.
-
-The fixed control does not import or execute Kiln. It runs only the same Node
-version/UID/GID command as the two prior controls, with `exec` identity explicitly
-`1000:1000` as required by the native API. The controller requires the exact image
-reference, Node version and numeric identity; the UID is not a security boundary.
-No command, source, image, environment or job ID is accepted from RPC.
-
-Deploy the ordinary pinned Wrangler configuration with Worker/application
-`kiln-private-image-startup`, one job namespace, no public URLs and no provider or
-storage credentials. Verify uploaded bytes, image map, deployment and privacy
-settings before the fixed private RPC. The loopback-only operator rejects browser
-origins/nonempty bodies and is never deployed.
-
-The same standard-2 size, disabled egress, 60-second deadline, five-second cleanup
-budget, recovery alarm and bounded outputs remain. The fixed job is retained even
-after failure or interruption. At the researched rates, 65 fully busy seconds cost
-about $0.00233 in Container CPU/memory/disk before allowances, with other services
-and registry storage additional. This is not an invoice or provider dollar cap.
-
-Retain the result and verify whole-instance stop; then stop the operator and remove
-only this application, Worker, namespace and `kiln-evaluation:rc1-local` registry
-image. Read back absence. A pass qualifies image startup only, not native evaluation,
-hostile-source isolation, CPU/software rendering or hosted launch. After this
-attempt, further cloud jobs require a concrete new scope and owner approval.
-
-Source: [native process identity](https://developers.cloudflare.com/containers/api/durable-object-container/).
-
-## Completed attempt: image startup failed
-
-Source `569fc5313f909c04ac960348b638e376cdb36239` was deployed with the exact
-original image on 6 October 2026. The uploaded JavaScript was read back and matched
-SHA-256 `57c509e5b71d086f18e8b3d900d3dfc2bbbc48a369ef816c057b946abe3a018a`.
-The deployed image map matched the original digest, public URL flags were false,
-and the version had no URLs or bindings beyond its job namespace. Wrangler reported
-the image prepared and ready before deployment.
-
-At 19:08:40 UTC the fixed invocation failed with `MONITOR_FAILED` after 1,242 ms.
-The trace reached `start` and `setInactivityTimeout`, but never entered `exec`.
-The Node command and Kiln engine were therefore not executed by this controller.
-Destruction and stopped inspection completed after 1,243 ms. The instance list was
-empty, and replay returned the exact retained failure without another attempt.
-
-The local operator was stopped; the application, Worker, namespace and registry
-image were removed. Readbacks verified absence and Worker 404. Receipts remain
-in the diagnostic worktree's ignored `.cache/startup-kiln-trial/`. The original
-five-job allowance is exhausted; no further cloud execution is authorized by it.
-
-Local checks passed all 131 hosted tests, all hosted typechecks/builds, root
-typecheck/lint, deployment dry run and redacted source/bundle scans. No engine
-source or package content changed; its full 3,290-test suite had passed on the
-preceding custom-image candidate. The current hosted CI run is
-[37516547552](https://github.com/instruktlabs/kiln/actions/runs/37516547552).
-
-This narrows the failure to this image or its startup configuration under the
-native API; the same controller starts managed and minimal custom images. It does
-not establish that OCI indexes, image `USER node`, a particular layer or Cloudflare
-itself is defective. Continue local image analysis before preparing a separately
-bounded next trial. Native evaluation and hosted launch remain unqualified.
diff --git a/hosting/probe/MANIFEST_STARTUP.md b/hosting/probe/MANIFEST_STARTUP.md
deleted file mode 100644
index 4d8aeea7..00000000
--- a/hosting/probe/MANIFEST_STARTUP.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# Proposed single-platform manifest control
-
-**Completed with owner approval on 6 October; its one job is consumed.** The original
-five-job trial is exhausted. This candidate permits one additional fixed job,
-with a $1 trial allowance covering its temporary Worker, Container and registry
-usage. The allowance is not a provider-enforced billing cap.
-
-Cloudflare's [current image builder](https://github.com/cloudflare/workers-sdk/blob/main/packages/containers-shared/src/build.ts)
-uses `--platform linux/amd64 --provenance=false`. The original Kiln image is an OCI
-index containing a Linux/AMD64 runtime manifest and an attestation. The successful
-minimal custom control selected a platform manifest directly. This is a specific
-image-format hypothesis, not a confirmed incompatibility or vendor defect.
-
-Select the original image's existing runtime manifest directly:
-
-```text
-sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8
-```
-
-Read-only inspection of the retained OCI archive verified the descriptor hashes.
-This manifest selects the same config `fe7ab6cb...`, ten filesystem layers, Node
-22.23.3, installed RC, `USER node` and entrypoint as the failed index. Do not rebuild
-the image, reinstall dependencies, change users or substitute another digest.
-Keep the original local index and attestation available as evidence.
-
-After approval, tag that local image as
-`registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation:rc1-platform-control`
-and push only `--platform linux/amd64`. Docker documents that this pushes the
-[platform manifest without the index or its attestations](https://docs.docker.com/reference/cli/docker/image/push/).
-Read the remote manifest and require the exact digest/config/layers above before
-deployment. An unexpected digest is a stop, not permission to change the controller.
-
-Deploy `manifest-startup.wrangler.jsonc` with pinned Wrangler 4.147.0. Verify uploaded
-Worker bytes, private bindings, disabled public URLs, exact image map and image
-preparation before invoking `KilnManifestStartupControl.runFixed()` once through
-a private service binding. The local operator must bind only loopback, reject
-browser origins and nonempty bodies, and must never be deployed.
-
-The unchanged lifecycle requires a fresh standard-2 VM, disabled Internet access,
-60-second execution deadline, bounded output, numeric exec identity `1000:1000`,
-whole-instance destruction and stopped inspection within the five-second cleanup
-budget, with a durable recovery alarm if cleanup fails. The command prints only
-Node version and UID/GID; it never imports Kiln or accepts source. Both HTTP
-entrypoints return 404. A durable claim prevents a second invocation, including
-after failure. At researched rates, 65 fully busy seconds cost approximately
-$0.00233 for Container CPU/memory/disk before allowances; other services and
-registry storage are additional.
-
-Preserve phase results and confirm stopped. Then remove only this candidate's
-application, Worker, namespace, registry tag and local operator, verifying absence.
-Do not recreate its namespace or reset its durable claim to retry. Whether it
-passes or fails, stop after this job and interpret it alongside the original
-index result. Startup success would still not qualify native evaluation, hostile
-input isolation, rendering or production hosting.
-
-## Local evidence
-
-The two new focused cases failed before implementation, then all 16 diagnostic
-cases passed. They check the exact manifest, original-index substitution denial,
-numeric identity, wrong runtime output, retained replay and private entrypoints.
-The complete hosted suite passes 133 tests; hosted typechecks/builds and root
-typecheck/lint pass. Wrangler's deployment dry run passes without uploading or
-starting a Container. Redacted source and actual JavaScript/source-map scans pass
-(12.64 KB and 30.65 KB respectively). The Worker bundle SHA-256 is
-`f339a35a1bc271bda9e985f03d0d0f9911979617b375bd6bcadd08ccc6d80a43`.
-Retain CI and compare deployed bytes before any approved cloud invocation.
-This diagnostic changes no engine or package code.
-
-## Provider result
-
-At 19:49:18 UTC, source `29fc0ac248f59aa1d8c6f6ca89160c85d266e8ca`
-passed this single job. Remote inspection verified the exact manifest, config and
-all ten original layers before deployment; the uploaded Worker matched the local
-hash above. Runtime output was Node `v22.23.3`, UID/GID `1000:1000`. Output
-completed at 10,865 ms; whole-instance destruction and stopped inspection completed
-at 10,959 ms. Cloudflare independently reported stopped with exit code zero.
-Replay returned the identical retained result without another execution.
-
-The application, Worker, namespace and registry tag were removed and readbacks
-verified absence. The loopback operator stopped and temporary Docker registry
-credentials were removed. Receipts are retained in the diagnostic worktree's
-`.cache/startup-manifest-trial/`; the settled billing total is not yet known.
-
-This comparison strongly implicates selection of the original index versus its
-runtime manifest. It is one controlled observation, not proof that every OCI
-index is unsupported or that the vendor has a general defect. Native Kiln
-evaluation, rendering and isolation are still unqualified. No support follow-up
-was sent. Further cloud jobs require a separately approved candidate and allowance;
-see [the proposed qualification](QUALIFICATION.md).
diff --git a/hosting/probe/NATIVE_LIFECYCLE.md b/hosting/probe/NATIVE_LIFECYCLE.md
deleted file mode 100644
index 8d16c049..00000000
--- a/hosting/probe/NATIVE_LIFECYCLE.md
+++ /dev/null
@@ -1,191 +0,0 @@
-# Private native lifecycle qualification stage
-
-This component prepares bounded private combined-service trials. The October 7
-candidate passed its fixed gateway/native sequence and verified cloud cleanup;
-see the [exact result and limitations](../../docs/reviews/2026-10-07-private-lifecycle-result.md).
-The offline preparation command does not authorize spending or reuse of an earlier
-allowance. A new execution still requires its own frozen candidate and approval.
-
-`lifecycle-run.ts` performs 21 fixed stages, in order:
-
-1. Create and read a small procedural material.
-2. Render and save an asset using its exact locked material revision.
-3. Restore the program, read its editable source and export the saved revision.
-4. Read its GLB and manifest; require exact evaluator image provenance and full
- material fidelity rather than accepting an unverified or CPU fallback result.
-5. Download source, GLB and material closure. Match source bytes, the GLB hash and
- material contents to the preceding responses; require `no-store`.
-6. Deny another account and an anonymous browser the owner's download. Deny
- foreign source/material reads without leaking their contents in error bodies.
-7. Remove only the disposable owner's live material group through a private
- control, import the saved asset into its library, then retrieve the restored
- material and render the retained source again.
-8. Require the next MCP request to be rejected by the configured compute quota.
-
-This requires 14 admitted MCP requests and one quota rejection. The local actual
-engine fixture observes three evaluations and three renders. The separate
-`LifecycleBudget` permits at most 14 coordinator, four evaluation and four render
-claims, a ceiling of **22 VM starts** enforced by the private wrappers.
-Claims are transactional, survive reconstruction, consume failed starts and cannot
-be refunded, reset or reopened. Closing before opening permanently refuses the
-allowance. This proposed ceiling is not an active approval or a dollar estimate.
-
-A transaction claims the lifecycle once before opening its ports. Interrupted,
-concurrent or repeated invocations return the stored record and cannot retry the
-sequence. Each stage stops the run on failure. HTTP requests carry abort signals;
-MCP responses have a 140-second outer deadline, downloads 15 seconds, and body
-reads, evidence retention and control/status operations ten seconds each. These
-are outer observation bounds; production VM deadlines and cleanup remain separate.
-Responses are limited to 8 MiB each and retained evidence to 64 MiB per run.
-
-The runner seals the allowance and pauses admission on exit, then requires zero
-active requests and pending cleanup. This is not proof of cloud-resource removal;
-the outer operator must independently inventory and delete the disposable resources.
-Its receipt contains stage names, outcomes, durations, response status/size/hash
-and verified engine identity. Credentials, source, download URLs and exceptions do
-not enter the receipt. Raw synthetic responses remain private bounded evidence.
-
-The local native fixture creates a fresh host for each request against the actual
-Node engine and tenant/R2 adapter. It uses a synthetic view producer and directly
-addresses private storage for downloads. Therefore it does not qualify real
-software Vulkan output, browser authentication or Cloudflare VM behavior. The
-separate gateway preflight covers real local gateway/token routing with synthetic
-identities. The operator now runs that preflight before creating fresh grants for
-the same two accounts and opening native admission. The combined local test stops
-at the first native request because Miniflare has no attached VM. This proves its
-expected failure/cleanup path, not the complete cloud lifecycle.
-
-Adversarial replays of actual engine responses reject altered download bytes,
-unverified manifest identity and leaked source/material data, including JSON-escaped
-source inside error responses. Additional cases prove allowance concurrency,
-one-use replay, oversized-body refusal and the actual ten-second evidence-write
-deadline. Late evidence completion cannot resume an already failed sequence.
-
-Live upstream OAuth, linking/deletion actions, real scheduled recovery, retention,
-load, settled costs, alerts and public-client verification remain launch gates.
-
-## Combined private topology and procedure
-
-`lifecycle-config.mjs` derives the six production roles, preserving their code and
-bindings except for the diagnostic allowance on the three native roles. The private
-gateway omits provider secret bindings and Cron. A private allowance Worker stores
-the one-use startup budget; a separate operator Worker owns the fixed sequence and
-synthetic credentials. This removes the circular dependency created by putting the
-allowance in the operator. A test requires every cross-Worker dependency to precede
-its caller in deployment order:
-
-`tenant -> allowance -> evaluation -> render -> request -> admission -> gateway -> operator`
-
-All eight Workers disable public routes, workers.dev, preview URLs and persisted
-logs/traces. Images retain production network/VM controls. The `.invalid` origin
-exists only in service-bound requests. Both operator HTTP handlers return 404;
-only a separate private service binding can call `runFixed`, `status` or `stop`.
-
-The operator is one-use across concurrent calls, eviction and replay. Its 15-minute
-alarm permanently closes the allowance and pauses admission. Unknown or non-idle
-cleanup retains a one-minute recovery alarm. No alarm resets requests or permits
-new starts. Status includes alarm/stop state. Control RPC results and promises are
-explicitly disposed after copying their plain values. This corrected retained
-capabilities found by the eviction test; replay preserves the closed allowance.
-See [Cloudflare RPC lifetimes](https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/).
-
-Prepare offline from a strict manifest with selected private resource IDs and
-pinned image references:
-
-```sh
-node hosting/scripts/prepare-deployment.mjs --private-lifecycle --manifest <manifest.json> --output .cache/<fresh-candidate>
-```
-
-The manifest fixes prefix `kiln-private-lifecycle-v1`, private origin, one concurrent
-request, fourteen daily/monthly admissions, a 120-second request deadline, 64 MiB
-tenant storage, 256 objects and 64 groups. Edge/account limits are 600/120 per minute
-for this test only; these are not adopted public quotas. The generator rejects
-changed limits, public origins, unexpected fields and existing output directories.
-It hashes eight bundles/configurations and nine account migrations. Tests reject
-unknown helpers and identity-provider code in native bundles. Production preparation
-retains its no-probe boundary. Synthetic-ID dry runs do not verify resource ownership.
-
-The next approved cloud execution must follow this sequence:
-
-1. Freeze a clean source commit with passing CI, verify both immutable image
- manifests and retain bundle/config hashes. Present the 22-start ceiling,
- deadlines, temporary resources and proposed spending allowance for approval.
- Previous trial allowances remain consumed.
-2. Inventory the owner's account and prove the trial names absent. Create only
- disposable trial D1/KV/R2 resources, insert their returned IDs in the manifest
- and rebuild its receipt. Never bind production data.
-3. Apply nine migrations and deploy in dependency order. Read back Worker versions,
- images, namespaces, bindings, disabled public surfaces and private storage.
- A CLI dry run cannot establish these properties.
-4. Establish a fresh private observer binding to `KilnLifecycleControl`. Read status,
- invoke `runFixed` once, then observe that same run through any interruption.
- Do not reset names or invoke a replacement run.
-5. Require the preflight, all native stages, exact image identity, closed allowance,
- paused admission, zero active/pending jobs and evidence hashes. Independently
- inspect actual image/GLB output; fidelity fields alone are not visual acceptance.
-6. Invoke `stop` on failure or completion and retain receipts/synthetic evidence
- privately. Confirm all Container instances gone, then remove the temporary
- observer and Workers in reverse dependency order, followed by their disposable
- namespaces and D1/KV/R2 data/resources. Inventory again to verify absence.
- Preserve pre-existing registry images unless explicitly included in cleanup.
-
-The local observer is `lifecycle-observer.ts`, with a dedicated
-`lifecycle-observer.wrangler.jsonc`. After trial approval and verified deployment,
-start it with the pinned Wrangler's `dev --config` command. Never deploy this
-facade. Its configured listener is `http://127.0.0.1:8798`; only POSTs with
-`X-Kiln-Operator: private-lifecycle-v1` to `/run-fixed`, `/status` and `/stop`
-are accepted. Browser origin/fetch metadata, other hosts/ports, query parameters
-and arbitrary controls are refused. This header is a browser-request guard, not
-a credential protecting against other programs running as the local user.
-
-It sends no RPC arguments, cancels uploaded bodies, returns `no-store` JSON,
-limits receipts to 128 KiB and redacts RPC failures. Status/stop observations have
-a ten-second deadline; the run observation allows sixteen minutes around the
-operator's fifteen-minute terminal alarm. Observation failure is an unknown result,
-not permission to repeat or replace the trial. Read the same run's durable status.
-Both promise and result capabilities are released, including late results after
-the observer deadline. The combined local topology/eviction tests now use this
-actual facade; focused tests cover its guards, timeout, disposal and size limit.
-Its config passes a Wrangler dry run. The approved October 7 trial used this local
-facade; its listener and remote proxy were stopped after verified cloud cleanup.
-
-`lifecycle-readback.mjs` verifies complete provider snapshots against the frozen
-manifest and clean candidate receipt. It requires exact code hashes and active
-versions, expected bindings and image digests, seven owned SQLite namespaces,
-private bucket surfaces, all nine recorded migrations, disabled Worker/Container
-logs and SSH, no routes/Cron, and no active/starting instances before admission.
-Unexpected bindings, including secrets, fail verification. The collector must
-retain complete pages and re-read them; synthetic fixtures are not cloud evidence.
-
-For each Worker the collector also retains `scriptSettings`, the raw result of
-[`GET .../workers/scripts/{name}/script-settings`](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/settings/methods/get/).
-Cloudflare returned `observability: null` for the disabled configuration in the
-October 7 private deployment. The CLI displayed inactive nested defaults such as
-`persist: true`; those defaults did not mean logs were enabled. The verifier accepts
-that representation only with explicit raw null evidence, disabled master/log/trace
-flags, disabled Logpush, and no tail consumers or log/trace destinations. Missing
-raw evidence and contradictory active settings fail. Non-null settings retain the
-strict redaction, invocation-log and persistence checks. Omitted empty binding/export
-collections are compared against the candidate's empty collections; required entries
-cannot be omitted. When present, D1's `database_id` alias must equal the expected ID.
-
-Its cleanup planner requires a stopped operator, closed allowance, paused idle
-admission, no recovery alarm and only stopped, correctly imaged VMs matched to
-recorded budget claims. Failed starts may consume a claim without producing a VM;
-failed qualification does not prevent cleanup once those safety conditions hold.
-The resulting plan selects only recorded trial resources, with Workers in reverse
-dependency order. Re-read resource IDs/versions immediately before deleting,
-retain bounded synthetic evidence, and verify absence afterward. A partial
-teardown failure needs inspection of its mutation receipts and current identities;
-never rerun the compute trial or force-delete unrelated references to recover.
-
-Deleting the private Workers/D1/KV/R2 resources is separate from erasing
-provider-managed operational data. The configured Analytics Engine dataset emits
-fixed, sanitized metrics, and Cloudflare documents **three months** of retention.
-The cleanup plan preserves registry images and explicitly does not assert that
-metrics were deleted. See [Analytics Engine limits](https://developers.cloudflare.com/analytics/analytics-engine/limits/).
-
-The linked October 7 result records concrete cloud and cleanup evidence for that
-candidate. This reusable procedure itself does not authorize another deployment.
-Real alarm firing, upstream sign-in, account actions, retention, monitoring and
-production load remain separate qualification requirements.
diff --git a/hosting/probe/QUALIFICATION.md b/hosting/probe/QUALIFICATION.md
deleted file mode 100644
index b3095be2..00000000
--- a/hosting/probe/QUALIFICATION.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# Manifest-based native qualification
-
-Completed with owner approval on 6 October. All four jobs passed; this allowance
-is now consumed and all temporary resources were removed. The original five-job allowance and
-the separately approved one-job manifest comparison are consumed. Do not recreate
-their namespaces or reset their claims. The approved scope was up to four new,
-sequential jobs with a separate $1 trial allowance, stopping on the first failure.
-The allowance is a planning bound, not a provider-enforced billing cap.
-
-`qualification.wrangler.jsonc` uses the proven original runtime manifest
-`sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8`
-and the existing fixed `worker.ts` controller. No image rebuild, dependency
-installation, user change or runtime-code change is part of this candidate.
-Keep the private operator local and bind it to `KilnProbeControl`; do not publish
-any HTTP route, domain, preview URL or automatic trigger.
-
-The four cases, enforced by `runProbeOnce`, are:
-
-1. Evaluate the installed public RC's fixed box program and require the same
- 1,912-byte GLB SHA-256 as the independent local and Linux CI fixtures.
-2. Probe direct TCP/DNS from native Node outside the JavaScript sandbox. Public
- Internet, metadata and renderer endpoints must remain inaccessible.
-3. Write a temporary marker and start a live detached child in one fresh VM,
- then destroy the whole VM.
-4. In a different fresh VM, verify neither the marker nor the child exists.
-
-Every job uses the production `ContainerEvaluationJob` controller: immutable image
-selection, numeric UID/GID `1000:1000`, disabled Internet, standard-2, 60-second
-deadline, durable alarm and five-second whole-instance destruction budget. The
-probe additionally inspects the stopped state before accepting each result.
-Bound output; retain fixed metadata and digest only, never raw native diagnostics.
-The coordinator persists its one-use claim before any execution and stops after
-a failed result. An interrupted or repeated trigger cannot restart the batch.
-
-Before invocation, verify exact CI source, bundle SHA-256, deployed image map,
-private bindings and absence of public URLs. Publish only the existing platform
-manifest, then inspect its digest/config/layers. Wrangler must report image
-preparation ready. After execution, retain results, verify stopped instances and
-remove the exact application, Worker, namespaces and registry tag with readbacks.
-Do not rerun a failed or interrupted batch under this allowance.
-
-Four fully busy 65-second standard-2 jobs would cost approximately $0.0093 for
-Container CPU/memory/disk before allowances at the researched rates; registry and
-Worker/DO charges are additional. This is not a settled invoice or a load estimate.
-
-Passing these checks would qualify basic engine execution and the tested provider
-boundaries only. CPU preview/software rendering, adversarial resource exhaustion,
-cancellation/alarm recovery, authenticated MCP, account controls, persistence,
-capacity and production launch remain separate gates.
-
-Local qualification passes 134 hosted tests, all three typechecks, five production
-bundle-boundary builds and root lint. The private configuration check first failed
-with the missing candidate, then passed after its addition. Pinned Wrangler
-4.147.0 dry-run deployment passes. Actual JavaScript and source-map secret scanning
-reports no matches across 43.09 KB. The Worker JavaScript SHA-256 is
-`0e97f19c8617d20f1bc96880aaa95b9e9303e45b560c7f242f7e19146527fede`.
-Exact-commit Linux/Windows CI passed as recorded below. Runtime source is unchanged from
-the existing probe; this preparation changes configuration, tests and records only.
-
-## Approved provider execution
-
-Both CI platforms passed source `8590c0abfcaedbfa8a34dfd76ac3322f01c0fb55`
-in [run 37522530858](https://github.com/instruktlabs/kiln/actions/runs/37522530858).
-The owner then approved this four-job batch and its $1 allowance. Invocation began
-at 20:04:01 UTC after exact remote manifest/config/layer and uploaded Worker checks.
-Worker/version metadata showed no public routes, URLs, external bindings or cron.
-
-| Case | Result | Elapsed including cleanup |
-| --- | --- | --- |
-| Installed engine box | Passed; 1,912-byte GLB SHA-256 `f94d231ed3eb4843a03704872adc3f20b00c2ea24567cb5916407b40a2cf1d40` | 3,398 ms |
-| Native TCP/DNS checks | Passed; tested endpoints were inaccessible | 15,320 ms |
-| Marker and detached child | Passed; child confirmed alive before whole-VM destruction | 1,260 ms |
-| Fresh VM | Passed; neither marker nor matching child present | 1,283 ms |
-
-Every result verified stopped state. Cloudflare's instance readback independently
-reported all four stopped with exit code zero. Repeating the private RPC returned
-the exact saved batch without new executions. These elapsed values are not billed
-CPU measurements, capacity estimates or representative cold-start percentiles.
-
-The application, Worker, both namespaces and registry tag were removed; subsequent
-readbacks verified absence. The loopback operator stopped and temporary registry
-authentication was removed. Receipts are under the diagnostic worktree's
-`.cache/manifest-qualification-trial/`. All ten jobs across the three separately
-approved scopes are consumed. No stable package or public service was published.
-Further tests need a prepared, reviewed scope and new authorization.
diff --git a/hosting/probe/README.md b/hosting/probe/README.md
deleted file mode 100644
index 36bf68e6..00000000
--- a/hosting/probe/README.md
+++ /dev/null
@@ -1,141 +0,0 @@
-# Private Cloudflare availability probe
-
-**Current status:** the original five-job allowance is exhausted. A separately
-approved sixth startup-only comparison passed when selecting the original image's
-Linux/AMD64 manifest directly. All trial resources were removed. See
-[the manifest result](MANIFEST_STARTUP.md) and the separately prepared
-[four-job qualification result](QUALIFICATION.md), which also passed all four cases
-and completed cleanup. All ten approved jobs are consumed. Neither the historical
-allowances below nor the old prebuilt receipt authorize another deployment.
-
-## Historical first trial
-
-This is a disposable operator probe, separate from every production bundle and
-the npm package. The owner approved a five-job trial with a $1 allowance. Its
-first job failed and all cloud trial resources were removed. The current candidate
-continues with only the four remaining jobs; it does not reset that allowance.
-The first stage answers whether the account can run the selected native image and
-whether basic network/filesystem/whole-VM cleanup checks work. It does not qualify
-the hosted service for launch.
-
-**Current stop condition:** the direct-RPC continuation at `cfbcb2a` has now
-attempted another job and failed during native startup. All cloud resources were
-removed and absence was verified. Subsequent smaller controls in
-[STARTUP.md](STARTUP.md) and [CUSTOM_STARTUP.md](CUSTOM_STARTUP.md) both passed.
-The unchanged image control in [KILN_STARTUP.md](KILN_STARTUP.md) then failed
-before its fixed Node command. Five jobs total have now been attempted; none remain.
-Do not redeploy this four-case candidate to a new coordinator. Prepare a revised
-diagnostic within the remaining scope, or obtain approval for a changed trial.
-The details below retain the reviewed four-case candidate for reproducibility.
-
-## Exact scope
-
-- Worker `kiln-private-evaluation-probe`, with no custom domain, route, workers.dev
- URL or version preview URL. Its HTTP handler always returns 404.
-- One SQLite coordinator namespace and one container-backed job namespace in the
- same Worker; no external service, credential, storage or identity bindings.
-- Container application `kiln-private-evaluation-probe-jobs`, using Cloudflare's
- `durable_object` scheduling policy, SSH disabled, no snapshots, and no container
- log collection. The controller starts each image with internet disabled.
-- Four remaining fixed jobs, sequentially: one installed-engine box fixture, direct native
- TCP/DNS reachability checks, a file plus live detached child, and a fresh VM
- checking that neither marker nor child is visible. The native checks bypass the
- JavaScript sandbox deliberately so they test the provider boundary.
-- Each job uses the production controller's 60-second deadline, durable alarm,
- output bounds, immutable image check and awaited whole-VM destruction. The
- probe stops at the first failure. No user may supply source or a command.
-- The `KilnProbeControl` named service entrypoint invokes only the fixed
- `availability-rc1` coordinator through `runFixed()`. An authenticated development
- service binding reaches it without a public URL. Both default and named HTTP
- handlers return 404. The prepared deployment has no cron. A durable transaction
- claims the entire run once; concurrent, later and interrupted calls cannot
- silently start another batch. Later calls only report retained state.
-- Read fixed result metadata through authenticated Workers logs. Never log source,
- arbitrary native output, identity records or credentials. Remove the
- Worker, probe namespaces and container application after retaining receipts;
- remove the trial registry image once it is no longer needed. Do not remove any
- existing application or resource.
-
-The four-job continuation is enforced in application state: the new scheduling policy
-does not support `max_instances`. There is no public invocation path. A controller
-failure requires investigation, not an automatic new run ID or a budget reset.
-Together with the first attempted job, this uses at most the original five jobs.
-One successful provider GLB can be compared with the two local/CI fixtures; it
-would not establish repeatability across two provider executions.
-
-## First attempt and scoped correction
-
-At source `ea08a16`, the live Worker matched SHA-256
-`6babbbb9073fbb4514b03675d73ee1387f30099cd6174cfca7ac8bc6515cc2e0` and the
-registry returned the exact local image digest below. The first `engine-a` job
-failed after 2,048 ms with `WORKER_FAILED` and a provider internal error. The
-controller destroyed the VM, the coordinator stopped, and the other four jobs
-did not run. Application/instance queries showed no running instances. The
-operator then deleted the exact trial application, Worker, both namespaces and
-registry image and verified their absence. This is failure and cleanup evidence,
-not successful native evaluation or a settled billing total.
-
-Cloudflare's current native API documentation says `exec` rejects user/group
-names. The image uses `node`, verified locally as numeric `1000:1000`. The
-continuation explicitly selects that numeric identity without changing the image
-or isolation settings. A regression test failed before this correction and
-passes afterward. This is a plausible explanation for the internal error, still
-requiring a live check. Operator-only diagnostics now retain the first failed
-API method name, never exception text or native output.
-
-The corrected scheduled deployment and a separate private trigger produced no
-observed invocation after their documented propagation windows. Both were removed,
-along with the application, namespaces and registry image; no additional job was
-observed. The next continuation uses the documented remote service-binding route
-above with the same remaining allowance. Local workerd verifies its HTTP denial,
-fixed run and retained result. This does not establish a successful provider run.
-
-## Local image and preparation
-
-The local image is `kiln-evaluation:rc1-local`, Linux amd64, immutable ID
-`sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a`.
-Its four-file context uses the approved public RC archive with SHA-256
-`f2de7eb69f6e16dd618c77249b1f46eda1b5d032789f5b0d9048b2b2a08ea8c2`.
-Two local fresh-container evaluations passed with identical 1,912-byte GLBs,
-matching the independently built Linux CI fixture. Receipts and resolved dependency
-inventory are retained under `.cache/evaluation-image-local-evidence/`.
-
-`scripts/build-provider-probe.mjs` bundles the reviewed source, validates its
-private configuration with pinned `@cloudflare/[email protected]`, and prepares Build
-Output for `[email protected]`. It never uploads or deploys. Pass `--cf-package`,
-`--account`, `--image` (managed-registry digest reference) and `--output` explicitly.
-From that output directory, `cf deploy --prebuilt --dry-run` must succeed before
-deployment. Do not rebuild or substitute an image after approval: verify the local
-image ID, use `cf containers push --tag kiln-evaluation:rc1-local`, and bind only
-the returned digest for those verified bytes. Retain the Worker bundle hash and
-final registry digest alongside the deployment/version/application IDs.
-
-The probe uses documented `ctx.exports` loopback namespaces. This also avoids a
-cf beta.12 dry-run validation problem: explicit same-Worker bindings are converted
-to `script_name`, which the container validator rejects as a foreign Worker.
-No CLI internals or production isolation controls were patched. Local workerd
-verified loopback calls, absent-container refusal, retained failure and HTTP denial.
-
-## Cost and remaining gates
-
-At the documented rates on 6 October, five jobs occupying `standard-2` (1 vCPU,
-6 GiB memory, 12 GB disk) for 65 seconds each cost roughly **$0.012** in metered
-container CPU, memory and disk before included allowances. This deliberately
-assumes a fully busy CPU throughout. Worker/DO/log charges are additional and tiny
-at this volume; existing applications share included usage. Reserve **up to $1**
-for this bounded trial, including image/storage overhead. This is an estimate, not
-a provider-enforced dollar cap. Keep the operator present, inspect unexpectedly
-running instances, and stop the trial on failure. Existing Workers Paid is reused.
-
-Subsequent qualification still requires CPU preview rendering, software Vulkan,
-memory exhaustion, output floods, infinite-loop and cancellation races, alarm
-recovery after controller interruption, cold-start/cost measurements and actual
-authenticated MCP plus storage integration. Passing this availability stage does
-not remove those launch gates.
-
-Sources: [native container API](https://developers.cloudflare.com/containers/api/durable-object-container/),
-[scheduling policy](https://developers.cloudflare.com/containers/configuration/scheduling-policy/),
-[pricing](https://developers.cloudflare.com/containers/platform/pricing/),
-[loopback bindings](https://developers.cloudflare.com/workers/runtime-apis/context/#exports),
-[remote service bindings](https://developers.cloudflare.com/workers/local-development/#using-remote-resources-with-durable-objects-and-workflows),
-[cf prebuilt deployment](https://developers.cloudflare.com/cf/projects/#deploy-a-prebuilt-build).
diff --git a/hosting/probe/RESILIENCE.md b/hosting/probe/RESILIENCE.md
deleted file mode 100644
index 17233c4f..00000000
--- a/hosting/probe/RESILIENCE.md
+++ /dev/null
@@ -1,164 +0,0 @@
-# Stable native rendering and recovery qualification
-
-Prepared and executed on 6 October 2026. **All twelve approved Cloudflare cases
-passed; trial resources were removed and absence verified.** The owner approved
-source `d068a7c` and a separate $1 allowance after both CI platforms passed.
-All 22 jobs across the four authorized scopes are now consumed. The batch stopped
-after its fixed cases and cannot reset or repeat its claim.
-The allowance is a planning bound, not a Cloudflare-enforced invoice cap.
-
-## Exact candidate
-
-`resilience.wrangler.jsonc` pins the independently built Linux/AMD64 software image
-`sha256:84a0fa62bcffa010b9ac1c5f2f0e2cf9045a9cdb6407f621e8049e6a37f9de99`.
-Its image configuration is
-`sha256:9c369c15226828815e0ebdb15cdc2091eb426fb42aa016f1556c8723307cddf3`.
-It contains the now-public stable package whose archive SHA-256 is
-`6ed3d6b9964429f14c3c6a0a6a13d56be509dd0f40b07061a37d491f901c1508`.
-The package lock audit reported zero known findings. The separate software image
-adds Mesa Vulkan/llvmpipe to the CPU image; it contains no probe scripts, provider
-credentials, user assets or listening application server.
-
-Pinned Wrangler 4.147.0 dry-run compilation produces a 30.68 KiB Worker with SHA-256
-`5d4021d4bbdc4920ccffe1eb34f93cd64f6d9752e73e19ffff75bede9ad594b8`.
-Gitleaks finds no matches in the probe source or actual Worker/source-map output.
-Production bundle checks exclude all probe and test imports.
-
-## Bounded provider work
-
-Each job uses a fresh `standard-2` instance and the production
-`ContainerEvaluationJob` controller: immutable image, numeric UID/GID `1000:1000`,
-Internet disabled, bounded input/output, durable watchdog, whole-instance
-destruction and stopped-state confirmation. Only the following fixed programs
-can run through the private `runFixed` service RPC:
-
-| Order | Case | Required evidence |
-| --- | --- | --- |
-| 1 | CPU preview | Actual stable evaluation and 128px CPU PNG matching the independent local digest |
-| 2 | Software views | Software Vulkan adapter; six 128px textured views across neutral/dark/light; retained PNGs, hashes and colour counts |
-| 3 | Native networking | Direct TCP/DNS outside Node vm cannot reach the tested Internet, metadata or renderer endpoints |
-| 4 | Marker and child | Write a temporary marker and establish a detached child is alive before destroying the VM |
-| 5 | Fresh VM | Neither marker nor child from the previous VM exists |
-| 6 | Native deadline | A native parent/child busy loop reaches readiness; the host deadline destroys the VM |
-| 7 | Native cancellation | Cancel 250ms after native readiness; destroy the whole VM and return the cancellation outcome |
-| 8 | stdout flood | Native readiness followed by output exhaustion trips the 1KiB stdout bound and destroys the VM |
-| 9 | stderr flood | Native readiness followed by output exhaustion trips the 16KiB stderr bound and destroys the VM |
-| 10 | Memory exhaustion | A child allocates beyond the VM allowance; SIGKILL and a positive kernel OOM counter delta are required |
-| 11 | Durable recovery | Inject one controller destruction failure; the real Durable Object alarm must subsequently confirm whole-VM destruction |
-| 12 | Engine afterward | A fresh VM executes the actual stable image entry and returns the expected 1,912-byte GLB digest |
-
-Native deadline and recovery jobs have 15-second deadlines; the others have
-60-second deadlines. Destruction/readback has a shared five-second bound. Native
-deadline evidence requires readiness at least one second before the deadline, so
-a startup failure cannot pass as an execution timeout. Recovery is observed from
-a different Durable Object for at most 45 seconds; the observer never calls the
-alarm handler itself. Operator cleanup after a missing alarm remains a failed
-result, even if a later callback succeeds.
-
-stdout is limited to 64KiB except the explicit flood case and software views.
-The six-image response is bounded at 512KiB; local measurement is 274,255 bytes.
-PNG signatures, structure, CRCs, dimensions and digests are validated outside the
-VM. Downloaded images must also be decoded and inspected before accepting the
-cloud rendering result; these are fixed material fixtures, not comprehensive
-visual-quality acceptance. SQLite-backed DO storage permits a combined key/value
-up to 2MB, above this bounded receipt
-([Cloudflare limits](https://developers.cloudflare.com/durable-objects/platform/limits/)).
-
-The coordinator persists its claim before execution, retains each result, runs
-sequentially and stops at the first failed case. Retries return the saved record;
-interrupted claims cannot silently restart. HTTP handlers always return 404;
-there are no routes, workers.dev/preview URLs, cron triggers or identity bindings.
-Native stdout/stderr logging is disabled. No arbitrary user source or external
-model call is accepted. A loopback-only operator receives the private service RPC.
-
-At current [Container rates](https://developers.cloudflare.com/containers/platform/pricing/),
-twelve fully busy 65-second standard-2 jobs model approximately $0.028 for CPU,
-allocated memory and disk before included allowances. Worker/DO, registry and
-other charges are additional. This is a conservative short-trial calculation,
-not a settled invoice or production capacity measurement.
-
-## Local evidence and execution procedure
-
-The focused tests first failed for missing private configuration and acceptance
-of truncated PNGs, then passed after the fixes. All 148 hosted tests, all three
-hosted typechecks, five production bundle checks, root typecheck and lint pass.
-Real workerd RPC tests deny public HTTP execution, fail closed without native
-compute and retain the one-use fixed batch across retries.
-
-All twelve fixed programs were exercised in restricted local Docker containers.
-The six material views and CPU preview decoded successfully; one material view
-was visually inspected. The software fixture initially truncated stdout at 64KiB;
-it now waits for the output stream to flush. The memory fixture observed one
-cgroup OOM kill with a 512MiB local cap. Busy-loop/flood checks prove those fixtures
-run and can be stopped locally, not that Cloudflare's deadlines or alarm recovery
-work. All local containers were removed and absence verified. Local receipts are
-under `.cache/resilience-local/`; the untracked local runner is
-`.cache/qualify-resilience-local.mjs`.
-
-Before requesting cloud approval, require exact-source Linux/Windows hosted CI.
-After approval, upload only the immutable runtime manifest and verify remote
-digest/config/layers. Verify the deployed Worker bundle/image identity and absence
-of public routes/triggers. Trigger once through the private operator and retain
-the results. Verify all instances stopped, including any failed case. Replaying
-the RPC must return the retained record without new jobs. Remove the exact trial
-application, Worker, namespaces and registry tag with absence readbacks; stop the
-operator and remove its temporary registry login. Do not restart a failed batch
-or recreate its namespaces under this allowance.
-
-Passing this trial would qualify these native/rendering/failure paths only.
-Authenticated MCP routing, account controls, private artifact lifecycle, global
-admission, load/cost measurement, production deployment and directory submissions
-remain separate launch work.
-
-## Approved Cloudflare result
-
-Exact-source Linux/Windows hosted CI passed in
-[run 37529896878](https://github.com/instruktlabs/kiln/actions/runs/37529896878).
-The owner then approved all twelve jobs. The remote registry manifest, config and
-layers matched the local image. `[email protected] deploy --prebuilt` deployed the
-exact compiled Worker; downloaded JavaScript matched the digest above. Version
-`af273169-3a66-4350-b7d8-6dede08f1bf2` and deployment
-`11289978-acde-4f2d-8036-02cd5c30197e` had no public route, URL, cron or external
-binding. The Container application disabled SSH and native logs. The loopback
-operator used Wrangler 4.147.0's remote service binding.
-
-| Case | Result | Elapsed including cleanup |
-| --- | --- | --- |
-| CPU preview | Passed; expected PNG digest | 13,583 ms |
-| Six software views | Passed; all PNGs retained and independently decoded | 13,286 ms |
-| Native network denial | Passed for the fixed TCP/DNS targets | 14,913 ms |
-| Marker and detached child | Passed; child alive before VM destruction | 7,644 ms |
-| Fresh VM | Passed; no prior marker or child | 1,102 ms |
-| Native deadline | Passed; ready at 929 ms, then deadline outcome | 15,101 ms |
-| Native cancellation | Passed; ready at 1,043 ms, then cancellation | 1,375 ms |
-| stdout flood | Passed; readiness and output-limit outcome | 963 ms |
-| stderr flood | Passed; readiness and output-limit outcome | 880 ms |
-| Memory exhaustion | Passed; child SIGKILL and one `/proc/vmstat` OOM kill | 15,412 ms |
-| Real alarm recovery | Passed; native ready at 950 ms and `ALARM_RECOVERED` | 15,079 ms |
-| Engine afterward | Passed; expected 1,912-byte GLB digest | 2,194 ms |
-
-All results confirmed whole-instance destruction. The provider API separately
-reported twelve stopped instances, with no active ones. The private RPC replay
-matched the retained result without starting another batch. These elapsed values
-are functional trial observations, not billed CPU, representative cold-start
-percentiles, throughput or a production cost forecast.
-
-All seven downloaded 128px PNGs passed an independent Windows pngjs decode, digest
-and colour-count check. Every image matched its local reference byte for byte.
-Visual inspection showed the matte cube, red/green textured cube and blue metallic
-sphere, both camera angles and all three backdrops. These small fixed fixtures
-qualify this software-rendering path, not comprehensive asset quality or capacity.
-
-The loopback operator stopped. Application `64098a73380d4e51b49fe937c6ccb99f`, Worker
-`3d13aa984bcb4b3dafb2de79288950a1`, both trial namespaces and the
-`kiln-evaluation:stable-resilience-control` registry tag were deleted. Follow-up
-reads verified absence. The temporary registry login was removed. Receipts,
-decoded images, immutable deployment metadata and cleanup readbacks are under
-the diagnostic worktree's `.cache/resilience-trial/`. No settled invoice is claimed.
-
-The original image-format and restricted nested-namespace failures remain in the
-earlier records. This result establishes the listed native VM paths and removes
-those specific qualification gaps. It does not turn the local Node MCP host into
-a deployed service: authenticated dispatch, production render adapters, private
-artifact lifecycle, account controls, admission/load/operations and end-to-end
-launch checks still require implementation or deployment evidence.
diff --git a/hosting/probe/STARTUP.md b/hosting/probe/STARTUP.md
deleted file mode 100644
index 086a0b07..00000000
--- a/hosting/probe/STARTUP.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# Managed-image startup control
-
-This private diagnostic isolates basic Cloudflare Container startup from Kiln,
-custom image preparation and the previous cf Build Output configuration. It uses
-Wrangler 4.147.0 with ordinary explicit Durable Object and service bindings.
-It is not a production evaluator and accepts no source, image, command or run ID.
-
-The owner authorized a five-job private trial with a $1 allowance. Two jobs had
-already been attempted before this candidate. This candidate has now consumed
-**one additional job**, leaving two for subsequent controls. Do not rerun this
-completed control, delete/recreate the namespace,
-change the fixed job ID, or redeploy a copy to regain an invocation. Even an
-interrupted or failed invocation keeps its durable claim. Cleanup alarms do not
-start another instance. This control does not reset or expand the allowance.
-
-## Fixed scope
-
-- Worker `kiln-private-startup-diagnostic`, application
- `kiln-private-managed-startup`, one SQLite Durable Object namespace.
-- No public route, domain, workers.dev or version preview URL. Both HTTP handlers
- return 404. A private service binding invokes `KilnStartupControl.runFixed()`.
-- `cloudflare/debian-trixie`, `standard-2`, Internet disabled, no snapshots,
- provider secrets, storage bindings, custom image upload or installed Kiln package.
-- A fixed Node command returns only its version and numeric UID/GID. The managed
- image currently supplies Node 24.20.0; a different version fails this control.
- It does not change Kiln's pinned Node 22.23.3 release runtime.
-- One 60-second deadline with a durable alarm, 1-KiB bounds on each output stream,
- five-second awaited destruction/inspection, and a cleanup recovery alarm if
- destruction cannot be confirmed. No arbitrary process output or exception text
- is retained. A process failure and a teardown failure have separate phase marks.
-
-At the rates checked on 6 October, 65 seconds of fully busy `standard-2` usage is
-approximately $0.00233 in Container CPU/memory/disk before included allowances.
-Worker/DO/log charges are additional. Keep the existing $1 trial allowance and
-read back resource absence after cleanup; this estimate is not a provider-enforced
-dollar cap or an actual invoice.
-
-## Preparation and evidence
-
-Run the hosting checks from `hosting/` after the root install/runtime rebuild
-required by `hosting/AGENTS.md`. `startup-diagnostic.test.mjs` covers fixed offline
-execution, one-use admission, HTTP denial, structured private RPC, phase attribution,
-failed startup, bounded output/deadlines and cleanup/recovery. Its workerd fixture
-has no real Container; it proves fail-closed behavior, not provider availability.
-
-Prepare with pinned Wrangler, using an absolute output directory inside ignored
-root `.cache/`:
-
-```powershell
-fnm exec --using 22.23.3 npm.cmd exec --yes [email protected] -- wrangler deploy --config hosting/probe/startup.wrangler.jsonc --dry-run --outdir <ABSOLUTE_IGNORED_DIRECTORY>
-```
-
-Before live execution, retain the exact commit, final bundle SHA-256, validated
-configuration, deployment/version/application/namespace IDs and start timestamp.
-Inspect the uploaded code and public URL flags. Invoke the fixed RPC once through
-a loopback-only local operator that rejects browser-origin requests. A second
-read returns the retained result; it must never cause another start. Stop after
-failure and inspect the phase trace before preparing another image or policy.
-
-After retaining the result, stop the local operator, delete only this diagnostic's
-application and Worker, and verify its instance and namespace absence. There is
-no custom registry image to delete for this control. A successful command proves
-basic managed-image execution only. It does not prove custom image execution,
-Kiln evaluation, hostile-source isolation or a launch-ready service.
-
-An expired `CLOUDFLARE_API_TOKEN` environment override was found during preparation.
-Removing that override in the command process allowed both CLIs to use the owner's
-valid saved OAuth sessions. Never print or copy credentials, clear saved profiles,
-or request another login merely because that override has expired.
-
-Sources: [native API](https://developers.cloudflare.com/containers/api/durable-object-container/),
-[managed image](https://developers.cloudflare.com/containers/guides/image-management/),
-[Wrangler configuration](https://developers.cloudflare.com/containers/reference/wrangler-configuration/),
-[pricing](https://developers.cloudflare.com/containers/platform/pricing/).
-
-## Completed private control
-
-On 6 October 2026 at 18:46:20 UTC, source `c6b119b4a6358d51c27406f6fb3e74cafd289782`
-passed the deployed managed-image control. The uploaded JavaScript SHA-256 was
-`ddcc444cf904223eb63f5f8d2a673422c35e1e34076ae4ea2a6d13c6b59b741e`; its bytes were
-read back and matched before invocation. Both public URL flags were disabled,
-the version advertised no URLs, and its only binding was its own job namespace.
-
-The command returned Node `v24.20.0` and managed-image identity `0:0`. Output
-completed after 470 ms and awaited destruction/inspection completed after 573 ms.
-These are one control's elapsed timings, not billed CPU measurements or Kiln
-performance. The instance API separately reported `stopped`, exit code zero.
-Replaying the fixed RPC returned the exact retained record without another start.
-
-The local operator initially rejected even an empty POST because workerd provided
-an empty body stream. This was a local guard failure before RPC, not a cloud job.
-The operator was corrected to reject any nonempty stream; its GET, Origin and body
-denial checks passed before the successful invocation.
-
-The local operator was stopped and the exact diagnostic application and Worker
-were removed. Follow-up reads confirmed application/namespace absence and a 404
-for the Worker. Receipts are retained in the diagnostic worktree under ignored
-`.cache/startup-managed-trial/`. No custom registry image was created.
-
-The exact source passes 3,290 engine tests (two platform skips), root typecheck
-and lint, 126 hosted tests, hosted typechecks/builds and redacted source/bundle
-secret scans. Linux and Windows hosted CI both pass in
-[run 37513405377](https://github.com/instruktlabs/kiln/actions/runs/37513405377).
-
-This establishes managed-image execution on the account through the documented
-configuration. The remaining custom-image and Kiln integration controls must be
-prepared separately; this does not qualify hostile user code, software rendering,
-authentication, production hosting or settled costs. No new support message was
-sent. The total is now three attempted jobs out of five, with two remaining.
diff --git a/hosting/probe/custom-startup-worker.ts b/hosting/probe/custom-startup-worker.ts
deleted file mode 100644
index 646131fd..00000000
--- a/hosting/probe/custom-startup-worker.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import { ManagedStartupDiagnostic } from './startup-diagnostic';
-
-interface Bindings {
- STARTUP_JOB: DurableObjectNamespace<KilnCustomStartupJob>;
-}
-
-export class KilnCustomStartupJob extends DurableObject {
- async runFixed() {
- return new ManagedStartupDiagnostic(this.ctx, 'configured').run();
- }
-
- async alarm() {
- await new ManagedStartupDiagnostic(this.ctx, 'configured').alarm();
- }
-}
-
-export class KilnCustomStartupControl extends WorkerEntrypoint<Bindings> {
- fetch() {
- return new Response('Not found', { status: 404 });
- }
-
- async runFixed() {
- return this.env.STARTUP_JOB.getByName('custom-runtime-2026-10-06').runFixed();
- }
-}
-
-export default {
- fetch() {
- return new Response('Not found', { status: 404 });
- },
-} satisfies ExportedHandler<Bindings>;
diff --git a/hosting/probe/custom-startup.wrangler.jsonc b/hosting/probe/custom-startup.wrangler.jsonc
deleted file mode 100644
index 750fab14..00000000
--- a/hosting/probe/custom-startup.wrangler.jsonc
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "name": "kiln-private-custom-startup",
- "main": "./custom-startup-worker.ts",
- "compatibility_date": "2026-10-06",
- "workers_dev": false,
- "preview_urls": false,
- "routes": [],
- "limits": { "cpu_ms": 30000, "subrequests": 50 },
- "observability": {
- "enabled": true,
- "logs": { "enabled": true, "invocation_logs": true }
- },
- "containers": [
- {
- "name": "kiln-private-custom-startup",
- "class_name": "KilnCustomStartupJob",
- "scheduling_policy": "durable_object",
- "images": {
- "control": {
- "image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-startup-control@sha256:a747ad80c8a161b650d79a6da9c422005b91148b18b8d2c669eb5a0b7c07e600"
- }
- },
- "observability": { "logs": { "enabled": false } }
- }
- ],
- "durable_objects": {
- "bindings": [
- { "name": "STARTUP_JOB", "class_name": "KilnCustomStartupJob" }
- ]
- },
- "exports": {
- "KilnCustomStartupControl": { "type": "worker" },
- "KilnCustomStartupJob": { "type": "durable-object", "storage": "sqlite" }
- }
-}
diff --git a/hosting/probe/fixtures.ts b/hosting/probe/fixtures.ts
deleted file mode 100644
index 83496e4e..00000000
--- a/hosting/probe/fixtures.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-// Fixed provider-qualification programs only. Never imported by production hosts.
-export const engineRequest = new TextEncoder().encode(
- JSON.stringify({
- version: 'kiln.evaluator.request.v2',
- requestId: 'image-fixture',
- operation: 'execute-export-glb',
- code: 'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}',
- options: {},
- limits: { maxGlbBytes: 2097152 },
- }),
-);
-
-export const glbDigest = 'f94d231ed3eb4843a03704872adc3f20b00c2ea24567cb5916407b40a2cf1d40';
-
-// The controller remains outside the VM. These deliberately bypass Node vm so
-// network/filesystem checks exercise the provider boundary, not the JS sandbox.
-const prefix = 'import fs from "node:fs";fs.readFileSync(0);';
-const finish = 'fs.writeSync(1,JSON.stringify({ok:true}));process.exit(0);';
-export const nativeFixtures: Record<string, string> = {
- network: `${prefix}
- const {connect}=await import('node:net');
- const {lookup}=await import('node:dns/promises');
- const targets=[['1.1.1.1',443],['169.254.169.254',80],['127.0.0.1',8000]];
- for(const [host,port] of targets){
- const connected=await new Promise(resolve=>{
- const socket=connect({host,port});
- const finish=value=>{socket.destroy();resolve(value);};
- socket.setTimeout(2000,()=>finish(false));
- socket.once('error',()=>finish(false));socket.once('connect',()=>finish(true));
- });
- if(connected)throw new Error('unexpected network access');
- }
- const resolved=await Promise.race([lookup('example.com').then(()=>true,()=>false),new Promise(resolve=>setTimeout(()=>resolve(false),2500))]);
- if(resolved)throw new Error('unexpected DNS resolution');
- ${finish}`,
- 'write-marker': `${prefix}
- if(fs.existsSync('/tmp/kiln-qualification-marker'))throw new Error('unexpected old file');
- fs.writeFileSync('/tmp/kiln-qualification-marker','qualification-only');
- const {spawn}=await import('node:child_process');
- const child=spawn(process.execPath,['-e','process.title="kiln-qualification-child";setInterval(()=>{},1000)'],{detached:true,stdio:'ignore',env:{},cwd:'/tmp'});
- child.unref();
- await new Promise(resolve=>setTimeout(resolve,100));
- if(!Number.isSafeInteger(child.pid))throw new Error('child did not start');
- process.kill(child.pid,0);
- ${finish}`,
- 'read-marker': `${prefix}
- if(fs.existsSync('/tmp/kiln-qualification-marker'))throw new Error('cross-job file');
- for(const pid of fs.readdirSync('/proc').filter(name=>/^\\d+$/.test(name)&&name!==String(process.pid))){
- let command='';try{command=fs.readFileSync('/proc/'+pid+'/cmdline','utf8');}catch{}
- if(command.includes('kiln-qualification-child'))throw new Error('cross-job child');
- }
- ${finish}`,
-};
diff --git a/hosting/probe/gateway-preflight.ts b/hosting/probe/gateway-preflight.ts
deleted file mode 100644
index 18a731f3..00000000
--- a/hosting/probe/gateway-preflight.ts
+++ /dev/null
@@ -1,280 +0,0 @@
-import type { KilnCompute, KilnComputeControl } from '../src/admission-worker';
-import { D1BrowserSessions } from '../src/browser-sessions';
-import { D1Connections } from '../src/connections';
-import { tenantForAccount } from '../src/tenant-identity';
-import { readBounded } from '../src/http';
-import { qualificationControl } from './qualification-rpc';
-import {
- assertQualification,
- privateJson,
- qualificationOrigin,
- syntheticAccount,
- type QualificationAccountsEnv,
-} from './qualification-accounts';
-
-export interface PreflightEnv extends QualificationAccountsEnv {
- TENANTS: DurableObjectNamespace;
- ARTIFACTS: R2Bucket;
- COMPUTE: Service<KilnCompute>;
- CONTROL: Service<KilnComputeControl>;
-}
-interface PreflightReceipt {
- state: 'running' | 'finished';
- passed: boolean;
- computePaused: boolean;
- results: { name: string; passed: boolean }[];
-}
-const check = (value: unknown) => {
- if (!value) throw new Error('PRIVATE_PREFLIGHT_CHECK');
-};
-const source = 'function build(){return createRoot("Private gateway fixture");}';
-const bytes = new TextEncoder().encode(source);
-const hex = (buffer: ArrayBuffer) =>
- Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, '0')).join('');
-async function discard(response: Response, expected: number) {
- const status = response.status;
- await response.body?.cancel();
- check(status === expected);
-}
-
-/** One-use, no-VM stage for the next private full-stack trial. Synthetic identity
- * creation and direct storage seeding are intentionally not evidence of live login
- * or engine save. Native admission stays paused throughout and after this stage.
- */
-export async function runGatewayPreflight(
- storage: DurableObjectStorage,
- env: PreflightEnv,
-): Promise<PreflightReceipt> {
- const record: PreflightReceipt = {
- state: 'running',
- passed: false,
- computePaused: false,
- results: [],
- };
- const claimed = await storage.transaction(async (tx) => {
- if (await tx.get('gateway-preflight')) return false;
- await tx.put('gateway-preflight', record);
- return true;
- });
- if (!claimed) return (await storage.get<PreflightReceipt>('gateway-preflight'))!;
- let touchedCompute = false;
- const step = async (name: string, action: () => Promise<void>) => {
- const result = { name, passed: false };
- record.results.push(result);
- try {
- await action();
- result.passed = true;
- } finally {
- await storage.put('gateway-preflight', record);
- }
- };
- const send = (path: string, init?: RequestInit) =>
- env.GATEWAY.fetch(new Request(`${qualificationOrigin}${path}`, init));
- try {
- assertQualification(env);
- await step('fresh-resources', async () => {
- const accounts = await env.ACCOUNTS.withSession('first-primary')
- .prepare('SELECT COUNT(*) AS n FROM kiln_accounts')
- .first<{ n: number }>();
- check(accounts?.n === 0);
- check((await env.OAUTH_KV.list({ limit: 1 })).keys.length === 0);
- check((await env.ARTIFACTS.list({ limit: 1 })).objects.length === 0);
- });
- await step('pause-native', async () => {
- touchedCompute = true;
- await qualificationControl(env.CONTROL.setPaused(true));
- const status = await qualificationControl<Awaited<ReturnType<KilnCompute['health']>>>(
- env.COMPUTE.health(),
- );
- check(status.paused && status.activeRequests === 0 && status.pendingCleanup === 0);
- record.computePaused = true;
- });
- await step('metadata', async () => {
- const metadata = await privateJson(await send('/.well-known/oauth-protected-resource/mcp'));
- check(metadata.resource === `${qualificationOrigin}/mcp`);
- });
- let alice!: Awaited<ReturnType<typeof syntheticAccount>>, bob!: typeof alice;
- await step('synthetic-accounts', async () => {
- alice = await syntheticAccount(env, 'alice');
- bob = await syntheticAccount(env, 'bob');
- check(alice.account.id !== bob.account.id);
- });
- await step('anonymous-denied', async () => {
- await discard(await send('/mcp'), 401);
- });
- const bearer = (account: typeof alice) => ({ authorization: `Bearer ${account.accessToken}` });
- const discover = (account: typeof alice) =>
- send('/mcp', {
- method: 'POST',
- headers: {
- ...bearer(account),
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- 'mcp-protocol-version': '2026-07-28',
- 'mcp-method': 'tools/list',
- },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method: 'tools/list',
- params: {
- _meta: {
- 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
- 'io.modelcontextprotocol/clientInfo': {
- name: 'kiln-private-preflight',
- version: '1',
- },
- 'io.modelcontextprotocol/clientCapabilities': {},
- },
- },
- }),
- });
- await step('edge-discovery', async () => {
- const response = await privateJson(await discover(alice));
- const result = response.result as { tools?: { name?: string }[] } | undefined;
- check(result?.tools?.some((tool) => tool.name === 'kiln_render'));
- });
- await step('oversized-denied', async () => {
- await discard(
- await send('/mcp', {
- method: 'POST',
- headers: { ...bearer(alice), 'content-type': 'application/json' },
- body: 'x'.repeat(1024 * 1024 + 1),
- }),
- 413,
- );
- // A normal authenticated request still works after early body rejection.
- await privateJson(await discover(alice));
- });
- let artifact = '',
- download = '';
- const tenant = env.TENANTS.getByName(
- await tenantForAccount(qualificationOrigin, alice.account.id),
- );
- await step('store-fixture', async () => {
- const files: Record<string, string> = {};
- // Fixed storage-routing fixtures, not an engine-created or validated asset.
- for (const [name, body, mime] of [
- ['source.kiln.js', bytes, 'application/javascript'],
- [
- 'asset.glb',
- new TextEncoder().encode('glTF-private-routing-fixture'),
- 'model/gltf-binary',
- ],
- [
- 'manifest.json',
- new TextEncoder().encode('{"fixture":"gateway-routing"}'),
- 'application/json',
- ],
- ] as const) {
- const uploaded = await privateJson(
- await tenant.fetch('https://tenant.internal/internal/artifacts', {
- method: 'POST',
- body,
- headers: {
- 'content-type': mime,
- 'content-length': String(body.byteLength),
- 'x-artifact-name': name,
- 'x-artifact-sha256': hex(await crypto.subtle.digest('SHA-256', body)),
- },
- }),
- 201,
- );
- check(typeof uploaded.id === 'string');
- files[name] = uploaded.id as string;
- }
- artifact = files['source.kiln.js']!;
- const selection = { collection: 'project', assetId: 'preflight-fixture', revisionId: 'v1' };
- await privateJson(
- await tenant.fetch('https://tenant.internal/internal/assets/commit', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ ...selection, mode: 'save', files }),
- }),
- 201,
- );
- const ticket = await privateJson(
- await tenant.fetch('https://tenant.internal/internal/downloads', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify(selection),
- }),
- 201,
- );
- check(typeof ticket.ticket === 'string' && /^[a-f0-9]{64}$/.test(ticket.ticket));
- download = `/downloads/${ticket.ticket}/source.kiln.js`;
- });
- const exactSource = async (response: Response) => {
- check(response.status === 200 && response.headers.get('cache-control') === 'no-store');
- check(new TextDecoder().decode(await readBounded(response.body, 1024)) === source);
- };
- await step('bearer-isolation', async () => {
- await exactSource(await send(`/mcp/artifacts/${artifact}`, { headers: bearer(alice) }));
- await discard(
- await send(`/mcp/artifacts/${artifact}`, {
- headers: { ...bearer(bob), 'x-kiln-tenant': alice.account.id },
- }),
- 404,
- );
- });
- await step('browser-isolation', async () => {
- await exactSource(await send(download, { headers: { cookie: alice.cookie } }));
- await discard(await send(download, { headers: { cookie: bob.cookie } }), 404);
- await discard(await send(download, { method: 'HEAD' }), 401);
- });
- await step('revoke-connection', async () => {
- const proof = await new D1BrowserSessions(env.ACCOUNTS, qualificationOrigin).read(
- new Request(`${qualificationOrigin}/account`, { headers: { cookie: alice.cookie } }),
- );
- const grant = await new D1Connections(env.ACCOUNTS).revoke(
- proof,
- alice.identity,
- alice.connectionId,
- );
- check(typeof grant === 'string');
- // Deliberately leave the helper token in KV: primary revocation must deny it.
- });
- await step('revoked-token-denied', async () => {
- await discard(await send(`/mcp/artifacts/${artifact}`, { headers: bearer(alice) }), 401);
- await discard(
- await send('/oauth/token', {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- grant_type: 'refresh_token',
- refresh_token: alice.refreshToken,
- client_id: alice.clientId,
- resource: `${qualificationOrigin}/mcp`,
- }),
- }),
- 400,
- );
- // Revoking one app does not sign the owner's browser out.
- await exactSource(await send(download, { headers: { cookie: alice.cookie } }));
- });
- await step('other-account-preserved', async () => {
- await privateJson(await discover(bob));
- await discard(await send(`/mcp/artifacts/${artifact}`, { headers: bearer(bob) }), 404);
- });
- record.passed = true;
- } catch {
- record.passed = false;
- } finally {
- if (touchedCompute) {
- try {
- await qualificationControl(env.CONTROL.setPaused(true));
- const status = await qualificationControl<Awaited<ReturnType<KilnCompute['health']>>>(
- env.COMPUTE.health(),
- );
- record.computePaused =
- status.paused && status.activeRequests === 0 && status.pendingCleanup === 0;
- } catch {
- record.computePaused = false;
- }
- record.passed &&= record.computePaused;
- }
- record.state = 'finished';
- await storage.put('gateway-preflight', record);
- }
- return record;
-}
diff --git a/hosting/probe/integrated-budget.ts b/hosting/probe/integrated-budget.ts
deleted file mode 100644
index 0ac1662e..00000000
--- a/hosting/probe/integrated-budget.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-export const integratedBudget = { coordinator: 9, evaluation: 4, render: 4 } as const;
-export type IntegratedKind = keyof typeof integratedBudget;
-interface BudgetRecord {
- state: 'open' | 'closed';
- claims: { kind: IntegratedKind; id: string }[];
-}
-/** Diagnostic-only ceiling. It cannot reset, refund a failed start or resume a prior batch. */
-export class IntegratedBudget {
- constructor(private readonly storage: DurableObjectStorage) {}
- open(): Promise<void> {
- return this.storage.transaction(async (tx) => {
- if (await tx.get('budget')) throw new Error('TRIAL_ALREADY_USED');
- await tx.put('budget', { state: 'open', claims: [] } satisfies BudgetRecord);
- });
- }
- claim(kind: IntegratedKind, id: string): Promise<void> {
- return this.storage.transaction(async (tx) => {
- const record = await tx.get<BudgetRecord>('budget');
- if (
- record?.state !== 'open' ||
- !Object.hasOwn(integratedBudget, kind) ||
- !/^[a-f0-9]{64}$/.test(id) ||
- record.claims.some((claim) => claim.kind === kind && claim.id === id) ||
- record.claims.filter((claim) => claim.kind === kind).length >= integratedBudget[kind]
- )
- throw new Error('TRIAL_BUDGET_DENIED');
- record.claims.push({ kind, id });
- await tx.put('budget', record);
- });
- }
- close(): Promise<void> {
- return this.storage.transaction(async (tx) => {
- const record = await tx.get<BudgetRecord>('budget');
- await tx.put('budget', { ...record, state: 'closed', claims: record?.claims ?? [] });
- });
- }
- status(): Promise<BudgetRecord | undefined> {
- return this.storage.get('budget');
- }
-}
diff --git a/hosting/probe/integrated-run.ts b/hosting/probe/integrated-run.ts
deleted file mode 100644
index e1767077..00000000
--- a/hosting/probe/integrated-run.ts
+++ /dev/null
@@ -1,252 +0,0 @@
-import { readBounded } from '../src/http';
-
-export const integratedSource = `function build(){const root=createRoot('Root');
-const albedo=proceduralTexture({schemaVersion:2,size:32,usage:'albedo',layers:[{op:'checker',colorA:0xcc2211,colorB:0x22bb33,squares:4}]});
-createPart('Textured',boxGeo(1,1,1),pbrMaterial({albedo,roughness:0.7,metalness:0.1}),{parent:root});
-createPart('Blue',sphereGeo(0.35),pbrMaterial({albedo:0x2233dd,roughness:0.25,metalness:0.4}),{parent:root,position:[0,0.2,0.85]});return root;}`;
-export const integratedCases = [
- 'render',
- 'save',
- 'restore',
- 'source',
- 'export',
- 'glb',
- 'manifest',
- 'other-source',
- 'other-glb',
- 'quota',
-] as const;
-type Case = (typeof integratedCases)[number];
-interface AdmissionStatus {
- paused: boolean;
- activeRequests: number;
- pendingCleanup: number;
- maxConcurrent: number;
-}
-interface Ports {
- open(): Promise<void>;
- close(): Promise<void>;
- pause(): Promise<void>;
- status(): Promise<AdmissionStatus>;
- dispatch(tenant: string, request: Request): Promise<Response>;
- retain(name: string, bytes: Uint8Array<ArrayBuffer>): Promise<void>;
-}
-interface Result {
- name: Case;
- passed: boolean;
- elapsedMs: number;
- status?: number;
- bytes?: number;
- sha256?: string;
- reason?: string;
- savedEngine?: string;
-}
-interface RunRecord {
- state: 'running' | 'finished';
- passed: boolean;
- results: Result[];
- cleanupConfirmed?: boolean;
-}
-function check(value: unknown): asserts value {
- if (!value) throw new Error('TRIAL_CHECK_FAILED');
-}
-function object(value: unknown): Record<string, unknown> {
- check(value !== null && typeof value === 'object' && !Array.isArray(value));
- return value as Record<string, unknown>;
-}
-function tool(result: Record<string, unknown>) {
- check(result.isError !== true && Array.isArray(result.content));
- const text = result.content.map(object).find((item) => item.type === 'text');
- check(typeof text?.text === 'string');
- return object(JSON.parse(text.text));
-}
-function fullMaterial(value: unknown) {
- const fidelity = object(value);
- check(fidelity.delivered === 'full-material' && fidelity.degraded === false);
-}
-const tenantA = 'a'.repeat(43),
- tenantB = 'b'.repeat(43);
-function request(id: number, method: string, params: Record<string, unknown>): Request {
- const headers = new Headers({
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- 'mcp-protocol-version': '2026-07-28',
- 'mcp-method': method,
- });
- const name = params.name ?? params.uri;
- if (typeof name === 'string') headers.set('mcp-name', name);
- return new Request('https://tenant.internal/mcp', {
- method: 'POST',
- headers,
- body: JSON.stringify({
- jsonrpc: '2.0',
- id,
- method,
- params: {
- ...params,
- _meta: {
- 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
- 'io.modelcontextprotocol/clientInfo': { name: 'kiln-private-integration', version: '1' },
- 'io.modelcontextprotocol/clientCapabilities': {},
- },
- },
- }),
- });
-}
-
-/** One fixed sequence, stopping at the first failure. Retries only read the durable record. */
-export async function runIntegratedOnce(
- storage: DurableObjectStorage,
- ports: Ports,
-): Promise<RunRecord> {
- const claimed = await storage.transaction(async (tx) => {
- if (await tx.get('run')) return false;
- await tx.put('run', { state: 'running', passed: false, results: [] } satisfies RunRecord);
- return true;
- });
- if (!claimed) return (await storage.get<RunRecord>('run'))!;
- const record: RunRecord = { state: 'running', passed: false, results: [] };
- let ref = '',
- assetId = '',
- revisionId = '',
- retained = 0;
- try {
- await ports.open();
- for (const [index, name] of integratedCases.entries()) {
- const start = Date.now();
- let result: Result = { name, passed: false, elapsedMs: 0 };
- try {
- let method = 'tools/call',
- params: Record<string, unknown>;
- const selector = { collection: 'project', assetId, revisionId };
- switch (name) {
- case 'render':
- params = {
- name: 'kiln_render',
- arguments: { code: integratedSource, capture: { preset: '1x1' } },
- };
- break;
- case 'save':
- params = {
- name: 'kiln_save',
- arguments: {
- programRef: ref,
- collection: 'project',
- name: 'Private integration fixture',
- },
- };
- break;
- case 'restore':
- params = { name: 'kiln_assets', arguments: { ...selector, action: 'restore' } };
- break;
- case 'export':
- params = { name: 'kiln_export', arguments: selector };
- break;
- case 'glb':
- case 'other-glb':
- case 'manifest':
- method = 'resources/read';
- params = {
- uri: `kiln://assets/project/${assetId}/${revisionId}/${name === 'manifest' ? 'manifest.json' : 'asset.glb'}`,
- };
- break;
- default:
- params = { name: 'kiln_source', arguments: { programRef: ref } };
- }
- const response = await ports.dispatch(
- name.startsWith('other-') ? tenantB : tenantA,
- request(index + 1, method, params),
- );
- const bytes = await readBounded(response.body, 8 * 1024 * 1024);
- retained += bytes.byteLength;
- check(retained <= 64 * 1024 * 1024);
- await ports.retain(name, bytes);
- const sha256 = Array.from(
- new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)),
- (byte) => byte.toString(16).padStart(2, '0'),
- ).join('');
- result = { ...result, status: response.status, bytes: bytes.byteLength, sha256 };
- if (name === 'quota') check(response.status === 429);
- else {
- check(response.status === 200);
- const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
- const rpc = object(JSON.parse(text));
- check(rpc.id === index + 1);
- if (name.startsWith('other-')) {
- check(!text.includes(integratedSource));
- check(rpc.error !== undefined || object(rpc.result).isError === true);
- check(rpc.result === undefined || !object(rpc.result).contents);
- } else {
- check(!rpc.error);
- const payload = object(rpc.result);
- if (method === 'tools/call') {
- const data = tool(payload);
- if (name === 'render') {
- check(data.ok === true && typeof data.programRef === 'string');
- ref = data.programRef;
- check(/^(?:p_|sha256:)[a-f0-9]{64}$/.test(ref));
- fullMaterial(data.viewFidelity);
- check((payload.content as unknown[]).some((item) => object(item).type === 'image'));
- } else if (name === 'save') {
- check(data.ok === true);
- const asset = object(data.asset);
- check(typeof asset.assetId === 'string' && typeof asset.revisionId === 'string');
- assetId = asset.assetId;
- revisionId = asset.revisionId;
- for (const id of [assetId, revisionId]) check(/^[a-z][a-z0-9_-]{0,79}$/.test(id));
- } else if (name === 'restore') check(data.programRef === ref);
- else if (name === 'source')
- check(data.code === integratedSource && data.nextOffset === null);
- else check(data.ok === true);
- } else {
- check(Array.isArray(payload.contents) && payload.contents.length === 1);
- const resource = object(payload.contents[0]);
- if (name === 'glb') {
- check(typeof resource.blob === 'string');
- check(atob(resource.blob).startsWith('glTF'));
- } else {
- check(typeof resource.text === 'string');
- const manifest = object(JSON.parse(resource.text));
- check(manifest.assetId === assetId && manifest.revisionId === revisionId);
- fullMaterial(object(manifest.preview).fidelity);
- const engine = object(manifest.build).engine;
- check(typeof engine === 'string');
- result.savedEngine = engine;
- }
- }
- }
- }
- const status = await ports.status();
- check(status.activeRequests === 0 && status.pendingCleanup === 0);
- result.passed = true;
- } catch {
- result.reason = 'TRIAL_CASE_FAILED';
- }
- result.elapsedMs = Date.now() - start;
- record.results.push(result);
- await storage.put('run', record);
- if (!result.passed) break;
- }
- } catch {
- /* Fail closed; retained cases explain how far the fixed sequence reached. */
- } finally {
- const cleanup = await Promise.allSettled([ports.close(), ports.pause()]);
- try {
- const status = await ports.status();
- record.cleanupConfirmed =
- cleanup.every((r) => r.status === 'fulfilled') &&
- status.paused &&
- status.activeRequests === 0 &&
- status.pendingCleanup === 0;
- } catch {
- record.cleanupConfirmed = false;
- }
- record.state = 'finished';
- record.passed =
- record.cleanupConfirmed === true &&
- record.results.length === integratedCases.length &&
- record.results.every((result) => result.passed);
- await storage.put('run', record);
- }
- return record;
-}
diff --git a/hosting/probe/integrated-worker.ts b/hosting/probe/integrated-worker.ts
deleted file mode 100644
index fd521d10..00000000
--- a/hosting/probe/integrated-worker.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import { KilnNativeRequest } from '../src/request-worker';
-import { KilnEvaluationJob } from '../src/evaluation-worker';
-import { KilnRenderJob } from '../src/render-worker';
-import type { KilnAdmission } from '../src/admission-worker';
-import { IntegratedBudget, type IntegratedKind } from './integrated-budget';
-import { runIntegratedOnce } from './integrated-run';
-
-export { KilnNativeStorage, KilnNativeEvaluation, KilnNativeRender } from '../src/request-worker';
-export { KilnTenant } from '../src/tenant';
-export { KilnAdmission } from '../src/admission-worker';
-
-interface BudgetBindings {
- BUDGET: DurableObjectNamespace<KilnIntegratedBudget>;
-}
-interface RunBindings extends BudgetBindings {
- RUN: DurableObjectNamespace<KilnIntegratedRun>;
- ADMISSION: DurableObjectNamespace<KilnAdmission>;
- ARTIFACTS: R2Bucket;
-}
-const budget = (env: unknown) => (env as BudgetBindings).BUDGET.getByName('integrated-v1');
-
-async function claimRequest(env: unknown, kind: IntegratedKind, id: string, request: Request) {
- try {
- await budget(env).claim(kind, id);
- } catch (error) {
- if (!request.bodyUsed) await request.body?.cancel().catch(() => {});
- throw error;
- }
-}
-
-/** Wrappers add only the diagnostic allowance; production run/fetch/cancel/alarm stay intact. */
-export class IntegratedRequestJob extends KilnNativeRequest {
- override async run(tenant: string, request: Request, deadline: number): Promise<Response> {
- await claimRequest(this.env, 'coordinator', this.ctx.id.toString(), request);
- return super.run(tenant, request, deadline);
- }
-}
-export class IntegratedEvaluationJob extends KilnEvaluationJob {
- override async fetch(request: Request): Promise<Response> {
- await claimRequest(this.env, 'evaluation', this.ctx.id.toString(), request);
- return super.fetch(request);
- }
-}
-export class IntegratedRenderJob extends KilnRenderJob {
- override async fetch(request: Request): Promise<Response> {
- await claimRequest(this.env, 'render', this.ctx.id.toString(), request);
- return super.fetch(request);
- }
-}
-export class KilnIntegratedBudget extends DurableObject {
- private readonly budget = new IntegratedBudget(this.ctx.storage);
- open() {
- return this.budget.open();
- }
- claim(kind: IntegratedKind, id: string) {
- return this.budget.claim(kind, id);
- }
- close() {
- return this.budget.close();
- }
- status() {
- return this.budget.status();
- }
-}
-export class KilnIntegratedRun extends DurableObject<RunBindings> {
- run() {
- const allowance = budget(this.env),
- admission = this.env.ADMISSION.getByName('global-v1');
- return runIntegratedOnce(this.ctx.storage, {
- open: () => allowance.open(),
- close: () => allowance.close(),
- pause: async () => {
- await admission.setPaused(true);
- },
- status: () => admission.status(),
- dispatch: (tenant, request) => admission.dispatch(tenant, request),
- retain: async (name, bytes) => {
- await this.env.ARTIFACTS.put(`probe-evidence/${name}.json`, bytes, {
- httpMetadata: { contentType: 'application/json' },
- });
- },
- });
- }
- async status() {
- return this.ctx.storage.get('run');
- }
-}
-export class KilnIntegratedControl extends WorkerEntrypoint<RunBindings> {
- fetch() {
- return new Response('Not found', { status: 404 });
- }
- runFixed() {
- return this.env.RUN.getByName('integrated-v1').run();
- }
- async stop() {
- await budget(this.env).close();
- await this.env.ADMISSION.getByName('global-v1').setPaused(true);
- return this.status();
- }
- async status() {
- return {
- run: await this.env.RUN.getByName('integrated-v1').status(),
- budget: await budget(this.env).status(),
- admission: await this.env.ADMISSION.getByName('global-v1').status(),
- };
- }
-}
-export default {
- fetch() {
- return new Response('Not found', { status: 404 });
- },
-} satisfies ExportedHandler;
diff --git a/hosting/probe/kiln-startup-worker.ts b/hosting/probe/kiln-startup-worker.ts
deleted file mode 100644
index 4c3b862e..00000000
--- a/hosting/probe/kiln-startup-worker.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import { ManagedStartupDiagnostic } from './startup-diagnostic';
-
-interface Bindings {
- STARTUP_JOB: DurableObjectNamespace<KilnImageStartupJob>;
-}
-
-export class KilnImageStartupJob extends DurableObject {
- async runFixed() {
- return new ManagedStartupDiagnostic(this.ctx, 'kiln').run();
- }
-
- async alarm() {
- await new ManagedStartupDiagnostic(this.ctx, 'kiln').alarm();
- }
-}
-
-export class KilnImageStartupControl extends WorkerEntrypoint<Bindings> {
- fetch() {
- return new Response('Not found', { status: 404 });
- }
-
- async runFixed() {
- return this.env.STARTUP_JOB.getByName('kiln-runtime-2026-10-06').runFixed();
- }
-}
-
-export default {
- fetch() {
- return new Response('Not found', { status: 404 });
- },
-} satisfies ExportedHandler<Bindings>;
diff --git a/hosting/probe/kiln-startup.wrangler.jsonc b/hosting/probe/kiln-startup.wrangler.jsonc
deleted file mode 100644
index 35d26b02..00000000
--- a/hosting/probe/kiln-startup.wrangler.jsonc
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "name": "kiln-private-image-startup",
- "main": "./kiln-startup-worker.ts",
- "compatibility_date": "2026-10-06",
- "workers_dev": false,
- "preview_urls": false,
- "routes": [],
- "limits": { "cpu_ms": 30000, "subrequests": 50 },
- "observability": {
- "enabled": true,
- "logs": { "enabled": true, "invocation_logs": true }
- },
- "containers": [
- {
- "name": "kiln-private-image-startup",
- "class_name": "KilnImageStartupJob",
- "scheduling_policy": "durable_object",
- "images": {
- "control": {
- "image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a"
- }
- },
- "observability": { "logs": { "enabled": false } }
- }
- ],
- "durable_objects": {
- "bindings": [
- { "name": "STARTUP_JOB", "class_name": "KilnImageStartupJob" }
- ]
- },
- "exports": {
- "KilnImageStartupControl": { "type": "worker" },
- "KilnImageStartupJob": { "type": "durable-object", "storage": "sqlite" }
- }
-}
diff --git a/hosting/probe/lifecycle-allowance-worker.ts b/hosting/probe/lifecycle-allowance-worker.ts
deleted file mode 100644
index 1b30d25c..00000000
--- a/hosting/probe/lifecycle-allowance-worker.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { DurableObject } from 'cloudflare:workers';
-import { LifecycleBudget, type LifecycleKind } from './lifecycle-budget';
-
-export class KilnLifecycleBudget extends DurableObject {
- private readonly allowance = new LifecycleBudget(this.ctx.storage);
- open() {
- return this.allowance.open();
- }
- claim(kind: LifecycleKind, id: string) {
- return this.allowance.claim(kind, id);
- }
- close() {
- return this.allowance.close();
- }
- status() {
- return this.allowance.status();
- }
-}
-export default { fetch: () => new Response('Not found', { status: 404 }) };
diff --git a/hosting/probe/lifecycle-binding.ts b/hosting/probe/lifecycle-binding.ts
deleted file mode 100644
index ab8bbf71..00000000
--- a/hosting/probe/lifecycle-binding.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { KilnLifecycleBudget } from './lifecycle-allowance-worker';
-import type { LifecycleKind } from './lifecycle-budget';
-
-export interface LifecycleAllowanceEnv {
- BUDGET: DurableObjectNamespace<KilnLifecycleBudget>;
-}
-export const lifecycleAllowance = (env: unknown) =>
- (env as LifecycleAllowanceEnv).BUDGET.getByName('lifecycle-v1');
-
-export async function claimLifecycle(
- env: unknown,
- kind: LifecycleKind,
- id: string,
- request: Request,
-): Promise<void> {
- try {
- await lifecycleAllowance(env).claim(kind, id);
- } catch {
- if (!request.bodyUsed) await request.body?.cancel().catch(() => {});
- throw new Error('PRIVATE_LIFECYCLE_ALLOWANCE_DENIED');
- }
-}
diff --git a/hosting/probe/lifecycle-budget.ts b/hosting/probe/lifecycle-budget.ts
deleted file mode 100644
index ed9ad050..00000000
--- a/hosting/probe/lifecycle-budget.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-export const lifecycleBudget = { coordinator: 14, evaluation: 4, render: 4 } as const;
-export type LifecycleKind = keyof typeof lifecycleBudget;
-interface BudgetRecord {
- state: 'open' | 'closed';
- claims: { kind: LifecycleKind; id: string }[];
-}
-/** Private diagnostic ceiling. Failed starts consume their claim permanently. */
-export class LifecycleBudget {
- constructor(private readonly storage: DurableObjectStorage) {}
- open(): Promise<void> {
- return this.storage.transaction(async (tx) => {
- if (await tx.get('lifecycle-allowance-v1')) throw new Error('LIFECYCLE_ALREADY_USED');
- await tx.put('lifecycle-allowance-v1', { state: 'open', claims: [] } satisfies BudgetRecord);
- });
- }
- claim(kind: LifecycleKind, id: string): Promise<void> {
- return this.storage.transaction(async (tx) => {
- const record = await tx.get<BudgetRecord>('lifecycle-allowance-v1');
- if (
- record?.state !== 'open' ||
- !Object.hasOwn(lifecycleBudget, kind) ||
- !/^[a-f0-9]{64}(?![\s\S])/.test(id) ||
- record.claims.some((claim) => claim.kind === kind && claim.id === id) ||
- record.claims.filter((claim) => claim.kind === kind).length >= lifecycleBudget[kind]
- )
- throw new Error('LIFECYCLE_BUDGET_DENIED');
- record.claims.push({ kind, id });
- await tx.put('lifecycle-allowance-v1', record);
- });
- }
- close(): Promise<void> {
- return this.storage.transaction(async (tx) => {
- const record = await tx.get<BudgetRecord>('lifecycle-allowance-v1');
- await tx.put('lifecycle-allowance-v1', { state: 'closed', claims: record?.claims ?? [] });
- });
- }
- status(): Promise<BudgetRecord | undefined> {
- return this.storage.get('lifecycle-allowance-v1');
- }
-}
diff --git a/hosting/probe/lifecycle-build-boundary.mjs b/hosting/probe/lifecycle-build-boundary.mjs
deleted file mode 100644
index ca9ec40f..00000000
--- a/hosting/probe/lifecycle-build-boundary.mjs
+++ /dev/null
@@ -1,26 +0,0 @@
-import assert from 'node:assert/strict';
-import { assertProductionBoundary } from '../scripts/build-boundary.mjs';
-
-export function assertLifecycleBoundary(role, inputs) {
- const paths = inputs.map(path => path.replaceAll('\\', '/'));
- if (role === 'operator') {
- const allowed = new Set(['lifecycle-worker', 'lifecycle-budget', 'lifecycle-binding',
- 'lifecycle-run', 'gateway-preflight', 'qualification-accounts', 'qualification-rpc']);
- for (const path of paths) {
- assert(!/(?:^|\/)test\//.test(path));
- const probe = path.match(/(?:^|\/)probe\/([^/]+)\.ts$/);
- if (/(?:^|\/)probe\//.test(path)) assert(probe && allowed.has(probe[1]));
- }
- return;
- }
- const wrappers = ['request', 'evaluation', 'render'].includes(role);
- const expected = role === 'allowance' ? new Set(['lifecycle-allowance-worker', 'lifecycle-budget']) :
- wrappers ? new Set([`lifecycle-${role}-worker`, 'lifecycle-binding']) : new Set();
- const production = paths.filter(path => {
- const probe = path.match(/(?:^|\/)probe\/([^/]+)\.ts$/);
- if (!probe) return true;
- assert(expected.has(probe[1]));
- return false;
- });
- assertProductionBoundary(role === 'gateway' ? 'worker' : `${role}-worker`, production);
-}
diff --git a/hosting/probe/lifecycle-config.mjs b/hosting/probe/lifecycle-config.mjs
deleted file mode 100644
index 546d8a2b..00000000
--- a/hosting/probe/lifecycle-config.mjs
+++ /dev/null
@@ -1,70 +0,0 @@
-import assert from 'node:assert/strict';
-import { OutputWorkerSchema, convertToWranglerConfig } from '@cloudflare/config';
-import { deploymentConfig } from '../scripts/deployment-config.mjs';
-
-/** Offline diagnostic topology, derived from production with no public route. */
-export function lifecycleConfig(manifest) {
- const c = deploymentConfig(manifest);
- assert.equal(manifest.prefix, 'kiln-private-lifecycle-v1');
- assert.equal(manifest.origin, 'https://kiln-private-qualification.invalid');
- assert.deepEqual(manifest.compute, {
- maxConcurrent: 1, tenantPerMinute: 14, tenantPerDay: 14,
- globalPerDay: 14, globalPerMonth: 14, deadlineMs: 120000,
- });
- assert.deepEqual(manifest.storage, { maxBytes: 67108864, maxObjects: 256, maxGroups: 64 });
- assert.equal(manifest.requestLimits.edge.perMinute, 600);
- assert.equal(manifest.requestLimits.account.perMinute, 120);
- const operatorName = `${manifest.prefix}-operator`;
- const allowanceName = `${manifest.prefix}-allowance`;
- const budget = { type: 'durable-object', worker: allowanceName, exportName: 'KilnLifecycleBudget' };
- for (const role of ['request', 'evaluation', 'render']) {
- c.workers[role].env.BUDGET = { ...budget };
- c.entries[role] = `../probe/lifecycle-${role}-worker`;
- }
- const gateway = c.workers.gateway;
- // This fixed private test uses synthetic identities only, never live providers.
- for (const [name, binding] of Object.entries(gateway.env))
- if (binding.type === 'secret') delete gateway.env[name];
- gateway.triggers = [];
- c.workers.allowance = OutputWorkerSchema.parse({
- ...gateway, name: allowanceName, env: {},
- exports: { KilnLifecycleBudget: { type: 'durable-object', storage: 'sqlite' } },
- });
- c.workers.operator = OutputWorkerSchema.parse({
- ...gateway,
- name: operatorName,
- env: {
- PUBLIC_ORIGIN: { type: 'text', value: manifest.origin },
- QUALIFICATION_MODE: { type: 'text', value: 'isolated-synthetic-v1' },
- EXPECTED_IMAGE: { type: 'text', value: manifest.images.software.split('@')[1] },
- ACCOUNTS: { ...gateway.env.ACCOUNTS }, OAUTH_KV: { ...gateway.env.OAUTH_KV },
- TENANTS: { ...gateway.env.TENANTS }, ARTIFACTS: { ...c.workers.tenant.env.ARTIFACTS },
- GATEWAY: { type: 'worker', worker: gateway.name },
- COMPUTE: { ...gateway.env.NATIVE_COMPUTE },
- CONTROL: { type: 'worker', worker: c.workers.admission.name, exportName: 'KilnComputeControl' },
- BUDGET: budget,
- RUN: { type: 'durable-object', worker: operatorName, exportName: 'KilnLifecycleRun' },
- },
- exports: {
- KilnLifecycleRun: { type: 'durable-object', storage: 'sqlite' },
- KilnLifecycleControl: { type: 'worker' },
- },
- });
- c.entries.operator = '../probe/lifecycle-worker';
- c.entries.allowance = '../probe/lifecycle-allowance-worker';
- for (const [role, worker] of Object.entries(c.workers)) {
- c.workers[role] = OutputWorkerSchema.parse(worker);
- const config = convertToWranglerConfig({
- accountId: manifest.account,
- worker: { ...worker, entrypoint: `./.cloudflare/output/v0/workers/${role}/bundle/worker.mjs` },
- containers: c.containers[role] ? [c.containers[role]] : [],
- });
- for (const binding of config.durable_objects?.bindings ?? [])
- if (binding.script_name === worker.name) delete binding.script_name;
- config.routes = [];
- if (config.d1_databases?.length) config.d1_databases[0].migrations_dir = './migrations';
- c.wrangler[role] = config;
- }
- c.deployOrder = ['tenant', 'allowance', 'evaluation', 'render', 'request', 'admission', 'gateway', 'operator'];
- return c;
-}
diff --git a/hosting/probe/lifecycle-evaluation-worker.ts b/hosting/probe/lifecycle-evaluation-worker.ts
deleted file mode 100644
index 3420e2d3..00000000
--- a/hosting/probe/lifecycle-evaluation-worker.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { KilnEvaluationJob as EvaluationJob } from '../src/evaluation-worker';
-import { claimLifecycle } from './lifecycle-binding';
-export { default } from '../src/evaluation-worker';
-export class KilnEvaluationJob extends EvaluationJob {
- override async fetch(request: Request): Promise<Response> {
- await claimLifecycle(this.env, 'evaluation', this.ctx.id.toString(), request);
- return super.fetch(request);
- }
-}
diff --git a/hosting/probe/lifecycle-observer.ts b/hosting/probe/lifecycle-observer.ts
deleted file mode 100644
index 3d6c8886..00000000
--- a/hosting/probe/lifecycle-observer.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-type Action = 'runFixed' | 'status' | 'stop';
-interface Env {
- PROBE: Record<Action, () => Promise<unknown>>;
-}
-const dispose = (value: unknown) =>
- (value as { [Symbol.dispose]?: () => void } | null | undefined)?.[Symbol.dispose]?.();
-
-/** Local loopback observer only. Its sole remote binding is the fixed private
- * operator, which owns the durable one-use claim. Never deploy this facade. */
-export default {
- async fetch(request: Request, env: Env): Promise<Response> {
- const url = new URL(request.url);
- const action = new Map<string, Action>([
- ['/run-fixed', 'runFixed'],
- ['/status', 'status'],
- ['/stop', 'stop'],
- ]).get(url.pathname);
- // No request content becomes an RPC argument. Abort unread bodies rather
- // than consuming arbitrary local input or a cross-origin upload.
- void request.body?.cancel().catch(() => {});
- if (
- request.method !== 'POST' ||
- url.origin !== 'http://127.0.0.1:8798' ||
- url.search ||
- url.hash ||
- request.headers.has('Origin') ||
- request.headers.has('Sec-Fetch-Site') ||
- request.headers.get('X-Kiln-Operator') !== 'private-lifecycle-v1' ||
- !action
- )
- return new Response('Not found', { status: 404 });
- const headers = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' };
- let work: Promise<unknown> | undefined;
- let timer: ReturnType<typeof setTimeout> | undefined;
- let expired = false;
- try {
- work = env.PROBE[action]();
- const result = await Promise.race([
- work.then((value) => {
- if (expired) {
- dispose(value);
- throw new Error('PRIVATE_OBSERVATION_EXPIRED');
- }
- return value;
- }),
- new Promise<never>((_, reject) => {
- timer = setTimeout(
- () => {
- expired = true;
- reject(new Error('PRIVATE_OBSERVATION_EXPIRED'));
- },
- action === 'runFixed' ? 16 * 60 * 1000 : 10000,
- );
- }),
- ]);
- try {
- const bytes = JSON.stringify(structuredClone(result));
- if (new TextEncoder().encode(bytes).length > 128 * 1024)
- throw new Error('PRIVATE_OBSERVATION_TOO_LARGE');
- return new Response(bytes, { headers: { ...headers, 'content-type': 'application/json' } });
- } finally {
- dispose(result);
- }
- } catch {
- return Response.json(
- {
- observation: 'unavailable',
- next: 'Read /status for the same trial; do not start a replacement run.',
- },
- { status: 502, headers },
- );
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- dispose(work);
- }
- },
-};
diff --git a/hosting/probe/lifecycle-observer.wrangler.jsonc b/hosting/probe/lifecycle-observer.wrangler.jsonc
deleted file mode 100644
index 17d57c0c..00000000
--- a/hosting/probe/lifecycle-observer.wrangler.jsonc
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "name": "kiln-local-lifecycle-observer",
- "main": "./lifecycle-observer.ts",
- "compatibility_date": "2026-10-06",
- "workers_dev": false,
- "preview_urls": false,
- "routes": [],
- "observability": { "enabled": false },
- "dev": { "ip": "127.0.0.1", "port": 8798, "local_protocol": "http" },
- "services": [{
- "binding": "PROBE",
- "service": "kiln-private-lifecycle-v1-operator",
- "entrypoint": "KilnLifecycleControl",
- "remote": true
- }]
-}
diff --git a/hosting/probe/lifecycle-readback.mjs b/hosting/probe/lifecycle-readback.mjs
deleted file mode 100644
index f274088f..00000000
--- a/hosting/probe/lifecycle-readback.mjs
+++ /dev/null
@@ -1,313 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { lifecycleConfig } from './lifecycle-config.mjs';
-
-const sorted = (values) => [...values].sort();
-const one = (values, predicate) => {
- const found = values.filter(predicate);
- assert.equal(found.length, 1, 'Expected exactly one matching private resource');
- return found[0];
-};
-const identifier = (value) => assert(typeof value === 'string' && /^[a-f0-9-]{28,64}$/.test(value));
-const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
-
-function verifyDisabledLogging(worker, settings) {
- assert(settings && Object.hasOwn(settings, 'observability'), 'Raw script settings are required');
- assert.equal(settings.logpush, false);
- assert(settings.tail_consumers === null || Array.isArray(settings.tail_consumers));
- assert.deepEqual(settings.tail_consumers ?? [], []);
- assert.equal(worker.logpush, false);
- assert.deepEqual(worker.tail_consumers, []);
- const checkDisabled = (observability) => {
- assert.equal(observability.enabled, false);
- assert.equal(observability.logs.enabled, false);
- assert.equal(observability.traces.enabled, false);
- assert.deepEqual(observability.logs.destinations ?? [], []);
- assert.deepEqual(observability.traces.destinations ?? [], []);
- };
- checkDisabled(worker.observability);
- // The script-settings API returns null when observability is disabled. The
- // CLI normalizes that into inactive defaults (including persist:true). Require
- // the independent raw readback; missing evidence must never mean disabled.
- if (settings.observability === null) return;
- checkDisabled(settings.observability);
- for (const observability of [settings.observability, worker.observability]) {
- assert.equal(observability.redact_query_string, true);
- assert.equal(observability.logs.invocation_logs, false);
- assert.equal(observability.logs.persist, false);
- assert.equal(observability.traces.persist, false);
- }
-}
-
-function verifyBindings(expected, actual = [], namespaces) {
- assert.deepEqual(sorted(actual.map((b) => b.name)), sorted(Object.keys(expected)));
- for (const [name, binding] of Object.entries(expected)) {
- const observed = one(actual, (b) => b.name === name);
- let value;
- switch (binding.type) {
- case 'text':
- value = { name, type: 'plain_text', text: binding.value };
- break;
- case 'd1':
- value = { name, type: 'd1', id: binding.id };
- if (observed.database_id !== undefined) value.database_id = binding.id;
- break;
- case 'kv':
- value = { name, type: 'kv_namespace', namespace_id: binding.id };
- break;
- case 'r2':
- value = { name, type: 'r2_bucket', bucket_name: binding.name };
- break;
- case 'rate-limit':
- value = {
- name,
- type: 'ratelimit',
- namespace_id: binding.namespace,
- simple: binding.simple,
- };
- break;
- case 'analytics-engine-dataset':
- value = { name, type: 'analytics_engine', dataset: binding.name };
- break;
- case 'worker':
- value = {
- name,
- type: 'service',
- service: binding.worker,
- ...(binding.exportName ? { entrypoint: binding.exportName } : {}),
- };
- if (observed.environment !== undefined) value.environment = 'production';
- break;
- case 'durable-object': {
- const namespace = one(
- namespaces,
- (n) => n.script === binding.worker && n.class === binding.exportName,
- );
- value = {
- name,
- type: 'durable_object_namespace',
- namespace_id: namespace.id,
- class_name: binding.exportName,
- };
- if (observed.script_name !== undefined) value.script_name = binding.worker;
- if (observed.environment !== undefined) value.environment = 'production';
- break;
- }
- default:
- assert.fail('Unsupported private binding');
- }
- assert.deepEqual(observed, value, 'Deployed private binding differs from candidate');
- }
-}
-
-/** Pure verification of CLI/API readback, not an API call or deployment. The
- * operator supplies complete, freshly collected pages and the frozen receipt. */
-export function verifyLifecycleDeployment(manifest, receipt, snapshot) {
- const c = lifecycleConfig(manifest);
- assert.equal(receipt.mode, 'private-lifecycle');
- assert.equal(receipt.sourceDirty, false);
- assert.match(receipt.sourceCommit, /^[a-f0-9]{40}$/);
- assert.equal(snapshot.account, manifest.account);
- assert.equal(snapshot.complete, true);
- assert.deepEqual(receipt.images, manifest.images);
- assert.deepEqual(receipt.deployOrder, c.deployOrder);
- assert.deepEqual(sorted(receipt.workers.map((w) => w.role)), sorted(c.deployOrder));
- assert.deepEqual(sorted(Object.keys(snapshot.workers)), sorted(c.deployOrder));
- assert.equal(snapshot.database.uuid, manifest.database.id);
- assert.equal(snapshot.database.name, manifest.database.name);
- assert.equal(snapshot.kv.id, manifest.oauthKv);
- assert.equal(snapshot.kv.title, `${manifest.prefix}-oauth`);
- assert.equal(snapshot.bucket.name, manifest.bucket);
- assert.equal(snapshot.managedDomain.enabled, false);
- assert.deepEqual(snapshot.customDomains.domains, []);
- assert.equal(receipt.migrations.length, 9);
- assert.deepEqual(sorted(snapshot.migrations), sorted(receipt.migrations.map((m) => m.name)));
- const namespaces = snapshot.namespaces.filter((n) => n.script.startsWith(`${manifest.prefix}-`));
- const expectedClasses = Object.values(c.workers).flatMap((w) =>
- Object.entries(w.exports)
- .filter(([, e]) => e.type === 'durable-object')
- .map(([name]) => `${w.name}:${name}`),
- );
- assert.deepEqual(
- sorted(namespaces.map((n) => `${n.script}:${n.class}`)),
- sorted(expectedClasses),
- );
- assert.equal(new Set(namespaces.map((n) => n.id)).size, namespaces.length);
- for (const namespace of namespaces) {
- identifier(namespace.id);
- assert.equal(namespace.use_sqlite, true);
- }
- const workers = [];
- const applications = [];
- for (const role of c.deployOrder) {
- const expected = c.workers[role],
- wrangler = c.wrangler[role];
- const { worker, version, deployments, routes, schedules, scriptSettings } = snapshot.workers[role];
- const prepared = one(receipt.workers, (w) => w.role === role);
- assert.equal(prepared.name, expected.name);
- identifier(worker.id);
- identifier(version.id);
- assert.equal(worker.name, expected.name);
- assert.equal(worker.subdomain.enabled, false);
- assert.equal(worker.subdomain.previews_enabled, false);
- verifyDisabledLogging(worker, scriptSettings);
- for (const key of ['domains', 'queues', 'dispatch_namespace_outbounds'])
- assert.deepEqual(worker.references[key], []);
- assert.deepEqual(routes, []);
- assert.deepEqual(schedules, []);
- assert.deepEqual(version.urls, []);
- assert.equal(version.compatibility_date, expected.compatibilityDate);
- assert.deepEqual(sorted(version.compatibility_flags), sorted(expected.compatibilityFlags));
- assert.deepEqual(version.limits, wrangler.limits);
- assert.deepEqual(version.exports ?? {}, expected.exports);
- assert.equal(version.main_module, 'worker.mjs');
- assert.equal(version.modules.length, 1);
- assert.equal(version.modules[0].name, 'worker.mjs');
- assert.equal(hash(Buffer.from(version.modules[0].content_base64, 'base64')), prepared.sha256);
- const deployment = deployments.deployments[0];
- identifier(deployment.id);
- assert.deepEqual(deployment.versions, [{ version_id: version.id, percentage: 100 }]);
- verifyBindings(expected.env, version.bindings, namespaces);
- if (c.containers[role]) {
- const container = c.containers[role];
- const className = Object.entries(expected.exports).find(
- ([, e]) => e.container === container.name,
- )[0];
- const namespace = one(namespaces, (n) => n.script === expected.name && n.class === className);
- const images = Object.fromEntries(
- Object.entries(container.images).map(([name, image]) => [name, image.reference]),
- );
- assert.deepEqual(version.containers, [
- { name: container.name, class_name: className, images },
- ]);
- const app = one(snapshot.applications, (a) => a.name === container.name);
- identifier(app.id);
- assert.equal(app.account_id, manifest.account);
- assert.equal(app.scheduling_policy, 'durable_object');
- assert.equal(app.durable_objects.namespace_id, namespace.id);
- assert.equal(app.configuration.wrangler_ssh.enabled, false);
- assert.equal(app.observability.logs.enabled, false);
- assert.equal(app.health.instances.active, 0);
- assert.equal(app.health.instances.starting, 0);
- applications.push({
- role,
- kind: role === 'request' ? 'coordinator' : role,
- id: app.id,
- name: app.name,
- className,
- namespaceId: namespace.id,
- images,
- });
- } else assert.deepEqual(version.containers ?? [], []);
- workers.push({
- role,
- name: worker.name,
- id: worker.id,
- version: version.id,
- deployment: deployment.id,
- sha256: prepared.sha256,
- });
- }
- assert.equal(new Set(workers.map((w) => w.id)).size, workers.length);
- assert.deepEqual(
- sorted(
- snapshot.applications
- .filter((a) => a.name.startsWith(`${manifest.prefix}-`))
- .map((a) => a.id),
- ),
- sorted(applications.map((a) => a.id)),
- );
- return {
- sourceCommit: receipt.sourceCommit,
- account: manifest.account,
- prefix: manifest.prefix,
- privateConfigurationVerified: true,
- workers,
- applications,
- namespaces,
- database: { id: manifest.database.id, name: manifest.database.name },
- kv: { id: manifest.oauthKv, title: snapshot.kv.title },
- bucket: manifest.bucket,
- metrics: {
- dataset: c.workers.gateway.env.OPERATIONS.name,
- retention: 'provider-managed three months',
- },
- };
-}
-
-/** Produces targets only. Re-read this exact deployment immediately before
- * executing, check the IDs again, retain evidence, and verify absence afterward.
- * This does not grant permission, perform deletion, or claim it succeeded. */
-export function planLifecycleCleanup(manifest, verified, status, instances) {
- const c = lifecycleConfig(manifest);
- assert.equal(verified.account, manifest.account);
- assert.equal(verified.prefix, manifest.prefix);
- assert.equal(verified.privateConfigurationVerified, true);
- assert.deepEqual(verified.database, { id: manifest.database.id, name: manifest.database.name });
- assert.deepEqual(verified.kv, { id: manifest.oauthKv, title: `${manifest.prefix}-oauth` });
- assert.equal(verified.bucket, manifest.bucket);
- assert.deepEqual(
- verified.workers.map((w) => w.role),
- c.deployOrder,
- );
- for (const w of verified.workers) {
- assert.equal(w.name, c.workers[w.role].name);
- identifier(w.id);
- }
- for (const a of verified.applications) {
- assert.equal(a.name, c.containers[a.role].name);
- identifier(a.id);
- assert.equal(a.kind, a.role === 'request' ? 'coordinator' : a.role);
- assert.deepEqual(
- a.images,
- Object.fromEntries(
- Object.entries(c.containers[a.role].images).map(([key, v]) => [key, v.reference]),
- ),
- );
- }
- assert.deepEqual(sorted(verified.applications.map((a) => a.role)), [
- 'evaluation',
- 'render',
- 'request',
- ]);
- assert.equal(status.operatorStopped, true);
- assert.equal(status.alarmAt, null);
- assert(status.record === null || ['finished', 'stopped'].includes(status.record.state));
- assert.equal(status.budget.state, 'closed');
- assert.equal(status.admission.paused, true);
- assert.equal(status.admission.activeRequests, 0);
- assert.equal(status.admission.pendingCleanup, 0);
- const claims = status.budget.claims;
- const limits = { coordinator: 14, evaluation: 4, render: 4 };
- assert(claims.length <= 22);
- assert.equal(new Set(claims.map((x) => `${x.kind}:${x.id}`)).size, claims.length);
- for (const claim of claims) {
- assert(Object.hasOwn(limits, claim.kind));
- assert.match(claim.id, /^[a-f0-9]{64}$/);
- }
- for (const [kind, limit] of Object.entries(limits))
- assert(claims.filter((c) => c.kind === kind).length <= limit);
- assert(instances.length <= claims.length);
- assert.equal(new Set(instances.map((i) => `${i.application_id}:${i.id}`)).size, instances.length);
- for (const instance of instances) {
- const app = one(verified.applications, (a) => a.id === instance.application_id);
- assert.equal(instance.status.state, 'stopped');
- assert(Object.values(app.images).includes(instance.image));
- assert(claims.some((c) => c.kind === app.kind && c.id === instance.id));
- }
- return {
- sourceCommit: verified.sourceCommit,
- account: manifest.account,
- workers: verified.workers.toReversed(),
- applications: verified.applications,
- namespaces: verified.namespaces,
- database: verified.database,
- kv: verified.kv,
- bucket: verified.bucket,
- registryImages: 'preserve',
- claims: claims.length,
- verifiedStoppedInstances: instances.length,
- metrics: { ...verified.metrics, deletionVerified: false },
- executed: false,
- };
-}
diff --git a/hosting/probe/lifecycle-render-worker.ts b/hosting/probe/lifecycle-render-worker.ts
deleted file mode 100644
index ba27601f..00000000
--- a/hosting/probe/lifecycle-render-worker.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { KilnRenderJob as RenderJob } from '../src/render-worker';
-import { claimLifecycle } from './lifecycle-binding';
-export { default } from '../src/render-worker';
-export class KilnRenderJob extends RenderJob {
- override async fetch(request: Request): Promise<Response> {
- await claimLifecycle(this.env, 'render', this.ctx.id.toString(), request);
- return super.fetch(request);
- }
-}
diff --git a/hosting/probe/lifecycle-request-worker.ts b/hosting/probe/lifecycle-request-worker.ts
deleted file mode 100644
index 655a6b33..00000000
--- a/hosting/probe/lifecycle-request-worker.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { KilnNativeRequest as NativeRequest } from '../src/request-worker';
-import { claimLifecycle } from './lifecycle-binding';
-export {
- default,
- KilnNativeStorage,
- KilnNativeEvaluation,
- KilnNativeRender,
-} from '../src/request-worker';
-export class KilnNativeRequest extends NativeRequest {
- override async run(tenant: string, request: Request, deadline: number): Promise<Response> {
- await claimLifecycle(this.env, 'coordinator', this.ctx.id.toString(), request);
- return super.run(tenant, request, deadline);
- }
-}
diff --git a/hosting/probe/lifecycle-run.ts b/hosting/probe/lifecycle-run.ts
deleted file mode 100644
index f5df038d..00000000
--- a/hosting/probe/lifecycle-run.ts
+++ /dev/null
@@ -1,521 +0,0 @@
-import { readBounded } from '../src/http';
-
-export { lifecycleBudget } from './lifecycle-budget';
-export const lifecycleCases = [
- 'material-create',
- 'material-get',
- 'render',
- 'save',
- 'restore',
- 'source',
- 'export',
- 'glb',
- 'manifest',
- 'source-download',
- 'glb-download',
- 'material-download',
- 'foreign-download',
- 'anonymous-download',
- 'foreign-source',
- 'foreign-material',
- 'drop-live-material',
- 'import',
- 'imported-material',
- 'rerender',
- 'quota',
-] as const;
-type Case = (typeof lifecycleCases)[number];
-type Account = 'owner' | 'other';
-interface Status {
- paused: boolean;
- activeRequests: number;
- pendingCleanup: number;
-}
-interface Ports {
- expectedImage: string;
- open(): Promise<void>;
- close(): Promise<void>;
- pause(): Promise<void>;
- status(): Promise<Status>;
- mcp(account: Account, request: Request): Promise<Response>;
- download(account: Account | 'anonymous', path: string, signal: AbortSignal): Promise<Response>;
- dropMaterial(materialId: string, revisionId: string): Promise<void>;
- retain(name: Case, bytes: Uint8Array<ArrayBuffer>): Promise<void>;
-}
-interface Result {
- name: Case;
- passed: boolean;
- elapsedMs: number;
- status?: number;
- bytes?: number;
- sha256?: string;
- savedEngine?: string;
-}
-interface Record {
- state: 'running' | 'finished';
- passed: boolean;
- admissionIdleAndPaused: boolean;
- results: Result[];
-}
-const origin = 'https://kiln-private-qualification.invalid';
-const check: (value: unknown) => asserts value = (value) => {
- if (!value) throw new Error('PRIVATE_LIFECYCLE_CHECK');
-};
-function object(value: unknown): { [key: string]: unknown } {
- check(value !== null && typeof value === 'object' && !Array.isArray(value));
- return value as { [key: string]: unknown };
-}
-function tool(value: unknown) {
- const result = object(value);
- check(result.isError !== true && Array.isArray(result.content));
- const text = result.content.map(object).find((item) => item.type === 'text');
- check(typeof text?.text === 'string');
- return object(JSON.parse(text.text));
-}
-function canonical(value: unknown): string {
- if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
- if (value && typeof value === 'object') {
- const item = object(value);
- return `{${Object.keys(item)
- .sort()
- .map((key) => `${JSON.stringify(key)}:${canonical(item[key])}`)
- .join(',')}}`;
- }
- return JSON.stringify(value);
-}
-function fullMaterial(value: unknown) {
- const fidelity = object(value);
- check(
- fidelity.delivered === 'full-material' &&
- fidelity.degraded === false &&
- fidelity.materialFaithful === true,
- );
-}
-function rejectPrivateData(value: unknown, source: string, material: string, depth = 0): void {
- check(depth < 32);
- if (typeof value === 'string') {
- check(!value.includes(source) && !value.includes(material));
- // MCP content may itself contain JSON. Inspect decoded strings as well as
- // ordinary object fields so escaping cannot hide a leaked source document.
- if (/^\s*[[{]/.test(value)) {
- let parsed: unknown;
- try {
- parsed = JSON.parse(value);
- } catch {
- return;
- }
- rejectPrivateData(parsed, source, material, depth + 1);
- }
- } else if (value && typeof value === 'object') {
- check(canonical(value) !== material);
- for (const child of Object.values(value)) rejectPrivateData(child, source, material, depth + 1);
- }
-}
-const hash = async (bytes: Uint8Array<ArrayBuffer>) =>
- Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (byte) =>
- byte.toString(16).padStart(2, '0'),
- ).join('');
-function downloadPath(url: unknown, filename: string): string {
- check(typeof url === 'string');
- const parsed = new URL(url);
- check(
- parsed.origin === origin &&
- !parsed.username &&
- !parsed.password &&
- !parsed.search &&
- !parsed.hash,
- );
- check(/^\/downloads\/[a-f0-9]{64}\/[a-z.]+$/.test(parsed.pathname));
- check(parsed.pathname.endsWith(`/${filename}`));
- return parsed.pathname;
-}
-function request(
- id: number,
- method: string,
- params: { [key: string]: unknown },
- signal: AbortSignal,
-) {
- const headers = new Headers({
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- 'mcp-protocol-version': '2026-07-28',
- 'mcp-method': method,
- });
- const name = params.name ?? params.uri;
- if (typeof name === 'string') headers.set('mcp-name', name);
- return new Request(`${origin}/mcp`, {
- method: 'POST',
- headers,
- signal,
- body: JSON.stringify({
- jsonrpc: '2.0',
- id,
- method,
- params: {
- ...params,
- _meta: {
- 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
- 'io.modelcontextprotocol/clientInfo': { name: 'kiln-private-lifecycle', version: '1' },
- 'io.modelcontextprotocol/clientCapabilities': {},
- },
- },
- }),
- });
-}
-async function bounded<T>(
- work: Promise<T>,
- milliseconds: number,
- abort?: AbortController,
-): Promise<T> {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- return await Promise.race([
- work,
- new Promise<never>((_, reject) => {
- timer = setTimeout(() => {
- abort?.abort();
- reject(new Error('PRIVATE_LIFECYCLE_DEADLINE'));
- }, milliseconds);
- }),
- ]);
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
-}
-const materialDraft = {
- materialId: 'qualification-stone',
- name: 'Private qualification stone',
- tileable: true,
- sources: [
- {
- id: 'authored',
- kind: 'procedural',
- provider: 'Kiln',
- creator: 'Fixture author',
- license: {
- spdx: 'CC0-1.0',
- url: 'https://creativecommons.org/publicdomain/zero/1.0/',
- attribution: '',
- },
- originalFiles: [],
- },
- ],
- maps: [
- {
- slot: 'baseColor',
- sourceId: 'authored',
- transforms: [],
- procedural: {
- schemaVersion: 2,
- size: 8,
- usage: 'albedo',
- layers: [
- { op: 'noise', colorA: 0x779944, colorB: 0xeeeecc, seed: 17, scale: 4, octaves: 2 },
- ],
- },
- },
- ],
-};
-
-/** Fixed native stage. The outer private driver owns synthetic credentials and
- * the durable VM allowance; neither can be selected by these request bodies.
- */
-export async function runLifecycleOnce(
- storage: DurableObjectStorage,
- ports: Ports,
-): Promise<Record> {
- const record: Record = {
- state: 'running',
- passed: false,
- admissionIdleAndPaused: false,
- results: [],
- };
- const claimed = await storage.transaction(async (tx) => {
- if (await tx.get('native-lifecycle')) return false;
- await tx.put('native-lifecycle', record);
- return true;
- });
- if (!claimed) return (await storage.get<Record>('native-lifecycle'))!;
- let opened = false,
- retained = 0,
- code = '',
- ref = '',
- assetId = '',
- revisionId = '',
- glbHash = '';
- let material: { [key: string]: unknown } = {},
- materialRevision = '';
- let downloads: { [key: string]: unknown } = {};
- try {
- check(/^sha256:[a-f0-9]{64}$/.test(ports.expectedImage));
- opened = true;
- await bounded(ports.open(), 10000);
- for (const [index, name] of lifecycleCases.entries()) {
- const started = Date.now();
- const result: Result = { name, passed: false, elapsedMs: 0 };
- const controller = new AbortController();
- try {
- const selection = { collection: 'project', assetId, revisionId };
- const materialDependencies = [
- {
- resourceId: 'qualification-stone',
- revisionId: materialRevision,
- sha256: materialRevision,
- },
- ];
- if (name === 'drop-live-material') {
- await bounded(ports.dropMaterial('qualification-stone', materialRevision), 10000);
- } else {
- let response: Response;
- let resource = false;
- let rpc = true;
- if (name.endsWith('-download')) {
- rpc = false;
- const file =
- name === 'glb-download'
- ? 'asset.glb'
- : name === 'material-download'
- ? 'materials.kiln.json'
- : 'source.kiln.js';
- const account =
- name === 'foreign-download'
- ? 'other'
- : name === 'anonymous-download'
- ? 'anonymous'
- : 'owner';
- response = await bounded(
- ports.download(account, downloadPath(downloads[file], file), controller.signal),
- 15000,
- controller,
- );
- } else {
- let method = 'tools/call';
- let params: { [key: string]: unknown };
- switch (name) {
- case 'material-create':
- params = {
- name: 'kiln_material_create_procedural',
- arguments: { draft: materialDraft },
- };
- break;
- case 'material-get':
- case 'foreign-material':
- case 'imported-material':
- params = {
- name: 'kiln_material_get',
- arguments: {
- materialId: 'qualification-stone',
- revisionId: materialRevision,
- },
- };
- break;
- case 'render':
- params = {
- name: 'kiln_render',
- arguments: { code, materialDependencies, capture: { preset: '1x1' } },
- };
- break;
- case 'rerender':
- params = {
- name: 'kiln_render',
- arguments: { programRef: ref, materialDependencies, capture: { preset: '1x1' } },
- };
- break;
- case 'save':
- params = {
- name: 'kiln_save',
- arguments: {
- programRef: ref,
- materialDependencies,
- collection: 'project',
- name: 'Private material qualification',
- },
- };
- break;
- case 'restore':
- params = { name: 'kiln_assets_restore', arguments: selection };
- break;
- case 'export':
- params = { name: 'kiln_export', arguments: selection };
- break;
- case 'import':
- params = {
- name: 'kiln_import',
- arguments: { ...selection, sourceCollection: 'project', collection: 'library' },
- };
- break;
- case 'glb':
- case 'manifest':
- method = 'resources/read';
- resource = true;
- params = {
- uri: `kiln://assets/project/${assetId}/${revisionId}/${name === 'glb' ? 'asset.glb' : 'manifest.json'}`,
- };
- break;
- default:
- params = { name: 'kiln_source', arguments: { programRef: ref } };
- }
- response = await bounded(
- ports.mcp(
- name.startsWith('foreign-') ? 'other' : 'owner',
- request(index + 1, method, params, controller.signal),
- ),
- 140000,
- controller,
- );
- }
- const bytes = await bounded(
- readBounded(response.body, 8 * 1024 * 1024, controller.signal),
- 10000,
- controller,
- );
- retained += bytes.byteLength;
- check(retained <= 64 * 1024 * 1024);
- result.status = response.status;
- result.bytes = bytes.byteLength;
- result.sha256 = await hash(bytes);
- await bounded(ports.retain(name, bytes), 10000);
- if (name === 'quota') check(response.status === 429);
- else if (name === 'foreign-download' || name === 'anonymous-download') {
- check(response.status === (name === 'foreign-download' ? 404 : 401));
- check(result.sha256 !== glbHash);
- rejectPrivateData(new TextDecoder().decode(bytes), code, canonical(material));
- } else {
- check(response.status === 200);
- if (!rpc) {
- check(
- response.headers
- .get('cache-control')
- ?.split(',')
- .map((value) => value.trim())
- .includes('no-store'),
- );
- if (name === 'glb-download') check(result.sha256 === glbHash);
- else if (name === 'source-download') check(new TextDecoder().decode(bytes) === code);
- else {
- const closure = object(JSON.parse(new TextDecoder().decode(bytes)));
- check(Array.isArray(closure.records) && closure.records.length === 1);
- check(canonical(object(closure.records[0]).manifest) === canonical(material));
- }
- } else {
- const message = object(
- JSON.parse(
- new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes),
- ),
- );
- check(message.id === index + 1);
- if (name.startsWith('foreign-')) {
- rejectPrivateData(message, code, canonical(material));
- check(message.error !== undefined || object(message.result).isError === true);
- } else {
- check(message.error === undefined);
- const payload = object(message.result);
- if (resource) {
- check(Array.isArray(payload.contents) && payload.contents.length === 1);
- const item = object(payload.contents[0]);
- if (name === 'glb') {
- check(typeof item.blob === 'string');
- const glb = Uint8Array.from(atob(item.blob), (char) => char.charCodeAt(0));
- check(glb.byteLength >= 20);
- const header = new DataView(glb.buffer);
- check(
- header.getUint32(0, true) === 0x46546c67 &&
- header.getUint32(4, true) === 2 &&
- header.getUint32(8, true) === glb.byteLength,
- );
- glbHash = await hash(glb);
- } else {
- check(typeof item.text === 'string');
- const manifest = object(JSON.parse(item.text));
- check(manifest.assetId === assetId && manifest.revisionId === revisionId);
- fullMaterial(object(manifest.preview).fidelity);
- const engine = object(manifest.build).engine;
- check(engine === `cloudflare-container:${ports.expectedImage}`);
- result.savedEngine = engine;
- }
- } else {
- const value = tool(payload);
- if (name === 'material-create') {
- material = object(value.material);
- check(
- material.materialId === 'qualification-stone' &&
- typeof material.revisionId === 'string' &&
- /^sha256:[a-f0-9]{64}$/.test(material.revisionId),
- );
- materialRevision = material.revisionId;
- const spec = object(value.portableSpec);
- code = `async function build(){const r=createRoot('Root');const m=await compilePortableMaterialSpecV2(${JSON.stringify(spec)});createPart('Body',boxGeo(1,1,1),m,{parent:r});return r;}`;
- } else if (name === 'material-get' || name === 'imported-material')
- check(canonical(value.material) === canonical(material));
- else if (name === 'render' || name === 'rerender') {
- check(
- value.ok === true &&
- typeof value.programRef === 'string' &&
- /^(?:p_|sha256:)[a-f0-9]{64}$/.test(value.programRef),
- );
- if (name === 'rerender') check(value.programRef === ref);
- ref = value.programRef;
- fullMaterial(value.viewFidelity);
- check(
- (payload.content as unknown[]).some((item) => object(item).type === 'image'),
- );
- } else if (name === 'save') {
- check(value.ok === true);
- const asset = object(value.asset);
- check(
- typeof asset.assetId === 'string' && typeof asset.revisionId === 'string',
- );
- assetId = asset.assetId;
- revisionId = asset.revisionId;
- check([assetId, revisionId].every((id) => /^[a-z][a-z0-9_-]{0,79}$/.test(id)));
- downloads = object(value.downloadUrls);
- } else if (name === 'restore') check(value.programRef === ref);
- else if (name === 'source')
- check(value.code === code && value.nextOffset === null);
- else check(value.ok === true);
- }
- }
- }
- }
- }
- const status = await bounded(ports.status(), 10000);
- check(status.activeRequests === 0 && status.pendingCleanup === 0);
- result.passed = true;
- } catch {
- /* Fixed case label and outcome only; never retain exceptions. */
- } finally {
- controller.abort();
- }
- result.elapsedMs = Date.now() - started;
- record.results.push(result);
- await storage.put('native-lifecycle', record);
- if (!result.passed) break;
- }
- } catch {
- /* A partial or failed setup cannot authorize another run. */
- } finally {
- if (opened) {
- const closing = await Promise.allSettled([
- bounded(ports.close(), 10000),
- bounded(ports.pause(), 10000),
- ]);
- try {
- const status = await bounded(ports.status(), 10000);
- record.admissionIdleAndPaused =
- closing.every((result) => result.status === 'fulfilled') &&
- status.paused &&
- status.activeRequests === 0 &&
- status.pendingCleanup === 0;
- } catch {
- record.admissionIdleAndPaused = false;
- }
- }
- record.state = 'finished';
- record.passed =
- record.admissionIdleAndPaused &&
- record.results.length === lifecycleCases.length &&
- record.results.every((result) => result.passed);
- await storage.put('native-lifecycle', record);
- }
- return record;
-}
diff --git a/hosting/probe/lifecycle-worker.ts b/hosting/probe/lifecycle-worker.ts
deleted file mode 100644
index e64ecd03..00000000
--- a/hosting/probe/lifecycle-worker.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import { lifecycleAllowance, type LifecycleAllowanceEnv } from './lifecycle-binding';
-import { runGatewayPreflight, type PreflightEnv } from './gateway-preflight';
-import { runLifecycleOnce } from './lifecycle-run';
-import {
- assertQualification,
- privateJson,
- qualificationOrigin,
- syntheticAccount,
-} from './qualification-accounts';
-import { tenantForAccount } from '../src/tenant-identity';
-import type { KilnCompute } from '../src/admission-worker';
-import { qualificationControl as control } from './qualification-rpc';
-
-interface Env extends PreflightEnv, LifecycleAllowanceEnv {
- RUN: DurableObjectNamespace<KilnLifecycleRun>;
- EXPECTED_IMAGE: string;
-}
-interface Receipt {
- state: 'running' | 'finished' | 'stopped';
- passed: boolean;
- preflight: Awaited<ReturnType<typeof runGatewayPreflight>> | null;
- native: Awaited<ReturnType<typeof runLifecycleOnce>> | null;
-}
-type ComputeStatus = Awaited<ReturnType<KilnCompute['health']>>;
-export class KilnLifecycleRun extends DurableObject<Env> {
- private async checkRunning() {
- if (await this.ctx.storage.get('operator-stopped')) throw new Error('PRIVATE_OPERATOR_STOPPED');
- }
- private async seal() {
- const [allowance, paused] = await Promise.allSettled([
- control(lifecycleAllowance(this.env).close()),
- control<ComputeStatus>(this.env.CONTROL.setPaused(true)),
- ]);
- return (
- allowance.status === 'fulfilled' &&
- paused.status === 'fulfilled' &&
- paused.value.paused &&
- paused.value.activeRequests === 0 &&
- paused.value.pendingCleanup === 0
- );
- }
- async run(): Promise<Receipt> {
- assertQualification(this.env);
- const record: Receipt = { state: 'running', passed: false, preflight: null, native: null };
- const claimed = await this.ctx.storage.transaction(async (tx) => {
- if (await tx.get('combined-lifecycle')) return false;
- if (await tx.get('operator-stopped')) record.state = 'stopped';
- await tx.put('combined-lifecycle', record);
- return record.state === 'running';
- });
- if (!claimed) return (await this.ctx.storage.get<Receipt>('combined-lifecycle'))!;
- try {
- // Stop admission and consume the allowance on interruption, even if the
- // observer goes away. No alarm can reopen or retry this one-use sequence.
- await this.ctx.storage.setAlarm(Date.now() + 15 * 60 * 1000);
- await this.checkRunning();
- record.preflight = await runGatewayPreflight(this.ctx.storage, this.env);
- await this.ctx.storage.put('combined-lifecycle', record);
- if (!record.preflight.passed) throw new Error('PRIVATE_PREFLIGHT_FAILED');
- await this.checkRunning();
- // Fresh grants for the same two permanent fixture accounts. Alice's old
- // revoked connection stays revoked. Secrets remain in this invocation.
- const owner = await syntheticAccount(this.env, 'alice');
- await this.checkRunning();
- const other = await syntheticAccount(this.env, 'bob');
- await this.checkRunning();
- const tenant = this.env.TENANTS.getByName(
- await tenantForAccount(qualificationOrigin, owner.account.id),
- );
- const accounts = { owner, other };
- record.native = await runLifecycleOnce(this.ctx.storage, {
- expectedImage: this.env.EXPECTED_IMAGE,
- open: async () => {
- await this.checkRunning();
- await control(lifecycleAllowance(this.env).open());
- await this.checkRunning();
- await control(this.env.CONTROL.setPaused(false));
- await this.checkRunning();
- },
- close: () => control(lifecycleAllowance(this.env).close()),
- pause: async () => {
- await control(this.env.CONTROL.setPaused(true));
- },
- status: () => control(this.env.COMPUTE.health()),
- mcp: async (account, request) => {
- await this.checkRunning();
- const headers = new Headers(request.headers);
- headers.set('authorization', `Bearer ${accounts[account].accessToken}`);
- return this.env.GATEWAY.fetch(new Request(request, { headers }));
- },
- download: async (account, path, signal) => {
- await this.checkRunning();
- return this.env.GATEWAY.fetch(
- new Request(`${qualificationOrigin}${path}`, {
- // Anonymous GET would redirect to login; HEAD exercises denial.
- method: account === 'anonymous' ? 'HEAD' : 'GET',
- signal,
- headers: account === 'anonymous' ? {} : { cookie: accounts[account].cookie },
- }),
- );
- },
- dropMaterial: async (materialId, revisionId) => {
- await this.checkRunning();
- if (
- materialId !== 'qualification-stone' ||
- !/^sha256:[a-f0-9]{64}(?![\s\S])/.test(revisionId)
- )
- throw new Error('PRIVATE_MATERIAL_SELECTION');
- const group = await privateJson(
- await tenant.fetch(
- `https://tenant.internal/internal/materials/${materialId}/${revisionId.slice(7)}`,
- ),
- );
- if (typeof group.id !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(group.id))
- throw new Error('PRIVATE_MATERIAL_GROUP');
- await privateJson(
- await tenant.fetch(`https://tenant.internal/internal/groups/${group.id}`, {
- method: 'DELETE',
- }),
- );
- },
- retain: async (name, bytes) => {
- await this.env.ARTIFACTS.put(`probe-evidence/native-${name}.bin`, bytes, {
- httpMetadata: { contentType: 'application/octet-stream' },
- });
- },
- });
- record.passed = record.native.passed;
- } catch {
- record.passed = false;
- } finally {
- const sealed = await this.seal();
- await this.ctx.storage.transaction(async (tx) => {
- const stopped = Boolean(await tx.get('operator-stopped'));
- record.state = stopped ? 'stopped' : 'finished';
- record.passed &&= sealed && !stopped;
- await tx.put('combined-lifecycle', record);
- });
- // Recover promptly when either control acknowledgement remains unknown.
- if (sealed) await this.ctx.storage.deleteAlarm();
- else await this.ctx.storage.setAlarm(Date.now() + 60000);
- }
- return record;
- }
- async stop() {
- await this.ctx.storage.transaction(async (tx) => {
- await tx.put('operator-stopped', true);
- const record = await tx.get<Receipt>('combined-lifecycle');
- if (record?.state === 'running') {
- record.state = 'stopped';
- record.passed = false;
- await tx.put('combined-lifecycle', record);
- }
- });
- const sealed = await this.seal();
- if (!sealed) await this.ctx.storage.setAlarm(Date.now() + 60000);
- else await this.ctx.storage.deleteAlarm();
- return this.status();
- }
- async alarm() {
- await this.stop();
- }
- async status() {
- const [record, budget, admission] = await Promise.all([
- this.ctx.storage.get<Receipt>('combined-lifecycle'),
- control(lifecycleAllowance(this.env).status()),
- control(this.env.COMPUTE.health()),
- ]);
- return {
- record: record ?? null,
- budget: budget ?? null,
- admission,
- alarmAt: await this.ctx.storage.getAlarm(),
- operatorStopped: Boolean(await this.ctx.storage.get('operator-stopped')),
- };
- }
-}
-export class KilnLifecycleControl extends WorkerEntrypoint<Env> {
- fetch() {
- return new Response('Not found', { status: 404 });
- }
- async runFixed() {
- using result = await this.env.RUN.getByName('lifecycle-v1').run();
- return structuredClone(result);
- }
- async status() {
- using result = await this.env.RUN.getByName('lifecycle-v1').status();
- return structuredClone(result);
- }
- async stop() {
- using result = await this.env.RUN.getByName('lifecycle-v1').stop();
- return structuredClone(result);
- }
-}
-export default { fetch: () => new Response('Not found', { status: 404 }) };
diff --git a/hosting/probe/manifest-startup-worker.ts b/hosting/probe/manifest-startup-worker.ts
deleted file mode 100644
index bdee9dcd..00000000
--- a/hosting/probe/manifest-startup-worker.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import { ManagedStartupDiagnostic } from './startup-diagnostic';
-
-interface Bindings {
- STARTUP_JOB: DurableObjectNamespace<KilnManifestStartupJob>;
-}
-
-export class KilnManifestStartupJob extends DurableObject {
- async runFixed() {
- return new ManagedStartupDiagnostic(this.ctx, 'kiln-manifest').run();
- }
-
- async alarm() {
- await new ManagedStartupDiagnostic(this.ctx, 'kiln-manifest').alarm();
- }
-}
-
-export class KilnManifestStartupControl extends WorkerEntrypoint<Bindings> {
- fetch() {
- return new Response('Not found', { status: 404 });
- }
-
- async runFixed() {
- return this.env.STARTUP_JOB.getByName('kiln-manifest-2026-10-06').runFixed();
- }
-}
-
-export default {
- fetch() {
- return new Response('Not found', { status: 404 });
- },
-} satisfies ExportedHandler<Bindings>;
diff --git a/hosting/probe/manifest-startup.wrangler.jsonc b/hosting/probe/manifest-startup.wrangler.jsonc
deleted file mode 100644
index 774c6104..00000000
--- a/hosting/probe/manifest-startup.wrangler.jsonc
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "name": "kiln-private-manifest-startup",
- "main": "./manifest-startup-worker.ts",
- "compatibility_date": "2026-10-06",
- "workers_dev": false,
- "preview_urls": false,
- "routes": [],
- "limits": { "cpu_ms": 30000, "subrequests": 50 },
- "observability": {
- "enabled": true,
- "logs": { "enabled": true, "invocation_logs": true }
- },
- "containers": [
- {
- "name": "kiln-private-manifest-startup",
- "class_name": "KilnManifestStartupJob",
- "scheduling_policy": "durable_object",
- "images": {
- "control": {
- "image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8"
- }
- },
- "observability": { "logs": { "enabled": false } }
- }
- ],
- "durable_objects": {
- "bindings": [
- { "name": "STARTUP_JOB", "class_name": "KilnManifestStartupJob" }
- ]
- },
- "exports": {
- "KilnManifestStartupControl": { "type": "worker" },
- "KilnManifestStartupJob": { "type": "durable-object", "storage": "sqlite" }
- }
-}
diff --git a/hosting/probe/observe-container.ts b/hosting/probe/observe-container.ts
deleted file mode 100644
index 3a5b1714..00000000
--- a/hosting/probe/observe-container.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-// Operator-only diagnostics. Never return native exception text or process output.
-const operations = new Set([
- 'start',
- 'monitor',
- 'setInactivityTimeout',
- 'exec',
- 'inspect',
- 'destroy',
-]);
-
-export function observeContainer(actual: Container, script?: string) {
- let failedOperation: string | undefined;
- const container = new Proxy(actual, {
- get(target, key) {
- const value = Reflect.get(target, key);
- if (typeof value !== 'function') return value;
- if (typeof key !== 'string' || !operations.has(key)) return value.bind(target);
- return (...args: unknown[]) => {
- const fail = (error: unknown): never => {
- failedOperation ??= key;
- throw error;
- };
- try {
- if (key === 'exec' && script)
- args[0] = ['/usr/local/bin/node', '--input-type=module', '-e', script];
- const result = value.apply(target, args);
- return result instanceof Promise ? result.catch(fail) : result;
- } catch (error) {
- return fail(error);
- }
- };
- },
- });
- return { container, failure: () => failedOperation };
-}
diff --git a/hosting/probe/qualification-accounts.ts b/hosting/probe/qualification-accounts.ts
deleted file mode 100644
index 69dcf2d2..00000000
--- a/hosting/probe/qualification-accounts.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { OAuthAuthorizationServer } from '@cloudflare/workers-oauth-provider';
-import { D1BrowserSessions } from '../src/browser-sessions';
-import { D1Connections } from '../src/connections';
-import { readBounded, sha256 } from '../src/http';
-
-export const qualificationOrigin = 'https://kiln-private-qualification.invalid';
-export interface QualificationAccountsEnv {
- PUBLIC_ORIGIN: string;
- QUALIFICATION_MODE: string;
- ACCOUNTS: D1Database;
- OAUTH_KV: KVNamespace;
- GATEWAY: Fetcher;
-}
-export function assertQualification(env: QualificationAccountsEnv): void {
- if (
- env.PUBLIC_ORIGIN !== qualificationOrigin ||
- env.QUALIFICATION_MODE !== 'isolated-synthetic-v1'
- )
- throw new Error('PRIVATE_QUALIFICATION_ONLY');
-}
-export function qualificationOAuth(env: QualificationAccountsEnv) {
- assertQualification(env);
- return new OAuthAuthorizationServer<QualificationAccountsEnv>({
- issuer: qualificationOrigin,
- resources: [`${qualificationOrigin}/mcp`],
- authorizeEndpoint: `${qualificationOrigin}/authorize`,
- tokenEndpoint: `${qualificationOrigin}/oauth/token`,
- clientRegistrationEndpoint: `${qualificationOrigin}/register`,
- scopesSupported: ['kiln:use'],
- accessTokenTTL: 900,
- refreshTokenTTL: 30 * 86400,
- onError: () => {},
- }).getOAuthApi(env);
-}
-export async function privateJson(
- response: Response,
- status = 200,
-): Promise<Record<string, unknown>> {
- const bytes = await readBounded(response.body, 65536);
- if (response.status !== status) throw new Error('PRIVATE_QUALIFICATION_RESPONSE');
- const value: unknown = JSON.parse(new TextDecoder().decode(bytes));
- if (!value || typeof value !== 'object' || Array.isArray(value))
- throw new Error('PRIVATE_QUALIFICATION_RESPONSE');
- return value as Record<string, unknown>;
-}
-
-/** Synthetic private fixture only. This bypasses upstream consent, not token validation.
- * Credentials stay inside the private runner; never put this module in a gateway bundle.
- */
-export async function syntheticAccount(env: QualificationAccountsEnv, name: 'alice' | 'bob') {
- assertQualification(env);
- const identity = { issuer: 'https://github.com', subject: `kiln-private-qualification-${name}` };
- const sessions = new D1BrowserSessions(env.ACCOUNTS, qualificationOrigin);
- const browser = await sessions.issue(identity);
- const redirect = 'http://127.0.0.1:49317/callback';
- const client = await privateJson(
- await env.GATEWAY.fetch(
- new Request(`${qualificationOrigin}/register`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- client_name: 'Kiln private qualification',
- redirect_uris: [redirect],
- grant_types: ['authorization_code', 'refresh_token'],
- response_types: ['code'],
- token_endpoint_auth_method: 'none',
- }),
- }),
- ),
- 201,
- );
- if (typeof client.client_id !== 'string') throw new Error('PRIVATE_QUALIFICATION_CLIENT');
- const verifier = `${crypto.randomUUID().replaceAll('-', '')}${crypto.randomUUID().replaceAll('-', '')}`;
- const query = new URLSearchParams({
- client_id: client.client_id,
- response_type: 'code',
- redirect_uri: redirect,
- resource: `${qualificationOrigin}/mcp`,
- scope: 'kiln:use',
- state: crypto.randomUUID(),
- code_challenge: await sha256(verifier),
- code_challenge_method: 'S256',
- });
- const api = qualificationOAuth(env);
- const request = await api.parseAuthRequest(
- new Request(`${qualificationOrigin}/authorize?${query}`),
- );
- const connections = new D1Connections(env.ACCOUNTS);
- const props = await connections.create(
- browser.account,
- request,
- await api.describeConsent(request),
- );
- const { redirectTo } = await api.completeAuthorization({
- request,
- userId: browser.account.id,
- metadata: { connectionId: props.connectionId },
- scope: request.scope,
- props,
- revokeExistingGrants: false,
- });
- const code = new URL(redirectTo).searchParams.get('code');
- if (!code) throw new Error('PRIVATE_QUALIFICATION_CODE');
- const token = await privateJson(
- await env.GATEWAY.fetch(
- new Request(`${qualificationOrigin}/oauth/token`, {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- grant_type: 'authorization_code',
- code,
- code_verifier: verifier,
- client_id: client.client_id,
- redirect_uri: redirect,
- resource: `${qualificationOrigin}/mcp`,
- }),
- }),
- ),
- );
- if (typeof token.access_token !== 'string' || typeof token.refresh_token !== 'string')
- throw new Error('PRIVATE_QUALIFICATION_TOKEN');
- // Keep only the Cookie pair, never the Set-Cookie attributes.
- const cookie = browser.cookie.split(';')[0]!;
- return {
- identity,
- account: browser.account,
- connectionId: props.connectionId,
- cookie,
- accessToken: token.access_token,
- refreshToken: token.refresh_token,
- clientId: client.client_id,
- };
-}
diff --git a/hosting/probe/qualification-rpc.ts b/hosting/probe/qualification-rpc.ts
deleted file mode 100644
index e4e0053c..00000000
--- a/hosting/probe/qualification-rpc.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-const dispose = (value: unknown) =>
- (value as { [Symbol.dispose]?: () => void } | null | undefined)?.[Symbol.dispose]?.();
-
-/** Control RPCs return JSON values only. Detach them and release both the RPC
- * promise and result capabilities so an observer cannot pin a completed run. */
-export async function qualificationControl<T>(work: Promise<T>): Promise<T> {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- const result = await Promise.race([
- work,
- new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(new Error('PRIVATE_CONTROL_DEADLINE')), 10000);
- }),
- ]);
- try {
- return structuredClone(result);
- } finally {
- dispose(result);
- }
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- dispose(work);
- }
-}
diff --git a/hosting/probe/qualification.wrangler.jsonc b/hosting/probe/qualification.wrangler.jsonc
deleted file mode 100644
index fe0ef28d..00000000
--- a/hosting/probe/qualification.wrangler.jsonc
+++ /dev/null
@@ -1,52 +0,0 @@
-{
- "name": "kiln-private-manifest-qualification",
- "main": "./worker.ts",
- "compatibility_date": "2026-10-06",
- "compatibility_flags": [
- "enable_ctx_exports"
- ],
- "workers_dev": false,
- "preview_urls": false,
- "routes": [],
- "limits": {
- "cpu_ms": 30000,
- "subrequests": 50
- },
- "observability": {
- "enabled": true,
- "logs": {
- "enabled": true,
- "invocation_logs": true
- }
- },
- "containers": [
- {
- "name": "kiln-private-manifest-qualification-jobs",
- "class_name": "KilnProbeJob",
- "scheduling_policy": "durable_object",
- "images": {
- "kiln": {
- "image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8"
- }
- },
- "observability": {
- "logs": {
- "enabled": false
- }
- }
- }
- ],
- "exports": {
- "KilnProbeControl": {
- "type": "worker"
- },
- "KilnProbeRun": {
- "type": "durable-object",
- "storage": "sqlite"
- },
- "KilnProbeJob": {
- "type": "durable-object",
- "storage": "sqlite"
- }
- }
-}
diff --git a/hosting/probe/resilience-execution.ts b/hosting/probe/resilience-execution.ts
deleted file mode 100644
index 8c8fb93d..00000000
--- a/hosting/probe/resilience-execution.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { ContainerEvaluationJob, ContainerJobFailure } from '../src/container-job';
-import { engineRequest } from './fixtures';
-import { resilienceFixtures } from './resilience-fixtures';
-import { observeResilience } from './resilience-observation';
-import { checkResilienceResult } from './resilience-result';
-import { resilienceCases, type ResilienceCase, type ResilienceResult } from './resilience-run';
-
-export const resilienceImage =
- 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:84a0fa62bcffa010b9ac1c5f2f0e2cf9045a9cdb6407f621e8049e6a37f9de99';
-type Context = Pick<DurableObjectState, 'container' | 'storage'>;
-interface ProbeClaim {
- name: ResilienceCase;
- started: number;
-}
-
-/** Only fixed test programs and a single deliberate cleanup fault enter this class. */
-export class ResilienceExecution {
- constructor(private readonly context: Context) {}
-
- async run(name: ResilienceCase): Promise<ResilienceResult> {
- if (!resilienceCases.includes(name)) throw new Error('Unknown fixed case');
- const actual = this.context.container;
- if (!actual) return { name, passed: false, reason: 'CONTAINER_UNAVAILABLE' };
- if (actual.images.kiln !== resilienceImage)
- return { name, passed: false, reason: 'IMAGE_UNAVAILABLE' };
- const started = Date.now();
- const claimed = await this.context.storage.transaction(async (transaction) => {
- if (await transaction.get('probe')) return false;
- await transaction.put('probe', { name, started } satisfies ProbeClaim);
- return true;
- });
- if (!claimed) return (await this.read()) ?? { name, passed: false, reason: 'ALREADY_CLAIMED' };
- const abort = new AbortController();
- let cancelTimer: ReturnType<typeof setTimeout> | undefined;
- let readyAt: number | undefined;
- const observed = observeResilience(
- actual,
- resilienceFixtures[name] ?? '',
- () => {
- readyAt = Date.now();
- if (name === 'native-cancel' || name === 'alarm-recovery')
- cancelTimer = setTimeout(() => abort.abort(), 250);
- },
- name === 'alarm-recovery',
- );
- const deadlineMs = name === 'native-deadline' || name === 'alarm-recovery' ? 15_000 : 60_000;
- let output: Uint8Array | undefined;
- let reason: string | undefined;
- try {
- // The final engine check uses the real image entry without substitution.
- output = await new ContainerEvaluationJob({
- container: name === 'engine-after' ? actual : observed.container,
- storage: this.context.storage,
- }).run(name === 'engine-after' ? engineRequest : new TextEncoder().encode('{}'), {
- deadlineMs,
- maxResponseBytes:
- name === 'stdout-flood' ? 1024 : name === 'software-views' ? 512 * 1024 : 64 * 1024,
- signal: abort.signal,
- });
- } catch (error) {
- reason = error instanceof ContainerJobFailure ? error.code : 'CHECK_FAILED';
- } finally {
- if (cancelTimer !== undefined) clearTimeout(cancelTimer);
- }
- const job = await this.context.storage.get<{ state: string }>('job');
- // Production controller marks finished only after bounded destroy+inspection.
- const stopped = job?.state === 'finished' && !actual.running;
- const common = {
- image: resilienceImage,
- elapsedMs: Date.now() - started,
- ready: observed.ready(),
- readyAfterMs: readyAt === undefined ? undefined : readyAt - started,
- exitCode: observed.exitCode(),
- };
- let result: ResilienceResult;
- if (
- name === 'alarm-recovery' &&
- reason === 'CLEANUP_FAILED' &&
- actual.running &&
- observed.ready() &&
- job?.state === 'running'
- ) {
- result = {
- name,
- passed: false,
- stopped: false,
- pendingAlarm: true,
- reason: 'AWAITING_DURABLE_ALARM',
- ...common,
- };
- } else {
- result = {
- ...(await checkResilienceResult({
- name,
- stopped,
- ready: observed.ready(),
- reason,
- output,
- })),
- ...common,
- };
- // A startup timeout must not masquerade as sustained native-loop evidence.
- if (
- name === 'native-deadline' &&
- (readyAt === undefined || readyAt - started > deadlineMs - 1000)
- )
- result.passed = false;
- }
- await this.context.storage.put('probeResult', result);
- return result;
- }
-
- read() {
- return this.context.storage.get<ResilienceResult>('probeResult');
- }
-
- async alarm(): Promise<void> {
- await new ContainerEvaluationJob(this.context).alarm();
- const [claim, result, job] = await Promise.all([
- this.context.storage.get<ProbeClaim>('probe'),
- this.read(),
- this.context.storage.get<{ state: string; outcome: string }>('job'),
- ]);
- if (claim?.name !== 'alarm-recovery' || !result?.pendingAlarm || job?.state !== 'finished')
- return;
- const passed =
- job.outcome === 'DEADLINE_EXCEEDED' &&
- !this.context.container?.running &&
- result.ready === true;
- await this.context.storage.put('probeResult', {
- ...result,
- passed,
- stopped: !this.context.container?.running,
- pendingAlarm: false,
- reason: passed ? 'ALARM_RECOVERED' : 'RECOVERY_FAILED',
- elapsedMs: Date.now() - claim.started,
- } satisfies ResilienceResult);
- }
-
- /** Teardown after observation expires. It can never turn failed recovery into a pass. */
- async stopUnconfirmed(): Promise<ResilienceResult> {
- const prior = await this.read();
- if (!prior?.pendingAlarm)
- return prior ?? { name: 'alarm-recovery', passed: false, reason: 'NO_RECOVERY' };
- let timer: ReturnType<typeof setTimeout> | undefined;
- let stopped = false;
- try {
- const actual = this.context.container!;
- stopped = await Promise.race([
- (async () => {
- await actual.destroy();
- return (await actual.inspect()) === null && !actual.running;
- })(),
- new Promise<false>((resolve) => {
- timer = setTimeout(() => resolve(false), 5000);
- }),
- ]);
- } catch {
- /* Preserve failure; the operator must reconcile any live instance. */
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
- const result = {
- ...prior,
- passed: false,
- pendingAlarm: false,
- stopped,
- reason: 'ALARM_NOT_OBSERVED',
- };
- await this.context.storage.put('probeResult', result);
- return result;
- }
-}
diff --git a/hosting/probe/resilience-fixtures.ts b/hosting/probe/resilience-fixtures.ts
deleted file mode 100644
index 26a708f6..00000000
--- a/hosting/probe/resilience-fixtures.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { nativeFixtures } from './fixtures';
-
-const prefix = 'import fs from "node:fs";fs.readFileSync(0);';
-const ready = 'fs.writeSync(1,"KILN_PROBE_READY\\n");';
-const busy = `${prefix}
- const {spawn}=await import('node:child_process');
- const child=spawn(process.execPath,['-e','process.title="kiln-resilience-child";for(;;){}'],{detached:true,stdio:'ignore',env:{},cwd:'/tmp'});
- child.unref();await new Promise(resolve=>setTimeout(resolve,100));
- if(!Number.isSafeInteger(child.pid))throw new Error('Missing child');
- process.kill(child.pid,0);${ready}for(;;){}`;
-const renderPrefix = `${prefix}
- const {createEvaluatorRequestV2,evaluateEvaluatorRequestV2,decodeEvaluatorResultV2}=await import('/opt/kiln/node_modules/@instruktlabs/kiln/lib/evaluator/index.js');
- const {createRequire}=await import('node:module');
- const {PNG}=createRequire('/opt/kiln/node_modules/@instruktlabs/kiln/package.json')('pngjs');
- const finishJson=value=>new Promise((resolve,reject)=>process.stdout.write(JSON.stringify(value),error=>error?reject(error):resolve()));
- async function evaluate(code){
- const {json}=createEvaluatorRequestV2({requestId:'resilience-render',code,maxGlbBytes:2097152});
- const wire=await evaluateEvaluatorRequestV2(json,{}, {deadlineMs:60000,maxResponseBytes:8*1024*1024});
- const result=decodeEvaluatorResultV2(wire,2097152,'resilience-render');
- if(!result.ok)throw new Error('Evaluation failed');return result.render.glb;
- }`;
-
-/** Fixed native code only, never user input or an engine security-boundary claim. */
-export const resilienceFixtures: Record<string, string> = {
- ...nativeFixtures,
- 'native-deadline': busy,
- 'native-cancel': busy,
- 'alarm-recovery': busy,
- 'stdout-flood': `${prefix}${ready}await new Promise(r=>setTimeout(r,100));const chunk=Buffer.alloc(8192,120);for(;;)fs.writeSync(1,chunk);`,
- 'stderr-flood': `${prefix}${ready}await new Promise(r=>setTimeout(r,100));const chunk=Buffer.alloc(8192,120);for(;;)fs.writeSync(2,chunk);`,
- 'memory-limit': `${prefix}
- const {spawn}=await import('node:child_process');
- let counterSource='cgroup';
- const counter=()=>{
- if(counterSource==='cgroup'){
- try{const text=fs.readFileSync('/sys/fs/cgroup/memory.events','utf8');const m=text.match(/^oom_kill (\\d+)$/m);if(m)return Number(m[1]);}catch{}
- counterSource='vmstat';
- }
- const m=fs.readFileSync('/proc/vmstat','utf8').match(/^oom_kill (\\d+)$/m);if(!m)throw new Error('No OOM counter');return Number(m[1]);
- };
- const before=counter();
- const child=spawn(process.execPath,['-e', 'require("node:fs").writeFileSync("/proc/self/oom_score_adj","500");const allocated=[];for(let n=0;n<256;n++)allocated.push(Buffer.alloc(64*1024*1024,1));process.exit(2);'],{stdio:'ignore',env:{},cwd:'/tmp'});
- const ended=await new Promise((resolve,reject)=>{child.once('error',reject);child.once('exit',(code,signal)=>resolve({code,signal}));});
- const oomKills=counter()-before;
- if(oomKills<1||ended.signal!=='SIGKILL')throw new Error('Memory exhaustion not observed');
- fs.writeSync(1,JSON.stringify({ok:true,oomKills,signal:ended.signal,counterSource}));process.exit(0);`,
- 'cpu-preview': `${renderPrefix}
- const glb=await evaluate('function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}');
- const {renderGlbViewCell}=await import('/opt/kiln/node_modules/@instruktlabs/kiln/lib/views/index.js');
- const view=await renderGlbViewCell(glb,{name:'qualification',dir:[1,0.4,1]},{size:128});
- const decoded=PNG.sync.read(Buffer.from(view.png));
- if(decoded.width!==128||decoded.height!==128)throw new Error('Invalid dimensions');
- await finishJson({ok:true,views:[{backdrop:'neutral',index:0,pngBase64:Buffer.from(view.png).toString('base64')}]});process.exit(0);`,
- 'software-views': `${renderPrefix}
- process.env.VK_ICD_FILENAMES='/opt/kiln/lvp-icd.json';
- const glb=await evaluate("function build(){const root=createRoot('Root');const albedo=proceduralTexture({schemaVersion:2,size:32,usage:'albedo',layers:[{op:'checker',colorA:0xcc2211,colorB:0x22bb33,squares:4}]});createPart('Textured',boxGeo(1,1,1),pbrMaterial({albedo,roughness:0.7,metalness:0.1}),{parent:root});createPart('Blue',sphereGeo(0.35),pbrMaterial({albedo:0x2233dd,roughness:0.25,metalness:0.4}),{parent:root,position:[0,0.2,0.85]});return root;}");
- await import('/opt/kiln/node_modules/@instruktlabs/kiln/render-service/src/register-hooks.mjs');
- const {initRenderer,renderGlb}=await import('/opt/kiln/node_modules/@instruktlabs/kiln/render-service/src/renderer.mjs');
- const gpu=await import('/opt/kiln/node_modules/@instruktlabs/kiln/render-service/src/gpu.mjs');
- await initRenderer({allowSoftware:true});const device=await gpu.acquireGpu();
- if(device.software!==true)throw new Error('Expected software adapter');
- const views=[];
- for(const backdrop of ['neutral','dark','light']){
- const result=await renderGlb(glb,{size:128,viewDirs:[[1,0.4,1],[0,0,1]],backdrop});
- if(result.views.length!==2)throw new Error('Invalid views');
- for(const [index,png] of result.views.entries()){
- const decoded=PNG.sync.read(Buffer.from(png));if(decoded.width!==128||decoded.height!==128)throw new Error('Invalid dimensions');
- let red=0,green=0;
- for(let n=0;n<decoded.data.length;n+=4){const [r,g,b]=decoded.data.subarray(n,n+3);if(r>g+12&&r>b+12)red++;if(g>r+12&&g>b+12)green++;}
- if(red<21||green<21)throw new Error('Missing texture evidence');
- views.push({backdrop,index,red,green,pngBase64:Buffer.from(png).toString('base64')});
- }
- }
- gpu.markGpuShutdown();device.device.destroy();
- await finishJson({ok:true,software:true,views});process.exit(0);`,
-};
diff --git a/hosting/probe/resilience-observation.ts b/hosting/probe/resilience-observation.ts
deleted file mode 100644
index 6c83c622..00000000
--- a/hosting/probe/resilience-observation.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-const marker = new TextEncoder().encode('KILN_PROBE_READY\n');
-
-/** Fixed probe instrumentation only; never imported by a production Worker. */
-export function observeResilience(
- actual: Container,
- script: string,
- onReady: () => void,
- failFirstDestruction = false,
-) {
- let ready = false;
- let index = 0;
- let invalidPrefix = false;
- let exitCode: number | undefined;
- let injectFailure = failFirstDestruction;
- const container = new Proxy(actual, {
- get(target, key) {
- if (key === 'destroy')
- return async () => {
- if (injectFailure) {
- injectFailure = false;
- throw new Error('Fixed probe destruction fault');
- }
- return target.destroy();
- };
- if (key === 'exec')
- return async (_command: string[], options?: ContainerExecOptions) => {
- const process = await target.exec(
- ['/usr/local/bin/node', '--input-type=module', '-e', script],
- options,
- );
- const exited = process.exitCode.then((code) => {
- exitCode = code;
- return code;
- });
- void exited.catch(() => {});
- const stdout = process.stdout?.pipeThrough(
- new TransformStream<Uint8Array, Uint8Array>({
- transform(chunk, controller) {
- if (!ready && !invalidPrefix) {
- for (const byte of chunk) {
- if (byte !== marker[index++]) {
- invalidPrefix = true;
- break;
- }
- if (index === marker.length) {
- ready = true;
- onReady();
- break;
- }
- }
- }
- controller.enqueue(chunk);
- },
- }),
- );
- return new Proxy(process, {
- get(processTarget, property) {
- if (property === 'stdout') return stdout;
- if (property === 'exitCode') return exited;
- const value = Reflect.get(processTarget, property);
- return typeof value === 'function' ? value.bind(processTarget) : value;
- },
- });
- };
- const value = Reflect.get(target, key);
- return typeof value === 'function' ? value.bind(target) : value;
- },
- });
- return { container, ready: () => ready, exitCode: () => exitCode };
-}
diff --git a/hosting/probe/resilience-result.ts b/hosting/probe/resilience-result.ts
deleted file mode 100644
index 5aaef769..00000000
--- a/hosting/probe/resilience-result.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import { glbDigest } from './fixtures';
-import type { ResilienceCase, ResilienceResult } from './resilience-run';
-
-async function sha(bytes: Uint8Array<ArrayBuffer>) {
- return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (b) =>
- b.toString(16).padStart(2, '0'),
- ).join('');
-}
-function bytes(value: unknown, max: number) {
- if (
- typeof value !== 'string' ||
- value.length > Math.ceil(max / 3) * 4 ||
- !/^[A-Za-z0-9+/]*={0,2}$/.test(value)
- )
- throw new Error('Invalid bytes');
- const decoded = Uint8Array.from(atob(value), (c) => c.charCodeAt(0));
- if (!decoded.length || decoded.length > max) throw new Error('Invalid byte limit');
- return decoded;
-}
-function object(value: unknown): Record<string, unknown> {
- if (!value || typeof value !== 'object' || Array.isArray(value))
- throw new Error('Invalid result');
- return value as Record<string, unknown>;
-}
-function validPng(png: Uint8Array): boolean {
- const signature = [137, 80, 78, 71, 13, 10, 26, 10];
- if (png.length < 57 || signature.some((byte, index) => png[index] !== byte)) return false;
- const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
- let offset = 8;
- let imageData = false;
- while (offset + 12 <= png.length) {
- const length = view.getUint32(offset);
- const end = offset + 12 + length;
- if (end > png.length) return false;
- const kind = String.fromCharCode(...png.subarray(offset + 4, offset + 8));
- let crc = 0xffffffff;
- for (let i = offset + 4; i < end - 4; i++) {
- crc ^= png[i]!;
- for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
- }
- if ((crc ^ 0xffffffff) >>> 0 !== view.getUint32(end - 4)) return false;
- if (offset === 8) {
- if (
- kind !== 'IHDR' ||
- length !== 13 ||
- view.getUint32(16) !== 128 ||
- view.getUint32(20) !== 128
- )
- return false;
- // CPU previews are RGB; software material views may also carry alpha.
- if (
- png[24] !== 8 ||
- ![2, 6].includes(png[25]!) ||
- png[26] !== 0 ||
- png[27] !== 0 ||
- png[28] !== 0
- )
- return false;
- } else if (kind === 'IHDR') return false;
- if (kind === 'IDAT' && length > 0) imageData = true;
- if (kind === 'IEND') return length === 0 && imageData && end === png.length;
- offset = end;
- }
- return false;
-}
-const expectedFailures: Partial<Record<ResilienceCase, string>> = {
- 'native-deadline': 'DEADLINE_EXCEEDED',
- 'native-cancel': 'CANCELLED',
- 'stdout-flood': 'OUTPUT_LIMIT_EXCEEDED',
- 'stderr-flood': 'OUTPUT_LIMIT_EXCEEDED',
-};
-
-/** Strictly retain fixed proof fields; no arbitrary native diagnostic strings. */
-export async function checkResilienceResult(input: {
- name: ResilienceCase;
- stopped: boolean;
- ready?: boolean;
- reason?: string;
- output?: Uint8Array;
-}): Promise<ResilienceResult> {
- const result: ResilienceResult = { name: input.name, passed: false, stopped: input.stopped };
- if (!input.stopped) return { ...result, reason: 'CLEANUP_UNCONFIRMED' };
- const expected = expectedFailures[input.name];
- if (expected)
- return {
- ...result,
- passed: input.reason === expected && input.ready === true,
- reason: input.reason,
- };
- if (input.reason || !input.output || input.output.byteLength > 1024 * 1024) return result;
- try {
- const value = object(
- JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(input.output)),
- );
- if (value.ok !== true) return result;
- if (input.name === 'engine-after') {
- if (value.version !== 'kiln.evaluator.result.v2' || value.requestId !== 'image-fixture')
- return result;
- const glb = bytes(object(value.render).glbBase64, 2097152);
- const digest = await sha(glb);
- return { ...result, passed: glb.length === 1912 && digest === glbDigest, digest };
- }
- if (input.name === 'memory-limit') {
- if (
- !Number.isSafeInteger(value.oomKills) ||
- (value.oomKills as number) < 1 ||
- (value.oomKills as number) > 100 ||
- !['cgroup', 'vmstat'].includes(String(value.counterSource)) ||
- value.signal !== 'SIGKILL'
- )
- return result;
- return {
- ...result,
- passed: true,
- oomKills: value.oomKills as number,
- counterSource: value.counterSource as string,
- };
- }
- if (input.name === 'cpu-preview' || input.name === 'software-views') {
- const expectedCount = input.name === 'cpu-preview' ? 1 : 6;
- if (!Array.isArray(value.views) || value.views.length !== expectedCount) return result;
- const views: NonNullable<ResilienceResult['views']> = [];
- for (const [i, entry] of value.views.entries()) {
- const view = object(entry);
- const png = bytes(view.pngBase64, 128 * 1024);
- if (!validPng(png)) return result;
- const backdrop =
- input.name === 'cpu-preview'
- ? 'neutral'
- : ['neutral', 'dark', 'light'][Math.floor(i / 2)]!;
- const index = input.name === 'cpu-preview' ? 0 : i % 2;
- if (view.backdrop !== backdrop || view.index !== index) return result;
- const digest = await sha(png);
- if (input.name === 'cpu-preview') {
- if (digest !== '75be56a750d986a9d444328aa6ec3c5b8555ede64734b1f83ac6860b6939e527')
- return result;
- } else if (
- value.software !== true ||
- !Number.isSafeInteger(view.red) ||
- !Number.isSafeInteger(view.green) ||
- (view.red as number) < 21 ||
- (view.green as number) < 21 ||
- (view.red as number) > 16384 ||
- (view.green as number) > 16384
- )
- return result;
- views.push({
- backdrop,
- index,
- pngBase64: view.pngBase64 as string,
- sha256: digest,
- ...(input.name === 'software-views'
- ? { red: view.red as number, green: view.green as number }
- : {}),
- });
- }
- return { ...result, passed: true, views };
- }
- return { ...result, passed: ['network', 'write-marker', 'read-marker'].includes(input.name) };
- } catch {
- return result;
- }
-}
diff --git a/hosting/probe/resilience-run.ts b/hosting/probe/resilience-run.ts
deleted file mode 100644
index b31ce981..00000000
--- a/hosting/probe/resilience-run.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-export const resilienceCases = [
- 'cpu-preview',
- 'software-views',
- 'network',
- 'write-marker',
- 'read-marker',
- 'native-deadline',
- 'native-cancel',
- 'stdout-flood',
- 'stderr-flood',
- 'memory-limit',
- 'alarm-recovery',
- 'engine-after',
-] as const;
-export type ResilienceCase = (typeof resilienceCases)[number];
-export interface ResilienceResult {
- name: ResilienceCase;
- passed: boolean;
- stopped?: boolean;
- reason?: string;
- image?: string;
- elapsedMs?: number;
- ready?: boolean;
- readyAfterMs?: number;
- exitCode?: number;
- digest?: string;
- views?: {
- backdrop: string;
- index: number;
- pngBase64: string;
- sha256: string;
- red?: number;
- green?: number;
- }[];
- oomKills?: number;
- counterSource?: string;
- pendingAlarm?: boolean;
-}
-interface RunRecord {
- state: 'running' | 'finished';
- results: ResilienceResult[];
-}
-
-/** A new allowance, never a reset or continuation of earlier exhausted probes. */
-export async function runResilienceOnce(
- storage: DurableObjectStorage,
- execute: (name: ResilienceCase) => Promise<ResilienceResult>,
-): Promise<RunRecord> {
- const claimed = await storage.transaction(async (transaction) => {
- if (await transaction.get('run')) return false;
- await transaction.put('run', { state: 'running', results: [] } satisfies RunRecord);
- return true;
- });
- if (!claimed) return (await storage.get<RunRecord>('run'))!;
- const record: RunRecord = { state: 'running', results: [] };
- for (const name of resilienceCases) {
- let result: ResilienceResult;
- try {
- result = await execute(name);
- } catch {
- result = { name, passed: false, reason: 'PROBE_FAILED' };
- }
- record.results.push(result);
- await storage.put('run', record);
- if (!result.passed) break;
- }
- record.state = 'finished';
- await storage.put('run', record);
- return record;
-}
diff --git a/hosting/probe/resilience-worker.ts b/hosting/probe/resilience-worker.ts
deleted file mode 100644
index d248453e..00000000
--- a/hosting/probe/resilience-worker.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import { ResilienceExecution } from './resilience-execution';
-import { runResilienceOnce, type ResilienceCase } from './resilience-run';
-
-interface Bindings {
- KilnResilienceRun: DurableObjectNamespace<KilnResilienceRun>;
- KilnResilienceJob: DurableObjectNamespace<KilnResilienceJob>;
-}
-export class KilnResilienceJob extends DurableObject {
- runFixture(name: ResilienceCase) {
- return new ResilienceExecution(this.ctx).run(name);
- }
- readResult() {
- return new ResilienceExecution(this.ctx).read();
- }
- stopUnconfirmed() {
- return new ResilienceExecution(this.ctx).stopUnconfirmed();
- }
- alarm() {
- return new ResilienceExecution(this.ctx).alarm();
- }
-}
-export class KilnResilienceRun extends DurableObject {
- async run() {
- const bindings = this.ctx.exports as unknown as Bindings;
- return runResilienceOnce(this.ctx.storage, async (name) => {
- const job = bindings.KilnResilienceJob.getByName(`stable-resilience-v1/${name}`);
- let result = await job.runFixture(name);
- if (!result.pendingAlarm) return result;
- // A different DO observes the actual alarm callback. It never calls alarm()
- // itself and cannot restart a VM or submit new source while polling.
- const until = Date.now() + 45_000;
- while (Date.now() < until) {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- const next = await job.readResult();
- if (next) result = next;
- if (!result.pendingAlarm) return result;
- }
- return job.stopUnconfirmed();
- });
- }
-}
-export class KilnResilienceControl extends WorkerEntrypoint {
- fetch() {
- return new Response('Not found', { status: 404 });
- }
- runFixed() {
- const bindings = this.ctx.exports as unknown as Bindings;
- return bindings.KilnResilienceRun.getByName('stable-resilience-v1').run();
- }
-}
-export default {
- fetch() {
- return new Response('Not found', { status: 404 });
- },
-} satisfies ExportedHandler;
diff --git a/hosting/probe/resilience.wrangler.jsonc b/hosting/probe/resilience.wrangler.jsonc
deleted file mode 100644
index 74576540..00000000
--- a/hosting/probe/resilience.wrangler.jsonc
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "name": "kiln-private-stable-resilience",
- "main": "./resilience-worker.ts",
- "compatibility_date": "2026-10-06",
- "compatibility_flags": ["enable_ctx_exports"],
- "workers_dev": false,
- "preview_urls": false,
- "routes": [],
- "limits": {"cpu_ms": 30000, "subrequests": 50},
- "observability": {"enabled": true, "logs": {"enabled": true, "invocation_logs": true}},
- "containers": [{
- "name": "kiln-private-stable-resilience-jobs",
- "class_name": "KilnResilienceJob",
- "scheduling_policy": "durable_object",
- "images": {"kiln": {"image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:84a0fa62bcffa010b9ac1c5f2f0e2cf9045a9cdb6407f621e8049e6a37f9de99"}},
- "observability": {"logs": {"enabled": false}}
- }],
- "exports": {
- "KilnResilienceControl": {"type": "worker"},
- "KilnResilienceRun": {"type": "durable-object", "storage": "sqlite"},
- "KilnResilienceJob": {"type": "durable-object", "storage": "sqlite"}
- }
-}
diff --git a/hosting/probe/run-once.ts b/hosting/probe/run-once.ts
deleted file mode 100644
index 71b9b769..00000000
--- a/hosting/probe/run-once.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-export const probeCases = ['engine-a', 'network', 'write-marker', 'read-marker'] as const;
-export type ProbeCase = (typeof probeCases)[number];
-export interface ProbeResult {
- name: ProbeCase;
- passed: boolean;
- image?: string;
- stopped?: boolean;
- elapsedMs?: number;
- digest?: string;
- reason?: string;
- failedOperation?: string;
-}
-interface RunRecord {
- state: 'running' | 'finished';
- results: ProbeResult[];
-}
-
-export async function runProbeOnce(
- storage: DurableObjectStorage,
- execute: (name: ProbeCase) => Promise<ProbeResult>,
-): Promise<RunRecord> {
- const claimed = await storage.transaction(async (transaction) => {
- if (await transaction.get('run')) return false;
- await transaction.put('run', { state: 'running', results: [] } satisfies RunRecord);
- return true;
- });
- if (!claimed) return (await storage.get<RunRecord>('run'))!;
- const record: RunRecord = { state: 'running', results: [] };
- for (const name of probeCases) {
- let result: ProbeResult;
- try {
- result = await execute(name);
- } catch {
- result = { name, passed: false, reason: 'PROBE_FAILED' };
- }
- record.results.push(result);
- await storage.put('run', record);
- if (!result.passed) break;
- }
- record.state = 'finished';
- await storage.put('run', record);
- return record;
-}
diff --git a/hosting/probe/startup-diagnostic.ts b/hosting/probe/startup-diagnostic.ts
deleted file mode 100644
index 6040867d..00000000
--- a/hosting/probe/startup-diagnostic.ts
+++ /dev/null
@@ -1,327 +0,0 @@
-const IMAGE = 'cloudflare/debian-trixie';
-const KILN_IMAGE =
- 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a';
-const KILN_MANIFEST_IMAGE =
- 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8';
-const DEADLINE_MS = 60_000;
-const CLEANUP_MS = 5_000;
-const COMMAND = [
- '/usr/local/bin/node',
- '--eval',
- 'process.stdout.write(JSON.stringify({version:process.version,uid:process.getuid(),gid:process.getgid()}))',
-];
-
-type Operation =
- | 'start'
- | 'monitor'
- | 'inactivity'
- | 'exec'
- | 'inspect'
- | 'output'
- | 'destroy'
- | 'stopped';
-type Reason =
- | 'ISOLATION_UNAVAILABLE'
- | 'IMAGE_UNAVAILABLE'
- | 'PREEXISTING_CONTAINER'
- | 'START_FAILED'
- | 'MONITOR_FAILED'
- | 'CONTAINER_EXITED'
- | 'INACTIVITY_FAILED'
- | 'EXEC_FAILED'
- | 'INSPECT_FAILED'
- | 'OUTPUT_FAILED'
- | 'DEADLINE_EXCEEDED'
- | 'CLEANUP_FAILED';
-interface Phase {
- operation: Operation;
- event: 'entered' | 'completed' | 'failed';
- elapsedMs: number;
- duringCleanup: boolean;
-}
-interface StartupRecord {
- state: 'running' | 'finished';
- passed: boolean;
- claimedAt: number;
- deadlineAt: number;
- phases: Phase[];
- cleanupRequired: boolean;
- stopped: boolean;
- reason?: Reason;
- runtime?: { version: string; uid: number; gid: number };
-}
-class DiagnosticFailure extends Error {
- constructor(readonly reason: Reason) {
- super(reason);
- }
-}
-
-function mark(
- record: StartupRecord,
- operation: Operation,
- event: Phase['event'],
- duringCleanup: boolean,
-) {
- // Only fixed operation names and numeric timing leave this diagnostic.
- if (record.phases.length < 32)
- record.phases.push({
- operation,
- event,
- elapsedMs: Math.max(0, Date.now() - record.claimedAt),
- duringCleanup,
- });
-}
-
-async function boundedOutput(
- stream: ReadableStream<Uint8Array> | null | undefined,
- check: () => void,
-) {
- if (!stream) throw new DiagnosticFailure('OUTPUT_FAILED');
- const bytes = new Uint8Array(1024);
- let length = 0;
- const reader = stream.getReader();
- try {
- for (;;) {
- check();
- const { value, done } = await reader.read();
- check();
- if (done) return bytes.slice(0, length);
- if (!(value instanceof Uint8Array) || length + value.byteLength > bytes.length)
- throw new DiagnosticFailure('OUTPUT_FAILED');
- bytes.set(value, length);
- length += value.byteLength;
- }
- } catch (error) {
- void reader.cancel().catch(() => {});
- throw error;
- } finally {
- reader.releaseLock();
- }
-}
-
-async function cleanup(container: Container | undefined, record: StartupRecord): Promise<boolean> {
- if (!container) {
- record.stopped = true;
- return true;
- }
- let timer: ReturnType<typeof setTimeout> | undefined;
- const deadline = Date.now() + CLEANUP_MS;
- try {
- await Promise.race([
- (async () => {
- mark(record, 'destroy', 'entered', true);
- await container.destroy();
- if (Date.now() >= deadline) throw new DiagnosticFailure('CLEANUP_FAILED');
- mark(record, 'destroy', 'completed', true);
- mark(record, 'stopped', 'entered', true);
- const info = await container.inspect();
- if (Date.now() >= deadline || container.running || info !== null)
- throw new DiagnosticFailure('CLEANUP_FAILED');
- record.stopped = true;
- mark(record, 'stopped', 'completed', true);
- })(),
- new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(new DiagnosticFailure('CLEANUP_FAILED')), CLEANUP_MS);
- }),
- ]);
- return true;
- } catch {
- mark(record, 'stopped', 'failed', true);
- return false;
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
-}
-
-/** Fixed platform diagnostic only. No source, image, command or run ID is accepted. */
-export class ManagedStartupDiagnostic {
- constructor(
- private readonly context: Pick<DurableObjectState, 'container' | 'storage'>,
- private readonly imageSource: 'managed' | 'configured' | 'kiln' | 'kiln-manifest' = 'managed',
- ) {}
-
- async run(): Promise<StartupRecord> {
- const storage = this.context.storage;
- const record: StartupRecord = {
- state: 'running',
- passed: false,
- claimedAt: Date.now(),
- deadlineAt: Date.now() + DEADLINE_MS,
- phases: [],
- cleanupRequired: true,
- stopped: false,
- };
- const claimed = await storage.transaction(async (transaction) => {
- if (await transaction.get('startup')) return false;
- await transaction.put('startup', record);
- await transaction.setAlarm(record.deadlineAt);
- return true;
- });
- if (!claimed) return (await storage.get<StartupRecord>('startup'))!;
-
- const container = this.context.container;
- let closing = false;
- let reason: Reason | undefined;
- let rejectStopped: (error: DiagnosticFailure) => void = () => {};
- const stopped = new Promise<never>((_, reject) => {
- rejectStopped = reject;
- });
- void stopped.catch(() => {});
- const stop = (failure: Reason) => {
- if (closing || reason) return;
- reason = failure;
- rejectStopped(new DiagnosticFailure(failure));
- };
- const check = () => {
- if (closing) throw new DiagnosticFailure('EXEC_FAILED');
- if (Date.now() >= record.deadlineAt) stop('DEADLINE_EXCEEDED');
- if (reason) throw new DiagnosticFailure(reason);
- };
- const step = async <T>(
- operation: Operation,
- failure: Reason,
- action: () => T | Promise<T>,
- ): Promise<T> => {
- check();
- mark(record, operation, 'entered', false);
- try {
- const result = await action();
- check();
- mark(record, operation, 'completed', false);
- return result;
- } catch (error) {
- mark(record, operation, 'failed', closing);
- throw error instanceof DiagnosticFailure ? error : new DiagnosticFailure(failure);
- }
- };
- const timer = setTimeout(
- () => stop('DEADLINE_EXCEEDED'),
- Math.max(0, record.deadlineAt - Date.now()),
- );
- try {
- const execute = async () => {
- if (!container) throw new DiagnosticFailure('ISOLATION_UNAVAILABLE');
- const kilnImage =
- this.imageSource === 'kiln'
- ? KILN_IMAGE
- : this.imageSource === 'kiln-manifest'
- ? KILN_MANIFEST_IMAGE
- : undefined;
- const image = this.imageSource === 'managed' ? IMAGE : container.images?.control;
- if (
- this.imageSource !== 'managed' &&
- (typeof image !== 'string' ||
- !/^registry\.cloudflare\.com\/[a-f0-9]{32}\/[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/.test(
- image,
- ))
- )
- throw new DiagnosticFailure('IMAGE_UNAVAILABLE');
- if (kilnImage && image !== kilnImage) throw new DiagnosticFailure('IMAGE_UNAVAILABLE');
- if (container.running) throw new DiagnosticFailure('PREEXISTING_CONTAINER');
- await step('start', 'START_FAILED', () =>
- container.start({
- image,
- instance: 'standard-2',
- enableInternet: false,
- entrypoint: ['sleep', 'infinity'],
- env: {},
- }),
- );
- mark(record, 'monitor', 'entered', false);
- try {
- void container.monitor().then(
- () => {
- mark(record, 'monitor', 'completed', closing);
- stop('CONTAINER_EXITED');
- },
- () => {
- mark(record, 'monitor', 'failed', closing);
- stop('MONITOR_FAILED');
- },
- );
- } catch {
- mark(record, 'monitor', 'failed', false);
- throw new DiagnosticFailure('MONITOR_FAILED');
- }
- await step('inactivity', 'INACTIVITY_FAILED', () =>
- container.setInactivityTimeout(120_000),
- );
- const process = await step('exec', 'EXEC_FAILED', () =>
- container.exec(COMMAND, {
- stdout: 'pipe',
- stderr: 'pipe',
- ...(kilnImage ? { user: '1000:1000' } : {}),
- }),
- );
- await step('inspect', 'INSPECT_FAILED', async () => {
- const observed = await container.inspect();
- if (observed?.image !== image) throw new DiagnosticFailure('INSPECT_FAILED');
- });
- record.runtime = await step('output', 'OUTPUT_FAILED', async () => {
- const [stdout, stderr, exitCode] = await Promise.all([
- boundedOutput(process.stdout, check),
- boundedOutput(process.stderr, check),
- process.exitCode,
- ]);
- check();
- if (exitCode !== 0 || stderr.byteLength !== 0)
- throw new DiagnosticFailure('OUTPUT_FAILED');
- const value: unknown = JSON.parse(
- new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(stdout),
- );
- if (!value || typeof value !== 'object' || Array.isArray(value))
- throw new DiagnosticFailure('OUTPUT_FAILED');
- const data = value as Record<string, unknown>;
- if (
- Object.keys(data).sort().join(',') !== 'gid,uid,version' ||
- typeof data.version !== 'string' ||
- data.version !== (kilnImage ? 'v22.23.3' : 'v24.20.0') ||
- (kilnImage && (data.uid !== 1000 || data.gid !== 1000)) ||
- !Number.isSafeInteger(data.uid) ||
- !Number.isSafeInteger(data.gid) ||
- Number(data.uid) < 0 ||
- Number(data.gid) < 0 ||
- Number(data.uid) > 0xffff_ffff ||
- Number(data.gid) > 0xffff_ffff
- )
- throw new DiagnosticFailure('OUTPUT_FAILED');
- return { version: data.version, uid: Number(data.uid), gid: Number(data.gid) };
- });
- };
- await Promise.race([execute(), stopped]);
- } catch (error) {
- record.reason = error instanceof DiagnosticFailure ? error.reason : 'EXEC_FAILED';
- } finally {
- closing = true;
- clearTimeout(timer);
- record.cleanupRequired = !(await cleanup(container, record));
- if (record.cleanupRequired) record.reason ??= 'CLEANUP_FAILED';
- record.state = 'finished';
- record.passed = record.reason === undefined && record.stopped;
- await storage.put('startup', record);
- if (record.cleanupRequired) await storage.setAlarm(Date.now() + 30_000);
- else await storage.deleteAlarm();
- }
- return structuredClone(record);
- }
-
- async alarm(): Promise<void> {
- const storage = this.context.storage;
- const record = await storage.get<StartupRecord>('startup');
- if (!record?.cleanupRequired) {
- await storage.deleteAlarm();
- return;
- }
- if (record.state === 'running' && Date.now() < record.deadlineAt) {
- await storage.setAlarm(record.deadlineAt);
- return;
- }
- record.state = 'finished';
- record.passed = false;
- record.reason ??= 'DEADLINE_EXCEEDED';
- record.cleanupRequired = !(await cleanup(this.context.container, record));
- await storage.put('startup', record);
- if (record.cleanupRequired) await storage.setAlarm(Date.now() + 30_000);
- else await storage.deleteAlarm();
- }
-}
diff --git a/hosting/probe/startup-worker.ts b/hosting/probe/startup-worker.ts
deleted file mode 100644
index 737c405a..00000000
--- a/hosting/probe/startup-worker.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import { ManagedStartupDiagnostic } from './startup-diagnostic';
-
-interface Bindings {
- STARTUP_JOB: DurableObjectNamespace<KilnManagedStartupJob>;
-}
-
-export class KilnManagedStartupJob extends DurableObject {
- async runFixed() {
- return new ManagedStartupDiagnostic(this.ctx).run();
- }
-
- async alarm() {
- await new ManagedStartupDiagnostic(this.ctx).alarm();
- }
-}
-
-/** The authenticated operator can invoke only this fixed, retained diagnostic. */
-export class KilnStartupControl extends WorkerEntrypoint<Bindings> {
- fetch() {
- return new Response('Not found', { status: 404 });
- }
-
- async runFixed() {
- return this.env.STARTUP_JOB.getByName('managed-runtime-2026-10-06').runFixed();
- }
-}
-
-export default {
- fetch() {
- return new Response('Not found', { status: 404 });
- },
-} satisfies ExportedHandler<Bindings>;
diff --git a/hosting/probe/startup.wrangler.jsonc b/hosting/probe/startup.wrangler.jsonc
deleted file mode 100644
index 78c95b81..00000000
--- a/hosting/probe/startup.wrangler.jsonc
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "name": "kiln-private-startup-diagnostic",
- "main": "./startup-worker.ts",
- "compatibility_date": "2026-10-06",
- "workers_dev": false,
- "preview_urls": false,
- "routes": [],
- "limits": { "cpu_ms": 30000, "subrequests": 50 },
- "observability": {
- "enabled": true,
- "logs": { "enabled": true, "invocation_logs": true }
- },
- "containers": [
- {
- "name": "kiln-private-managed-startup",
- "class_name": "KilnManagedStartupJob",
- "scheduling_policy": "durable_object",
- "observability": { "logs": { "enabled": false } }
- }
- ],
- "durable_objects": {
- "bindings": [
- { "name": "STARTUP_JOB", "class_name": "KilnManagedStartupJob" }
- ]
- },
- "exports": {
- "KilnStartupControl": { "type": "worker" },
- "KilnManagedStartupJob": { "type": "durable-object", "storage": "sqlite" }
- }
-}
diff --git a/hosting/probe/worker.ts b/hosting/probe/worker.ts
deleted file mode 100644
index 3396ebc5..00000000
--- a/hosting/probe/worker.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import { ContainerEvaluationJob, ContainerJobFailure } from '../src/container-job';
-import { engineRequest, glbDigest, nativeFixtures } from './fixtures';
-import { observeContainer } from './observe-container';
-import { probeCases, runProbeOnce, type ProbeCase, type ProbeResult } from './run-once';
-
-interface ProbeBindings {
- KilnProbeRun: DurableObjectNamespace<KilnProbeRun>;
- KilnProbeJob: DurableObjectNamespace<KilnProbeJob>;
-}
-
-async function digest(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
- return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (byte) =>
- byte.toString(16).padStart(2, '0'),
- ).join('');
-}
-
-export class KilnProbeJob extends DurableObject {
- async runFixture(name: ProbeCase): Promise<ProbeResult> {
- if (!probeCases.includes(name)) throw new Error('Unknown fixed fixture');
- const actual = this.ctx.container;
- if (!actual) return { name, passed: false, reason: 'CONTAINER_UNAVAILABLE' };
- const image = actual.images.kiln;
- const started = Date.now();
- const script = nativeFixtures[name];
- // This substitution exists only in the private probe bundle. Production
- // ContainerEvaluationJob always invokes the immutable evaluate.mjs entry.
- const observed = observeContainer(actual, script);
- try {
- const output = await new ContainerEvaluationJob({
- container: observed.container,
- storage: this.ctx.storage,
- }).run(script ? new TextEncoder().encode('{}') : engineRequest, {
- deadlineMs: 60_000,
- maxResponseBytes: 1024 * 1024,
- });
- const stopped = !actual.running && (await actual.inspect()) === null;
- const value = JSON.parse(
- new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(output),
- );
- let passed = value.ok === true;
- let outputDigest: string | undefined;
- if (!script) {
- passed &&=
- value.version === 'kiln.evaluator.result.v2' && value.requestId === 'image-fixture';
- const binary = atob(value.render?.glbBase64 ?? '');
- const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
- outputDigest = await digest(bytes);
- passed &&= bytes.byteLength === 1912 && outputDigest === glbDigest;
- }
- return {
- name,
- passed: passed && stopped,
- stopped,
- image,
- elapsedMs: Date.now() - started,
- digest: outputDigest,
- };
- } catch (error) {
- return {
- name,
- passed: false,
- image,
- elapsedMs: Date.now() - started,
- stopped: !actual.running && (await actual.inspect()) === null,
- reason: error instanceof ContainerJobFailure ? error.code : 'CHECK_FAILED',
- failedOperation: observed.failure(),
- };
- }
- }
-
- async alarm() {
- await new ContainerEvaluationJob(this.ctx).alarm();
- }
-}
-
-export class KilnProbeRun extends DurableObject {
- async run() {
- const bindings = this.ctx.exports as unknown as ProbeBindings;
- return runProbeOnce(this.ctx.storage, (name) =>
- bindings.KilnProbeJob.getByName(`availability-rc1/${name}`).runFixture(name),
- );
- }
-}
-
-/** Operator-only service binding; never accepts source, commands or a new run ID. */
-export class KilnProbeControl extends WorkerEntrypoint {
- fetch() {
- return new Response('Not found', { status: 404 });
- }
-
- async runFixed() {
- const bindings = this.ctx.exports as unknown as ProbeBindings;
- return bindings.KilnProbeRun.getByName('availability-rc1').run();
- }
-}
-
-export default {
- fetch() {
- return new Response('Not found', { status: 404 });
- },
- async scheduled(_event: ScheduledController, _env: unknown, ctx: ExecutionContext) {
- const bindings = ctx.exports as unknown as ProbeBindings;
- const result = await bindings.KilnProbeRun.getByName('availability-rc1').run();
- // No source, credentials or arbitrary container output enter logs.
- console.log(JSON.stringify({ kind: 'kiln-private-availability-probe', ...result }));
- },
-} satisfies ExportedHandler;
diff --git a/hosting/scripts/build-boundary.mjs b/hosting/scripts/build-boundary.mjs
deleted file mode 100644
index 30567c62..00000000
--- a/hosting/scripts/build-boundary.mjs
+++ /dev/null
@@ -1,14 +0,0 @@
-export function assertProductionBoundary(entry, inputs) {
- const paths = inputs.map((name) => name.replaceAll('\\', '/'));
- if (paths.some((name) => /(?:^|\/)(?:test|probe)\//.test(name)))
- throw new Error('Production bundle includes test or probe helpers');
- if (
- entry !== 'worker' &&
- paths.some((name) =>
- /oauth|(?:^|\/)(?:auth|github|google|connections|account-(?:page|actions)|browser-(?:login|sessions|cookies))\.ts$/.test(
- name,
- ),
- )
- )
- throw new Error('Storage bundle includes authorization-server code');
-}
diff --git a/hosting/scripts/build-integrated-probe.mjs b/hosting/scripts/build-integrated-probe.mjs
deleted file mode 100644
index a72309cd..00000000
--- a/hosting/scripts/build-integrated-probe.mjs
+++ /dev/null
@@ -1,174 +0,0 @@
-// Local-only build. Upload, R2 provisioning and deployment require a reviewed allowance.
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { mkdir, readFile, writeFile } from 'node:fs/promises';
-import { dirname, resolve, sep } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { parseArgs } from 'node:util';
-import { build } from 'esbuild';
-import {
- OutputRootConfigSchema,
- OutputWorkerSchema,
- OutputContainerSchema,
- convertToWranglerConfig,
-} from '@cloudflare/config';
-
-const { values } = parseArgs({
- options: {
- account: { type: 'string' },
- output: { type: 'string' },
- 'cf-package': { type: 'string' },
- },
-});
-assert.match(values.account ?? '', /^[a-f0-9]{32}$/);
-assert(values.output && values['cf-package']);
-const cli = JSON.parse(await readFile(values['cf-package'], 'utf8'));
-assert.equal(cli.name, 'cf');
-assert.equal(cli.version, '1.0.0-beta.12');
-const root = fileURLToPath(new URL('../../', import.meta.url)),
- output = resolve(values.output);
-assert(output.startsWith(resolve(root, '.cache') + sep));
-const name = 'kiln-private-integrated-v1',
- bucket = 'kiln-private-integrated-v1-evidence';
-const coordinator = `registry.cloudflare.com/${values.account}/kiln-coordinator@sha256:029c4fba6f0521a5a18c9dde364d07b5ffc076fe4d988358868950de40134b66`;
-const software = `registry.cloudflare.com/${values.account}/kiln-software@sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24`;
-const compiled = await build({
- entryPoints: [fileURLToPath(new URL('../probe/integrated-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- target: 'es2022',
- external: ['cloudflare:workers'],
- metafile: true,
-});
-const inputs = Object.keys(compiled.metafile.inputs);
-assert(
- !inputs.some((path) =>
- /oauth|\/src\/(?:auth|github|google|browser-|account-)/.test(path.replaceAll('\\', '/')),
- ),
-);
-const doBinding = (exportName) => ({ type: 'durable-object', worker: name, exportName });
-const text = (value) => ({ type: 'text', value });
-const applications = [
- ['coordinator', 'IntegratedRequestJob', 'coordinator', coordinator],
- ['evaluation', 'IntegratedEvaluationJob', 'kiln', software],
- ['render', 'IntegratedRenderJob', 'renderer', software],
-];
-const exports = {
- KilnIntegratedControl: { type: 'worker' },
- KilnNativeStorage: { type: 'worker' },
- KilnNativeEvaluation: { type: 'worker' },
- KilnNativeRender: { type: 'worker' },
- KilnIntegratedRun: { type: 'durable-object', storage: 'sqlite' },
- KilnIntegratedBudget: { type: 'durable-object', storage: 'sqlite' },
- KilnAdmission: { type: 'durable-object', storage: 'sqlite' },
- KilnTenant: { type: 'durable-object', storage: 'sqlite' },
-};
-for (const [kind, exportName] of applications)
- exports[exportName] = { type: 'durable-object', storage: 'sqlite', container: `${name}-${kind}` };
-const worker = OutputWorkerSchema.parse({
- name,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['enable_ctx_exports', 'enable_request_signal'],
- workersDev: false,
- previewUrls: false,
- domains: [],
- triggers: [],
- limits: { cpuMs: 30000, subrequests: 500 },
- observability: {
- enabled: true,
- logs: { enabled: true, headSamplingRate: 1, invocationLogs: true, persist: true },
- },
- env: {
- BUDGET: doBinding('KilnIntegratedBudget'),
- RUN: doBinding('KilnIntegratedRun'),
- ADMISSION: doBinding('KilnAdmission'),
- TENANTS: doBinding('KilnTenant'),
- REQUESTS: doBinding('IntegratedRequestJob'),
- EVALUATIONS: doBinding('IntegratedEvaluationJob'),
- RENDERS: doBinding('IntegratedRenderJob'),
- ARTIFACTS: { type: 'r2', name: bucket },
- PUBLIC_ORIGIN: text('https://kiln.instruktlabs.com'),
- STORAGE_MAX_BYTES: text('67108864'),
- STORAGE_MAX_OBJECTS: text('256'),
- STORAGE_MAX_GROUPS: text('64'),
- COMPUTE_MAX_CONCURRENT: text('1'),
- COMPUTE_TENANT_PER_MINUTE: text('9'),
- COMPUTE_TENANT_PER_DAY: text('9'),
- COMPUTE_GLOBAL_PER_DAY: text('9'),
- COMPUTE_GLOBAL_PER_MONTH: text('9'),
- COMPUTE_DEADLINE_MS: text('120000'),
- },
- exports,
- manifest: {
- type: 'complete',
- mainModule: 'worker.mjs',
- modules: { 'worker.mjs': { type: 'esm' } },
- },
-});
-const files = {
- 'config.json': OutputRootConfigSchema.parse({
- accountId: values.account,
- buildContext: { isPreview: false },
- }),
- 'workers/default/worker.config.json': worker,
-};
-for (const [kind, , key, image] of applications)
- files[`containers/${name}-${kind}/container.config.json`] = OutputContainerSchema.parse({
- name: `${name}-${kind}`,
- schedulingPolicy: 'durable-object',
- ssh: { enabled: false },
- images: { [key]: { reference: image } },
- observability: { enabled: false, logs: { enabled: false } },
- });
-for (const [name, value] of Object.entries(files)) {
- const path = resolve(output, '.cloudflare/output/v0', name);
- await mkdir(dirname(path), { recursive: true });
- await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
-}
-const bytes = compiled.outputFiles[0].contents,
- path = resolve(output, '.cloudflare/output/v0/workers/default/bundle/worker.mjs');
-await mkdir(dirname(path), { recursive: true });
-await writeFile(path, bytes);
-// cf beta.12 serializes every named DO binding with script_name, even when the
-// target is this Worker. Container deployment rejects that external-binding form.
-// Keep the Build Output for inspection and emit an equivalent Wrangler config
-// referencing these exact bytes. The seven self-bindings are explicitly local.
-const wrangler = convertToWranglerConfig({
- accountId: values.account,
- worker: { ...worker, entrypoint: './.cloudflare/output/v0/workers/default/bundle/worker.mjs' },
- containers: applications.map(
- ([kind]) => files[`containers/${name}-${kind}/container.config.json`],
- ),
-});
-assert.equal(wrangler.durable_objects.bindings.length, 7);
-for (const binding of wrangler.durable_objects.bindings) {
- assert.equal(binding.script_name, worker.name);
- assert.equal(worker.exports[binding.class_name]?.type, 'durable-object');
- delete binding.script_name;
-}
-wrangler.routes = [];
-await writeFile(resolve(output, 'wrangler.json'), `${JSON.stringify(wrangler, null, 2)}\n`);
-const receipt = {
- worker: name,
- bucket,
- coordinator,
- software,
- workerSha256: createHash('sha256').update(bytes).digest('hex'),
- bytes: bytes.length,
- cli: cli.version,
- deploymentConfig: 'wrangler.json',
- deployWithoutBundling: true,
- inputs,
- maxMcpRequests: 9,
- quotaRejectionRequests: 1,
- maxVmStarts: { coordinator: 9, evaluation: 4, render: 4, total: 17 },
- deadlineMs: 120000,
- maxActiveParents: 1,
- maxActiveChildrenPerParent: 1,
- publicHttp: false,
- deployed: false,
-};
-await writeFile(resolve(output, 'build-receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);
-console.log(JSON.stringify(receipt));
diff --git a/hosting/scripts/build-provider-probe.mjs b/hosting/scripts/build-provider-probe.mjs
deleted file mode 100644
index 0256a0a1..00000000
--- a/hosting/scripts/build-provider-probe.mjs
+++ /dev/null
@@ -1,115 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { mkdir, readFile, writeFile } from 'node:fs/promises';
-import { dirname, resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { parseArgs } from 'node:util';
-import { build } from 'esbuild';
-import {
- OutputRootConfigSchema,
- OutputWorkerSchema,
- OutputContainerSchema,
-} from '@cloudflare/config';
-
-// Explicit local preparation only. cf deploy --prebuilt consumes this reviewed
-// output after approval; this script never uploads, provisions or invokes a VM.
-const { values } = parseArgs({
- options: {
- 'cf-package': { type: 'string' },
- account: { type: 'string' },
- image: { type: 'string' },
- output: { type: 'string' },
- },
-});
-assert.match(values.account ?? '', /^[a-f0-9]{32}$/);
-assert.match(
- values.image ?? '',
- /^registry\.cloudflare\.com\/[a-f0-9]{32}\/[a-z0-9-]+@sha256:[a-f0-9]{64}$/,
-);
-assert.ok(values.image.startsWith(`registry.cloudflare.com/${values.account}/`));
-assert.ok(values['cf-package'] && values.output);
-const cliPackage = resolve(values['cf-package']);
-const cli = JSON.parse(await readFile(cliPackage, 'utf8'));
-assert.equal(cli.name, 'cf');
-assert.equal(cli.version, '1.0.0-beta.12');
-const output = resolve(values.output);
-const workerName = 'kiln-private-evaluation-probe';
-const containerName = 'kiln-private-evaluation-probe-jobs';
-const bundle = await build({
- entryPoints: [fileURLToPath(new URL('../probe/worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- target: 'es2022',
- external: ['cloudflare:workers'],
- metafile: true,
-});
-const bytes = bundle.outputFiles[0].contents;
-const rootConfig = OutputRootConfigSchema.parse({
- accountId: values.account,
- buildContext: { isPreview: false },
-});
-const workerConfig = OutputWorkerSchema.parse({
- name: workerName,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['enable_ctx_exports'],
- workersDev: false,
- previewUrls: false,
- domains: [],
- limits: { cpuMs: 30000, subrequests: 50 },
- // The operator uses an authenticated remote service binding. No background
- // trigger can consume the fixed allowance before the operator is connected.
- triggers: [],
- observability: {
- enabled: true,
- logs: { enabled: true, headSamplingRate: 1, invocationLogs: true, persist: true },
- },
- exports: {
- KilnProbeControl: { type: 'worker' },
- KilnProbeRun: { type: 'durable-object', storage: 'sqlite' },
- KilnProbeJob: { type: 'durable-object', storage: 'sqlite', container: containerName },
- },
- manifest: {
- type: 'complete',
- mainModule: 'worker.mjs',
- modules: { 'worker.mjs': { type: 'esm' } },
- },
-});
-const containerConfig = OutputContainerSchema.parse({
- name: containerName,
- schedulingPolicy: 'durable-object',
- ssh: { enabled: false },
- images: { kiln: { reference: values.image } },
- observability: { enabled: false, logs: { enabled: false } },
-});
-const files = {
- 'config.json': rootConfig,
- 'workers/default/worker.config.json': workerConfig,
- [`containers/${containerName}/container.config.json`]: containerConfig,
-};
-for (const [name, content] of Object.entries(files)) {
- const path = resolve(output, '.cloudflare/output/v0', name);
- await mkdir(dirname(path), { recursive: true });
- await writeFile(path, `${JSON.stringify(content, null, 2)}\n`);
-}
-const modulePath = resolve(output, '.cloudflare/output/v0/workers/default/bundle/worker.mjs');
-await mkdir(dirname(modulePath), { recursive: true });
-await writeFile(modulePath, bytes);
-const receipt = {
- worker: workerName,
- image: values.image,
- workerSha256: createHash('sha256').update(bytes).digest('hex'),
- bytes: bytes.length,
- cli: cli.version,
- inputs: Object.keys(bundle.metafile.inputs),
- maxJobs: 4,
- priorTrialJobs: 1,
- totalApprovedJobs: 5,
- maxConcurrent: 1,
- deadlineMs: 60000,
- publicHttp: false,
- deployed: false,
-};
-await writeFile(resolve(output, 'build-receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);
-console.log(JSON.stringify(receipt));
diff --git a/hosting/scripts/build.mjs b/hosting/scripts/build.mjs
deleted file mode 100644
index 4b0e0a81..00000000
--- a/hosting/scripts/build.mjs
+++ /dev/null
@@ -1,68 +0,0 @@
-import { mkdir, writeFile } from 'node:fs/promises';
-import { createHash } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { build } from 'esbuild';
-import { assertProductionBoundary } from './build-boundary.mjs';
-
-const output = new URL('../../.cache/hosted-worker/', import.meta.url);
-await mkdir(output, { recursive: true });
-const nativeOnly = process.argv.includes('--native-only');
-if (!nativeOnly) {
- const { checkEdgeManifest } = await import('./edge-manifest.mjs');
- await checkEdgeManifest();
-}
-for (const entry of [
- 'worker',
- 'tenant-worker',
- 'evaluation-worker',
- 'render-worker',
- 'request-worker',
- 'admission-worker',
- 'native-programs',
- 'native-assets',
- 'native-materials',
- 'native-mcp',
- 'native-host',
- 'native-evaluator',
- 'native-render',
-]) {
- // The installed-image build must not depend on a checkout SDK or edge snapshot.
- if (nativeOnly && !entry.startsWith('native-')) continue;
- const result = await build({
- entryPoints: [fileURLToPath(new URL(`../src/${entry}.ts`, import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: entry.startsWith('native-') ? 'node' : 'browser',
- conditions: entry.startsWith('native-') ? undefined : ['workerd'],
- target: 'es2022',
- metafile: true,
- external: entry.startsWith('native-')
- ? [
- 'cloudflare:workers',
- '@instruktlabs/kiln',
- '@instruktlabs/kiln/*',
- '@modelcontextprotocol/server',
- '@modelcontextprotocol/node',
- ]
- : ['cloudflare:workers'],
- });
- const bytes = result.outputFiles[0].contents;
- const inputs = Object.keys(result.metafile.inputs);
- assertProductionBoundary(entry, inputs);
- await writeFile(new URL(`${entry}.mjs`, output), bytes);
- await writeFile(
- new URL(entry === 'worker' ? 'build.json' : `${entry}-build.json`, output),
- `${JSON.stringify(
- {
- sha256: createHash('sha256').update(bytes).digest('hex'),
- bytes: bytes.byteLength,
- inputs,
- imports: result.metafile.outputs[Object.keys(result.metafile.outputs)[0]].imports,
- },
- null,
- 2,
- )}\n`,
- );
- console.log(`Built ${entry} (${bytes.byteLength} bytes); no deployment performed.`);
-}
diff --git a/hosting/scripts/deployment-config.mjs b/hosting/scripts/deployment-config.mjs
deleted file mode 100644
index 6233b555..00000000
--- a/hosting/scripts/deployment-config.mjs
+++ /dev/null
@@ -1,321 +0,0 @@
-import {
- OutputRootConfigSchema,
- OutputWorkerSchema,
- OutputContainerSchema,
- convertToWranglerConfig,
-} from '@cloudflare/config';
-
-const fail = () => {
- throw new Error('Invalid deployment manifest');
-};
-function fields(value, names) {
- if (
- !value ||
- typeof value !== 'object' ||
- Array.isArray(value) ||
- Object.keys(value).sort().join(',') !== [...names].sort().join(',')
- )
- fail();
-}
-function matches(value, pattern) {
- if (typeof value !== 'string' || value.trim() !== value || !pattern.test(value)) fail();
-}
-function count(value, maximum = Number.MAX_SAFE_INTEGER) {
- if (!Number.isSafeInteger(value) || value < 1 || value > maximum) fail();
-}
-
-// Inputs have already passed manifest validation. This is a reviewable candidate,
-// not a Notifications API payload or evidence of live alert delivery.
-function monitoringCandidate(account, datasetName) {
- const dataset = `events.analyticsEngine.${datasetName}`;
- const query = (filters) =>
- `SELECT COUNT(*) AS value\nFROM ${dataset}\nWHERE accountTag = '${account}'\n AND timestamp >= NOW() - INTERVAL '5' MINUTE\n AND blob1 = 'kiln.ops.v1'\n AND ${filters}`;
- return {
- schemaVersion: 1,
- configured: false,
- destination: null,
- dataset,
- dialect: 'Cloudflare Analytics SQL API',
- alerts: [
- [
- 'deletion-heartbeat',
- "blob2 = 'health' AND blob3 = 'deletion' AND blob4 = 'ok' AND double5 = 1",
- '<',
- 1,
- ],
- ['compute-heartbeat', "blob2 = 'health' AND blob3 = 'compute' AND blob4 = 'ok'", '<', 1],
- [
- 'deletion-overdue',
- "blob2 = 'health' AND blob3 = 'deletion' AND blob4 = 'ok' AND double4 > 0",
- '>=',
- 1,
- ],
- [
- 'compute-cleanup',
- "blob2 = 'health' AND blob3 = 'compute' AND blob4 = 'ok' AND double4 > 0",
- '>=',
- 3,
- ],
- ['gateway-errors', "blob2 = 'http' AND blob4 LIKE '5%'", '>=', 5],
- ['gateway-rejections', "blob2 = 'http' AND blob4 = '429'", '>=', 100],
- ].map(([name, filters, comparison, threshold]) => ({
- name,
- query: query(filters),
- comparison,
- threshold,
- executionIntervalMinutes: 1,
- repeatIntervalMinutes: 60,
- })),
- };
-}
-
-/** Pure preparation: no Cloudflare requests, credentials, resource creation or public routes. */
-export function deploymentConfig(m) {
- fields(m, [
- 'account',
- 'prefix',
- 'origin',
- 'database',
- 'oauthKv',
- 'bucket',
- 'images',
- 'compute',
- 'storage',
- 'requestLimits',
- ]);
- fields(m.database, ['id', 'name']);
- fields(m.images, ['coordinator', 'software']);
- fields(m.compute, [
- 'maxConcurrent',
- 'tenantPerMinute',
- 'tenantPerDay',
- 'globalPerDay',
- 'globalPerMonth',
- 'deadlineMs',
- ]);
- fields(m.storage, ['maxBytes', 'maxObjects', 'maxGroups']);
- fields(m.requestLimits, ['edge', 'account']);
- for (const policy of Object.values(m.requestLimits)) {
- fields(policy, ['namespace', 'perMinute']);
- matches(policy.namespace, /^[1-9][0-9]*$/);
- count(Number(policy.namespace));
- count(policy.perMinute);
- }
- if (m.requestLimits.edge.namespace === m.requestLimits.account.namespace) fail();
- matches(m.account, /^[a-f0-9]{32}$/);
- matches(m.prefix, /^kiln-[a-z0-9]+(?:-[a-z0-9]+)*$/);
- if (m.prefix.length > 40) fail();
- matches(m.database.id, /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/);
- matches(m.oauthKv, /^[a-f0-9]{32}$/);
- if (m.database.name !== `${m.prefix}-accounts` || m.bucket !== `${m.prefix}-artifacts`) fail();
- let origin;
- try {
- origin = new URL(m.origin);
- } catch {
- fail();
- }
- if (
- origin.protocol !== 'https:' ||
- origin.origin !== m.origin ||
- origin.username ||
- origin.password
- )
- fail();
- for (const [kind, image] of Object.entries(m.images)) {
- matches(
- image,
- /^registry\.cloudflare\.com\/[a-f0-9]{32}\/kiln-(?:coordinator|software)@sha256:[a-f0-9]{64}$/,
- );
- if (!image.startsWith(`registry.cloudflare.com/${m.account}/kiln-${kind}@sha256:`)) fail();
- }
- for (const value of Object.values(m.compute)) count(value);
- for (const value of Object.values(m.storage)) count(value);
- count(m.compute.maxConcurrent, 16);
- count(m.compute.deadlineMs, 120000);
- if (
- m.compute.tenantPerMinute > m.compute.tenantPerDay ||
- m.compute.tenantPerDay > m.compute.globalPerDay ||
- m.compute.globalPerDay > m.compute.globalPerMonth
- )
- fail();
- const names = Object.fromEntries(
- ['gateway', 'tenant', 'admission', 'request', 'evaluation', 'render'].map((role) => [
- role,
- `${m.prefix}-${role}`,
- ]),
- );
- const text = (value) => ({ type: 'text', value: String(value) });
- const object = (role, exportName) => ({
- type: 'durable-object',
- worker: names[role],
- exportName,
- });
- const workerBinding = (role, exportName) => ({ type: 'worker', worker: names[role], exportName });
- const sqlite = { type: 'durable-object', storage: 'sqlite' };
- const entry = { type: 'worker' };
- const containers = {};
- for (const [role, imageKey, kind] of [
- ['request', 'coordinator', 'coordinator'],
- ['evaluation', 'kiln', 'software'],
- ['render', 'renderer', 'software'],
- ]) {
- containers[role] = OutputContainerSchema.parse({
- name: `${names[role]}-vm`,
- schedulingPolicy: 'durable-object',
- ssh: { enabled: false },
- observability: { enabled: false, logs: { enabled: false } },
- images: { [imageKey]: { reference: m.images[kind] } },
- });
- }
- const definitions = {
- gateway: {
- entry: 'worker',
- env: {
- ACCOUNTS: { type: 'd1', ...m.database },
- OAUTH_KV: { type: 'kv', id: m.oauthKv },
- OPERATIONS: {
- type: 'analytics-engine-dataset',
- name: `${m.prefix.replaceAll('-', '_')}_ops`,
- },
- PUBLIC_ORIGIN: text(m.origin),
- ...Object.fromEntries(
- [
- ['edge', 'EDGE_REQUEST_LIMIT'],
- ['account', 'ACCOUNT_REQUEST_LIMIT'],
- ].map(([kind, name]) => [
- name,
- {
- type: 'rate-limit',
- namespace: m.requestLimits[kind].namespace,
- simple: { limit: m.requestLimits[kind].perMinute, period: 60 },
- },
- ]),
- ),
- TENANTS: object('tenant', 'KilnTenant'),
- NATIVE_COMPUTE: workerBinding('admission', 'KilnCompute'),
- ...Object.fromEntries(
- [
- 'GOOGLE_CLIENT_ID',
- 'GOOGLE_CLIENT_SECRET',
- 'GITHUB_CLIENT_ID',
- 'GITHUB_CLIENT_SECRET',
- ].map((name) => [name, { type: 'secret' }]),
- ),
- },
- exports: {},
- },
- tenant: {
- entry: 'tenant-worker',
- env: {
- ARTIFACTS: { type: 'r2', name: m.bucket },
- STORAGE_MAX_BYTES: text(m.storage.maxBytes),
- STORAGE_MAX_OBJECTS: text(m.storage.maxObjects),
- STORAGE_MAX_GROUPS: text(m.storage.maxGroups),
- },
- exports: { KilnTenant: sqlite },
- },
- admission: {
- entry: 'admission-worker',
- env: {
- ADMISSION: object('admission', 'KilnAdmission'),
- REQUESTS: object('request', 'KilnNativeRequest'),
- COMPUTE_MAX_CONCURRENT: text(m.compute.maxConcurrent),
- COMPUTE_TENANT_PER_MINUTE: text(m.compute.tenantPerMinute),
- COMPUTE_TENANT_PER_DAY: text(m.compute.tenantPerDay),
- COMPUTE_GLOBAL_PER_DAY: text(m.compute.globalPerDay),
- COMPUTE_GLOBAL_PER_MONTH: text(m.compute.globalPerMonth),
- COMPUTE_DEADLINE_MS: text(m.compute.deadlineMs),
- },
- exports: { KilnAdmission: sqlite, KilnCompute: entry, KilnComputeControl: entry },
- },
- request: {
- entry: 'request-worker',
- env: {
- PUBLIC_ORIGIN: text(m.origin),
- TENANTS: object('tenant', 'KilnTenant'),
- REQUESTS: object('request', 'KilnNativeRequest'),
- EVALUATIONS: object('evaluation', 'KilnEvaluationJob'),
- RENDERS: object('render', 'KilnRenderJob'),
- },
- exports: {
- KilnNativeRequest: { ...sqlite, container: containers.request.name },
- KilnNativeStorage: entry,
- KilnNativeEvaluation: entry,
- KilnNativeRender: entry,
- },
- },
- evaluation: {
- entry: 'evaluation-worker',
- env: { EVALUATIONS: object('evaluation', 'KilnEvaluationJob') },
- exports: { KilnEvaluationJob: { ...sqlite, container: containers.evaluation.name } },
- },
- render: {
- entry: 'render-worker',
- env: { RENDERS: object('render', 'KilnRenderJob') },
- exports: { KilnRenderJob: { ...sqlite, container: containers.render.name } },
- },
- };
- const workers = {},
- wrangler = {};
- for (const [role, definition] of Object.entries(definitions)) {
- const worker = OutputWorkerSchema.parse({
- name: names[role],
- compatibilityDate: '2026-10-06',
- compatibilityFlags: [
- 'enable_ctx_exports',
- 'enable_request_signal',
- 'global_fetch_strictly_public',
- ],
- workersDev: false,
- previewUrls: false,
- domains: [],
- triggers: role === 'gateway' ? [{ type: 'scheduled', schedule: '* * * * *' }] : [],
- limits: { cpuMs: 30000, subrequests: 500 },
- // URLs can contain authorization codes and download capabilities. Do not
- // persist request/trace payloads; sanitized operational metrics are separate.
- observability: {
- enabled: false,
- redactQueryString: true,
- logs: { enabled: false, invocationLogs: false, persist: false },
- traces: { enabled: false, persist: false },
- },
- env: definition.env,
- exports: definition.exports,
- manifest: {
- type: 'complete',
- mainModule: 'worker.mjs',
- modules: { 'worker.mjs': { type: 'esm' } },
- },
- });
- workers[role] = worker;
- const config = convertToWranglerConfig({
- accountId: m.account,
- worker: {
- ...worker,
- entrypoint: `./.cloudflare/output/v0/workers/${role}/bundle/worker.mjs`,
- },
- containers: containers[role] ? [containers[role]] : [],
- });
- // cf beta.12 emits script_name even for self bindings; Containers require
- // those to be local. Never remove it from an actual cross-service binding.
- for (const binding of config.durable_objects?.bindings ?? [])
- if (binding.script_name === worker.name) delete binding.script_name;
- config.routes = [];
- if (role === 'gateway') config.d1_databases[0].migrations_dir = './migrations';
- wrangler[role] = config;
- }
- return {
- monitoring: monitoringCandidate(m.account, definitions.gateway.env.OPERATIONS.name),
- root: OutputRootConfigSchema.parse({
- accountId: m.account,
- buildContext: { isPreview: false },
- }),
- workers,
- containers,
- wrangler,
- entries: Object.fromEntries(
- Object.entries(definitions).map(([role, value]) => [role, value.entry]),
- ),
- deployOrder: ['tenant', 'evaluation', 'render', 'request', 'admission', 'gateway'],
- };
-}
diff --git a/hosting/scripts/edge-manifest.mjs b/hosting/scripts/edge-manifest.mjs
deleted file mode 100644
index ac4cd2d5..00000000
--- a/hosting/scripts/edge-manifest.mjs
+++ /dev/null
@@ -1,96 +0,0 @@
-import { mkdir, readFile, writeFile } from 'node:fs/promises';
-import { pathToFileURL } from 'node:url';
-import { createMcpHandler } from '@modelcontextprotocol/server';
-import { createKilnMcpServer } from '../../dist/mcp-engine.mjs';
-import { listDiscoveryEntries } from '../../lib/discovery/index.js';
-import { HOSTED_PROGRAM_RETENTION } from '../src/program-contract.ts';
-
-const destination = new URL('../src/generated/edge-manifest.json', import.meta.url);
-
-/** Capture metadata only. These sentinels cannot evaluate source or access user storage. */
-export async function generateEdgeManifest() {
- const unavailable = () => {
- throw new Error('Metadata generation must not access host services');
- };
- const service = new Proxy(
- {},
- { get: (_target, key) => (key === 'retention' ? HOSTED_PROGRAM_RETENTION : unavailable) },
- );
- const createServer = () =>
- createKilnMcpServer({
- assetLibrary: service,
- programStore: service,
- materialLibrary: service,
- workspace: { run: unavailable, current: () => undefined },
- evaluatorProfile: 'evaluator-required',
- evaluatorPort: { render: unavailable },
- cacheEvaluations: false,
- cacheCaptures: false,
- });
- const handler = createMcpHandler(createServer, { legacy: 'stateless', maxSubscriptions: 0 });
- async function rpc(method, params = {}) {
- const response = await handler.fetch(
- new Request('http://kiln-native.internal/mcp', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- 'mcp-protocol-version': '2025-11-25',
- },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
- }),
- );
- const text = await response.text();
- const message = response.headers.get('content-type')?.includes('text/event-stream')
- ? text
- .split('\n')
- .filter((line) => line.startsWith('data:'))
- .map((line) => JSON.parse(line.slice(5)))
- .findLast((value) => value.id !== undefined)
- : JSON.parse(text);
- if (response.status !== 200 || !message?.result || message.error)
- throw new Error(`Cannot capture native metadata for ${method}`);
- return message.result;
- }
- try {
- const { serverInfo, capabilities, instructions } = await rpc('initialize', {
- protocolVersion: '2025-11-25',
- capabilities: {},
- clientInfo: { name: 'metadata-build', version: '1' },
- });
- const { tools } = await rpc('tools/list');
- const { resources } = await rpc('resources/list');
- const { resourceTemplates } = await rpc('resources/templates/list');
- return {
- kind: 'kiln.hosted-edge.v1',
- serverInfo,
- capabilities,
- instructions,
- tools,
- resources,
- resourceTemplates,
- catalog: listDiscoveryEntries(),
- };
- } finally {
- await handler.close();
- }
-}
-
-export async function checkEdgeManifest() {
- const expected = `${JSON.stringify(await generateEdgeManifest(), null, 2)}\n`;
- if ((await readFile(destination, 'utf8')) !== expected)
- throw new Error(
- 'Hosted edge manifest is stale. Run node hosting/scripts/edge-manifest.mjs --write',
- );
-}
-
-if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
- if (process.argv.includes('--write')) {
- await mkdir(new URL('../src/generated/', import.meta.url), { recursive: true });
- await writeFile(destination, `${JSON.stringify(await generateEdgeManifest(), null, 2)}\n`);
- console.log('Generated hosted metadata from the native engine; no services called.');
- } else {
- await checkEdgeManifest();
- console.log('Hosted edge metadata matches the native engine.');
- }
-}
diff --git a/hosting/scripts/prepare-deployment.mjs b/hosting/scripts/prepare-deployment.mjs
deleted file mode 100644
index 10d53803..00000000
--- a/hosting/scripts/prepare-deployment.mjs
+++ /dev/null
@@ -1,165 +0,0 @@
-// Offline only. Provisioning, secrets, image upload and deployment are separate
-// reviewed operations. This command deliberately exposes no public route.
-import assert from 'node:assert/strict';
-import { execFile } from 'node:child_process';
-import { createHash } from 'node:crypto';
-import { mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises';
-import { dirname, relative, resolve, sep } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { parseArgs, promisify } from 'node:util';
-import { build } from 'esbuild';
-import { assertProductionBoundary } from './build-boundary.mjs';
-import { deploymentConfig } from './deployment-config.mjs';
-import { lifecycleConfig } from '../probe/lifecycle-config.mjs';
-import { assertLifecycleBoundary } from '../probe/lifecycle-build-boundary.mjs';
-
-const root = fileURLToPath(new URL('../../', import.meta.url));
-const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
-async function main() {
- const { values } = parseArgs({
- options: {
- manifest: { type: 'string' },
- output: { type: 'string' },
- 'private-lifecycle': { type: 'boolean', default: false },
- },
- });
- assert(values.manifest && values.output);
- const raw = await readFile(values.manifest);
- assert(raw.length <= 16384);
- const manifest = JSON.parse(raw);
- const privateLifecycle = values['private-lifecycle'];
- const configuration = privateLifecycle ? lifecycleConfig(manifest) : deploymentConfig(manifest);
- const cache = await realpath(resolve(root, '.cache'));
- const output = resolve(values.output),
- parent = await realpath(dirname(output));
- assert(parent === cache || parent.startsWith(cache + sep));
- // Refuse an existing output, including a link or a partly prepared candidate.
- await mkdir(output);
- assert((await realpath(output)).startsWith(cache + sep));
- const files = [];
- const put = async (path, bytes) => {
- const destination = resolve(output, path);
- assert(destination.startsWith(output + sep));
- await mkdir(dirname(destination), { recursive: true });
- await writeFile(destination, bytes, { flag: 'wx' });
- files.push({ path, sha256: hash(bytes), bytes: Buffer.byteLength(bytes) });
- };
- const json = (path, value) => put(path, `${JSON.stringify(value, null, 2)}\n`);
- const git = async (...args) =>
- (await promisify(execFile)('git', args, { cwd: root })).stdout.trim();
- const sourceCommit = await git('rev-parse', 'HEAD');
- const sourceDirty = Boolean(await git('status', '--porcelain'));
- const receipt = {
- schemaVersion: 1,
- mode: privateLifecycle ? 'private-lifecycle' : 'production-candidate',
- sourceCommit,
- sourceDirty,
- configSchema: '0.23.0',
- publicHttp: false,
- deployed: false,
- resourcesCreated: false,
- manifestSha256: hash(raw),
- deployOrder: configuration.deployOrder,
- requiredGatewaySecrets: Object.keys(configuration.workers.gateway.env).filter(
- (name) => configuration.workers.gateway.env[name].type === 'secret',
- ),
- images: manifest.images,
- workers: [],
- migrations: [],
- files,
- launchGates: privateLifecycle
- ? [
- 'exact-source CI',
- 'disposable resource ownership',
- 'immutable image identity',
- 'verified dependency-order deployment',
- 'no-public-route readback',
- 'bounded operator and verified cleanup',
- 'owner private-trial approval',
- ]
- : [
- 'exact-source CI',
- 'resource ownership',
- 'image identity',
- 'provider secrets',
- 'public ingress protection',
- 'sanitized operational monitoring',
- 'live OAuth and lifecycle qualification',
- 'owner deployment approval',
- ],
- };
- const schemaPackage = JSON.parse(
- await readFile(
- new URL('../node_modules/@cloudflare/config/package.json', import.meta.url),
- 'utf8',
- ),
- );
- assert.equal(schemaPackage.version, receipt.configSchema);
- await json('.cloudflare/output/v0/config.json', configuration.root);
- await json('monitoring-candidate.json', configuration.monitoring);
- for (const [role, entry] of Object.entries(configuration.entries)) {
- const result = await build({
- entryPoints: [resolve(root, 'hosting/src', `${entry}.ts`)],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- target: 'es2022',
- metafile: true,
- external: ['cloudflare:workers'],
- });
- const bytes = result.outputFiles[0].contents;
- const inputs = Object.keys(result.metafile.inputs);
- if (privateLifecycle) assertLifecycleBoundary(role, inputs);
- else assertProductionBoundary(entry, inputs);
- const built = Object.values(result.metafile.outputs)[0];
- const worker = configuration.workers[role];
- for (const name of ['default', ...Object.keys(worker.exports)])
- assert(built.exports.includes(name));
- assert(built.imports.every((item) => item.external && item.path === 'cloudflare:workers'));
- const bundle = `.cloudflare/output/v0/workers/${role}/bundle/worker.mjs`;
- await put(bundle, bytes);
- await json(`.cloudflare/output/v0/workers/${role}/worker.config.json`, worker);
- await json(`${role}.wrangler.json`, configuration.wrangler[role]);
- receipt.workers.push({
- role,
- name: worker.name,
- entry,
- bundle,
- sha256: hash(bytes),
- bytes: bytes.length,
- inputs: inputs.map((input) => relative(root, resolve(input)).replaceAll('\\', '/')),
- });
- }
- for (const container of Object.values(configuration.containers))
- await json(
- `.cloudflare/output/v0/containers/${container.name}/container.config.json`,
- container,
- );
- const migrations = resolve(root, 'hosting/migrations');
- for (const name of (await readdir(migrations))
- .filter((name) => /^\d{4}_[a-z_]+\.sql$/.test(name))
- .sort()) {
- const bytes = await readFile(resolve(migrations, name));
- await put(`migrations/${name}`, bytes);
- receipt.migrations.push({ name, sha256: hash(bytes) });
- }
- assert.equal(await git('rev-parse', 'HEAD'), sourceCommit);
- await writeFile(
- resolve(output, 'deployment-receipt.json'),
- `${JSON.stringify(receipt, null, 2)}\n`,
- { flag: 'wx' },
- );
- console.log(JSON.stringify(receipt));
-}
-try {
- await main();
-} catch {
- // A malformed input could contain a mistakenly supplied credential. Never
- // echo it, parser excerpts or arbitrary provider/configuration error text.
- console.error(
- 'Deployment preparation failed. Check the manifest, pinned dependencies and a fresh output directory under .cache; nothing was deployed.',
- );
- process.exitCode = 1;
-}
diff --git a/hosting/scripts/prepare-native-host.mjs b/hosting/scripts/prepare-native-host.mjs
deleted file mode 100644
index 081df53e..00000000
--- a/hosting/scripts/prepare-native-host.mjs
+++ /dev/null
@@ -1,82 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { copyFile, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
-import { dirname, join, resolve, sep } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { assertProductionBoundary } from './build-boundary.mjs';
-
-const root = fileURLToPath(new URL('../../', import.meta.url));
-const archive = process.argv[2];
-if (!archive)
- throw new Error(
- 'Usage: node hosting/scripts/prepare-native-host.mjs <qualified.tgz> [cache-directory]',
- );
-const output = resolve(process.argv[3] ?? join(root, '.cache/native-host-image/context'));
-if (!output.startsWith(join(root, '.cache') + sep))
- throw new Error('Build context must be within this checkout cache');
-await mkdir(output, { recursive: true });
-if ((await readdir(output)).length) throw new Error('Build context must be empty');
-const published = JSON.parse(
- await readFile(join(root, '.github/published-candidate.json'), 'utf8'),
-);
-const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
-assert.equal(
- hash(await readFile(archive)),
- published.sha256,
- 'Use the exact public release archive',
-);
-const files = {};
-for (const name of ['native-mcp', 'native-host']) {
- const base = join(root, '.cache/hosted-worker');
- const identity = JSON.parse(await readFile(join(base, `${name}-build.json`), 'utf8'));
- const bytes = await readFile(join(base, `${name}.mjs`));
- assert.equal(hash(bytes), identity.sha256);
- assertProductionBoundary(name, identity.inputs);
- await writeFile(join(output, `${name}.mjs`), bytes);
- files[`${name}.mjs`] = identity.sha256;
-}
-for (const [source, destination] of [
- ['Dockerfile.host', 'Dockerfile'],
- ['serve.mjs', 'serve.mjs'],
-]) {
- const path = join(root, 'hosting/container', source);
- await copyFile(path, join(output, destination));
- files[destination] = hash(await readFile(path));
-}
-await copyFile(archive, join(output, 'candidate.tgz'));
-await writeFile(join(output, 'candidate.sha256'), `${published.sha256} candidate.tgz\n`);
-const dependencies = JSON.parse(
- await readFile(join(root, 'hosting/package.json'), 'utf8'),
-).dependencies;
-await writeFile(
- join(output, 'package.json'),
- `${JSON.stringify(
- {
- name: 'kiln-private-native-host',
- version: published.version,
- private: true,
- type: 'module',
- dependencies: {
- '@instruktlabs/kiln': 'file:./candidate.tgz',
- '@modelcontextprotocol/node': dependencies['@modelcontextprotocol/node'],
- '@modelcontextprotocol/server': dependencies['@modelcontextprotocol/server'],
- },
- },
- null,
- 2,
- )}\n`,
-);
-await writeFile(
- join(dirname(output), 'context-receipt.json'),
- `${JSON.stringify(
- {
- output,
- engine: published,
- files,
- next: 'Generate package-lock.json in this context, then build Dockerfile for linux/amd64. Retain the resulting immutable image and inventories.',
- },
- null,
- 2,
- )}\n`,
-);
-console.log(`Prepared minimal native host context: ${output}`);
diff --git a/hosting/scripts/smoke-native-host.mjs b/hosting/scripts/smoke-native-host.mjs
deleted file mode 100644
index 26424941..00000000
--- a/hosting/scripts/smoke-native-host.mjs
+++ /dev/null
@@ -1,166 +0,0 @@
-import assert from 'node:assert/strict';
-import { spawn } from 'node:child_process';
-import { createHash, randomUUID } from 'node:crypto';
-import { mkdir, readFile, writeFile } from 'node:fs/promises';
-import { join, resolve, sep } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const root = fileURLToPath(new URL('../../', import.meta.url));
-const image = process.argv[2];
-if (!image || !/^[a-zA-Z0-9._:/@-]+$/.test(image))
- throw new Error('Supply the built image reference');
-const output = resolve(process.argv[3] ?? join(root, '.cache/native-host-image/qualification'));
-if (!output.startsWith(join(root, '.cache') + sep))
- throw new Error('Receipt must be in the checkout cache');
-await mkdir(output, { recursive: true });
-const name = `kiln-host-qualification-${randomUUID()}`;
-const published = JSON.parse(
- await readFile(join(root, '.github/published-candidate.json'), 'utf8'),
-);
-const receipt = {
- image,
- container: name,
- engine: published,
- status: 'running',
- cloudflareQualified: false,
-};
-
-async function docker(args, input) {
- return new Promise((done, fail) => {
- const child = spawn('docker', args, {
- windowsHide: true,
- stdio: ['pipe', 'pipe', 'pipe'],
- timeout: 60_000,
- });
- const stdout = [],
- stderr = [];
- let bytes = 0;
- for (const [stream, chunks] of [
- [child.stdout, stdout],
- [child.stderr, stderr],
- ])
- stream.on('data', (chunk) => {
- bytes += chunk.length;
- if (bytes > 1024 * 1024) child.kill();
- else chunks.push(chunk);
- });
- child.stdin.on('error', () => {});
- child.once('error', fail);
- child.once('close', (code) =>
- code === 0
- ? done(Buffer.concat(stdout).toString('utf8'))
- : fail(new Error(`Docker ${args[0]} failed: ${Buffer.concat(stderr).toString('utf8')}`)),
- );
- child.stdin.end(input);
- });
-}
-
-const check = `
-import assert from 'node:assert/strict';
-import {request} from 'node:http';
-import {readFile} from 'node:fs/promises';
-import {createHash} from 'node:crypto';
-const pkg=JSON.parse(await readFile('/opt/kiln/node_modules/@instruktlabs/kiln/package.json','utf8'));
-const hash=b=>createHash('sha256').update(b).digest('hex');
-function call(path,method='GET',headers={},body='') {return new Promise((resolve,reject)=>{
- const req=request({hostname:'127.0.0.1',port:3000,path,method,headers:{host:'kiln-native.internal',...headers}},res=>{
- let text='';res.on('data',c=>{text+=c;if(text.length>256*1024)req.destroy();});res.on('end',()=>resolve({status:res.statusCode,text}));res.on('error',reject);
- });req.on('error',reject);req.end(body);
-});}
-let ready=false;for(let i=0;i<100;i++){try{ready=(await call('/_ready')).status===204;}catch{}if(ready)break;await new Promise(r=>setTimeout(r,100));}assert(ready);
-const meta={'io.modelcontextprotocol/protocolVersion':'2026-07-28','io.modelcontextprotocol/clientInfo':{name:'native-host-fixture',version:'1'},'io.modelcontextprotocol/clientCapabilities':{}};
-const headers={'content-type':'application/json',accept:'application/json, text/event-stream','mcp-protocol-version':'2026-07-28','mcp-method':'tools/list'};
-const body=JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/list',params:{_meta:meta}});
-const listed=await call('/mcp','POST',headers,body);assert.equal(listed.status,200);const result=JSON.parse(listed.text);assert(!result.error);
-const names=result.result.tools.map(t=>t.name).sort();assert.equal(new Set(names).size,names.length);for(const n of ['kiln_discover','kiln_render','kiln_save','kiln_source','kiln_export','kiln_material'])assert(names.includes(n));
-assert(result.result.tools.find(t=>t.name==='kiln_render').inputSchema.properties.materialDependencies);
-const presets=await call('/mcp','POST',{...headers,'mcp-method':'tools/call','mcp-name':'kiln_material'},JSON.stringify({jsonrpc:'2.0',id:4,method:'tools/call',params:{_meta:meta,name:'kiln_material',arguments:{action:'presets'}}}));assert.equal(presets.status,200);const presetResult=JSON.parse(presets.text).result;assert(!presetResult.isError);assert(JSON.parse(presetResult.content.find(x=>x.type==='text').text).presets.length>0);
-const legacy=await call('/mcp','POST',{'content-type':'application/json',accept:'application/json, text/event-stream','mcp-protocol-version':'2025-11-25'},JSON.stringify({jsonrpc:'2.0',id:2,method:'initialize',params:{protocolVersion:'2025-11-25',capabilities:{},clientInfo:{name:'legacy-fixture',version:'1'}}}));assert.equal(legacy.status,200);assert(legacy.text.includes(pkg.version));
-assert.equal((await call('/mcp','POST',{...headers,host:'foreign.example'},body)).status,421);
-assert.equal((await call('/mcp','POST',{...headers,authorization:'Bearer PRIVATE_FIXTURE'},body)).status,403);
-const failed=await call('/mcp','POST',{...headers,'mcp-method':'tools/call','mcp-name':'kiln_render'},JSON.stringify({jsonrpc:'2.0',id:3,method:'tools/call',params:{_meta:meta,name:'kiln_render',arguments:{code:'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}'}}}));assert.equal(failed.status,200);const failure=JSON.parse(failed.text).result;assert.equal(failure.isError,true);assert(!failure.content.some(x=>x.type==='image'));
-// Trusted fixed fixture tests the installed protocol adapter, not VM isolation.
-const {loadContainerMcpRuntime}=await import('/opt/kiln/native-mcp.mjs');
-const {evaluateEvaluatorRequestV2}=await import('/opt/kiln/node_modules/@instruktlabs/kiln/lib/evaluator/index.js');
-const fixtureSource='function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}';
-const fixtureImage='sha256:'+'a'.repeat(64);
-const fixtureTransport=withIdentity=>async request=>{const input=await request.text();assert.equal(JSON.parse(input).code,fixtureSource);return new Response(await evaluateEvaluatorRequestV2(input),{headers:withIdentity?{'x-kiln-execution-image':fixtureImage}:{}});};
-const qualified=await loadContainerMcpRuntime({fetch:fixtureTransport(true)});
-const evaluated=await qualified.evaluatorPort.render(fixtureSource);
-assert.equal(qualified.evaluatorPort.executionImage(evaluated),fixtureImage);
-assert.equal(qualified.evaluatorPort.executionImage({...evaluated}),undefined);
-const unqualified=await loadContainerMcpRuntime({fetch:fixtureTransport(false)});
-await assert.rejects(unqualified.evaluatorPort.render(fixtureSource),error=>error.code==='WORKER_FAILED');
-console.log(JSON.stringify({version:pkg.version,archiveSha256:hash(await readFile('/opt/kiln/candidate.tgz')),tools:names,checks:['ready','modern-tool-catalog','material-binding-schema','material-presets-from-installed-package','legacy-initialize','foreign-host-denied','credentials-denied','missing-private-services-fail-closed','controller-image-bound-to-installed-evaluation','missing-controller-image-denied'],bundleSha256:Object.fromEntries(await Promise.all(['native-host.mjs','native-mcp.mjs','serve.mjs'].map(async name=>[name,hash(await readFile('/opt/kiln/'+name))])))}));
-`;
-
-try {
- receipt.imageIdentity = JSON.parse(
- await docker([
- 'image',
- 'inspect',
- image,
- '--format',
- '{"id":{{json .Id}},"os":{{json .Os}},"architecture":{{json .Architecture}},"user":{{json .Config.User}}}',
- ]),
- );
- assert.equal(receipt.imageIdentity.os, 'linux');
- assert.equal(receipt.imageIdentity.architecture, 'amd64');
- assert.equal(receipt.imageIdentity.user, 'node');
- await docker([
- 'create',
- '--name',
- name,
- '--network',
- 'none',
- '--cpus',
- '1',
- '--memory',
- '1g',
- '--memory-swap',
- '1g',
- '--pids-limit',
- '128',
- '--cap-drop',
- 'ALL',
- '--security-opt',
- 'no-new-privileges',
- '--read-only',
- '--tmpfs',
- '/tmp:rw,noexec,nosuid,size=64m',
- '--env',
- 'KILN_PUBLIC_ORIGIN=https://kiln.example.com',
- image,
- ]);
- await docker(['start', name]);
- assert.equal(
- (await docker(['inspect', name, '--format', '{{.Image}}'])).trim(),
- receipt.imageIdentity.id,
- );
- receipt.result = JSON.parse(
- await docker(['exec', '-i', '--user', '1000:1000', name, 'node', '--input-type=module'], check),
- );
- assert.equal(receipt.result.version, published.version);
- assert.equal(receipt.result.archiveSha256, published.sha256);
- for (const file of ['package-lock.json', 'os-packages.txt', 'node-version.txt'])
- await docker(['cp', `${name}:/opt/kiln/${file}`, join(output, file)]);
- receipt.lockSha256 = createHash('sha256')
- .update(await readFile(join(output, 'package-lock.json')))
- .digest('hex');
- receipt.status = 'passed';
-} catch (error) {
- receipt.status = 'failed';
- receipt.error = error.message;
- process.exitCode = 1;
-} finally {
- try {
- await docker(['rm', '--force', name]);
- receipt.removed = true;
- } catch (error) {
- receipt.cleanupError = error.message;
- receipt.status = 'failed';
- process.exitCode = 1;
- }
- await writeFile(join(output, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);
-}
-console.log(JSON.stringify(receipt, null, 2));
diff --git a/hosting/scripts/smoke-native-render.mjs b/hosting/scripts/smoke-native-render.mjs
deleted file mode 100644
index a95af5ca..00000000
--- a/hosting/scripts/smoke-native-render.mjs
+++ /dev/null
@@ -1,138 +0,0 @@
-import assert from 'node:assert/strict';
-import { spawn } from 'node:child_process';
-import { createHash, randomUUID } from 'node:crypto';
-import { mkdir, readFile, writeFile } from 'node:fs/promises';
-import { join, resolve, sep } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const root = fileURLToPath(new URL('../../', import.meta.url));
-const image = process.argv[2];
-if (!image || !/^[a-zA-Z0-9._:/@-]+$/.test(image))
- throw new Error('Supply the built image reference');
-const output = resolve(process.argv[3] ?? join(root, '.cache/software-render-entry/qualification'));
-if (!output.startsWith(join(root, '.cache') + sep))
- throw new Error('Receipt must be in the checkout cache');
-await mkdir(output, { recursive: true });
-const name = `kiln-render-qualification-${randomUUID()}`;
-const published = JSON.parse(
- await readFile(join(root, '.github/published-candidate.json'), 'utf8'),
-);
-const receipt = {
- image,
- container: name,
- engine: published,
- status: 'running',
- cloudflareQualified: false,
- hostileSourceQualified: false,
-};
-async function docker(args, input) {
- return new Promise((done, fail) => {
- const child = spawn('docker', args, {
- windowsHide: true,
- stdio: ['pipe', 'pipe', 'pipe'],
- timeout: 60_000,
- });
- const stdout = [],
- stderr = [];
- let bytes = 0,
- excessive = false;
- for (const [stream, chunks] of [
- [child.stdout, stdout],
- [child.stderr, stderr],
- ])
- stream.on('data', (chunk) => {
- bytes += chunk.length;
- if (bytes > 20 * 1024 * 1024) {
- excessive = true;
- child.kill();
- } else chunks.push(chunk);
- });
- child.stdin.on('error', () => {});
- child.once('error', fail);
- child.once('close', (code) =>
- code === 0 && !excessive
- ? done(Buffer.concat(stdout).toString('utf8'))
- : fail(new Error(`Docker ${args[0]} failed: ${Buffer.concat(stderr).toString('utf8')}`)),
- );
- child.stdin.end(input);
- });
-}
-try {
- receipt.imageIdentity = JSON.parse(
- await docker([
- 'image',
- 'inspect',
- image,
- '--format',
- '{"id":{{json .Id}},"os":{{json .Os}},"architecture":{{json .Architecture}},"user":{{json .Config.User}}}',
- ]),
- );
- assert.equal(receipt.imageIdentity.os, 'linux');
- assert.equal(receipt.imageIdentity.architecture, 'amd64');
- assert.equal(receipt.imageIdentity.user, 'node');
- await docker([
- 'create',
- '--interactive',
- '--name',
- name,
- '--network',
- 'none',
- '--cpus',
- '2',
- '--memory',
- '4g',
- '--memory-swap',
- '4g',
- '--pids-limit',
- '128',
- '--cap-drop',
- 'ALL',
- '--security-opt',
- 'no-new-privileges',
- image,
- 'node',
- '--input-type=module',
- ]);
- assert.equal(
- (await docker(['inspect', name, '--format', '{{.Image}}'])).trim(),
- receipt.imageIdentity.id,
- );
- const fixture = await readFile(new URL('./software-render-fixture.mjs', import.meta.url));
- receipt.fixtureSha256 = createHash('sha256').update(fixture).digest('hex');
- receipt.result = JSON.parse(await docker(['start', '--attach', '--interactive', name], fixture));
- assert.equal(receipt.result.version, published.version);
- assert.equal(receipt.result.archiveSha256, published.sha256);
- assert.equal(receipt.result.images.length, 8);
- for (const item of receipt.result.images) {
- assert.match(item.name, /^[a-z0-9-]+\.png$/);
- const bytes = Buffer.from(item.base64, 'base64');
- assert.equal(createHash('sha256').update(bytes).digest('hex'), item.sha256);
- await writeFile(join(output, item.name), bytes);
- delete item.base64;
- }
- for (const file of ['package-lock.json', 'os-packages.txt', 'node-version.txt'])
- await docker(['cp', `${name}:/opt/kiln/${file}`, join(output, file)]);
- receipt.lockSha256 = createHash('sha256')
- .update(await readFile(join(output, 'package-lock.json')))
- .digest('hex');
- receipt.status = 'passed';
-} catch (error) {
- receipt.status = 'failed';
- receipt.error = error.message;
- process.exitCode = 1;
-} finally {
- try {
- await docker(['rm', '--force', name]);
- assert.equal(
- (await docker(['ps', '--all', '--quiet', '--filter', `name=^/${name}$`])).trim(),
- '',
- );
- receipt.removed = true;
- } catch (error) {
- receipt.cleanupError = error.message;
- receipt.status = 'failed';
- process.exitCode = 1;
- }
- await writeFile(join(output, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);
-}
-console.log(JSON.stringify(receipt, null, 2));
diff --git a/hosting/scripts/software-render-fixture.mjs b/hosting/scripts/software-render-fixture.mjs
deleted file mode 100644
index 40bd94c6..00000000
--- a/hosting/scripts/software-render-fixture.mjs
+++ /dev/null
@@ -1,142 +0,0 @@
-// Fixed trusted fixture, passed over stdin to the disposable image by the smoke script.
-// No host workspace, network, user program or credential is available to this process.
-import assert from 'node:assert/strict';
-import { spawnSync } from 'node:child_process';
-import { createHash } from 'node:crypto';
-import { readFile } from 'node:fs/promises';
-import { createRequire } from 'node:module';
-import { renderGLB } from '@instruktlabs/kiln';
-import {
- createNativeRenderPort,
- encodeRenderRequest,
- RENDER_LIMITS,
-} from '/opt/kiln/native-render.mjs';
-
-const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
-const pkg = JSON.parse(await readFile('/opt/kiln/node_modules/@instruktlabs/kiln/package.json'));
-const { PNG } = createRequire('/opt/kiln/node_modules/@instruktlabs/kiln/package.json')('pngjs');
-const source = `function build(){const root=createRoot('Root');
- const albedo=proceduralTexture({schemaVersion:2,size:32,usage:'albedo',layers:[{op:'checker',colorA:0xcc2211,colorB:0x22bb33,squares:4}]});
- createPart('Textured',boxGeo(1,1,1),pbrMaterial({albedo,roughness:0.7,metalness:0.1}),{parent:root});
- createPart('Blue',sphereGeo(0.35),pbrMaterial({albedo:0x2233dd,roughness:0.25,metalness:0.4}),{parent:root,position:[0,0.2,0.85]});return root;}`;
-const { glb } = await renderGLB(source);
-const images = [];
-const runs = [];
-function entry(input) {
- // Deliberately omit the image's Vulkan environment: Cloudflare exec does too.
- return spawnSync('/usr/local/bin/node', ['/opt/kiln/render.mjs'], {
- input,
- env: { PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/node' },
- timeout: 30_000,
- maxBuffer: RENDER_LIMITS.responseBytes,
- });
-}
-function record(name, bytes) {
- const png = PNG.sync.read(Buffer.from(bytes));
- assert.equal(png.width, 128);
- assert.equal(png.height, 128);
- let red = 0,
- green = 0;
- for (let n = 0; n < png.data.length; n += 4) {
- const [r, g, b] = png.data.subarray(n, n + 3);
- if (r > g + 12 && r > b + 12) red++;
- if (g > r + 12 && g > b + 12) green++;
- }
- assert(red > 20 && green > 20, `${name}: expected textured colours`);
- images.push({
- name,
- sha256: hash(bytes),
- red,
- green,
- base64: Buffer.from(bytes).toString('base64'),
- });
-}
-const port = createNativeRenderPort({
- fetch: async (request) => {
- assert.equal(request.url, 'http://kiln-renderer.internal/render');
- const result = entry(Buffer.from(await request.arrayBuffer()));
- assert.equal(result.status, 0, result.stderr?.toString() || result.error?.message);
- assert.equal(result.signal, null);
- runs.push({ stderrSha256: hash(result.stderr), bytes: result.stdout.length });
- return new Response(result.stdout);
- },
-});
-for (const backdrop of ['neutral', 'dark', 'light']) {
- const result = await port({
- glb,
- size: 128,
- viewDirs: [
- [1, 0.4, 1],
- [0, 0, 1],
- ],
- backdrop,
- ...(backdrop === 'neutral' ? { beautySize: 128 } : {}),
- });
- assert.equal(result.ok, true, JSON.stringify(result));
- assert.equal(result.backend, 'vulkan');
- assert.equal(result.derivativeFidelity.inputGlbSha256, `sha256:${hash(glb)}`);
- assert.equal(result.derivativeFidelity.materialFaithful, true);
- assert.equal(result.viewsPng.length, 2);
- for (const [i, bytes] of result.viewsPng.entries()) record(`${backdrop}-${i}.png`, bytes);
- if (backdrop === 'neutral') record('beauty.png', result.beautyPng);
- runs.at(-1).rendererId = result.rendererId;
-}
-const cameras = [
- {
- position: [2, 1.2, 2],
- target: [0, 0, 0],
- up: [0, 1, 0],
- fovDeg: 50,
- aspect: 1,
- near: 0.1,
- far: 20,
- },
-];
-const camera = await port({
- glb,
- cameras,
- width: 128,
- height: 128,
- lightingPresetId: 'review-neutral-v1',
-});
-assert.equal(camera.ok, true, JSON.stringify(camera));
-assert.deepEqual(camera.cameras, cameras);
-assert.equal(camera.width, 128);
-assert.equal(camera.height, 128);
-assert.equal(camera.lightingPresetId, 'review-neutral-v1');
-record('camera.png', camera.viewsPng[0]);
-for (const bytes of [
- Buffer.from('{'),
- encodeRenderRequest({ glb: Buffer.from('not a GLB'), size: 128, viewDirs: [[1, 0, 0]] }).bytes,
-]) {
- const result = entry(bytes);
- assert.equal(result.status, 1);
- assert.equal(result.stdout.length, 0);
- assert.equal(result.stderr.toString(), 'Kiln software render input or execution failed.\n');
-}
-console.log(
- JSON.stringify({
- version: pkg.version,
- archiveSha256: hash(await readFile('/opt/kiln/candidate.tgz')),
- inputGlbSha256: hash(glb),
- runs,
- images,
- checks: [
- 'actual-render-entry',
- 'fixed-software-device',
- 'exact-glb-identity',
- 'three-backdrops',
- 'beauty',
- 'exact-camera',
- 'malformed-input-before-device',
- ],
- bundleSha256: Object.fromEntries(
- await Promise.all(
- ['native-render.mjs', 'render.mjs'].map(async (name) => [
- name,
- hash(await readFile(`/opt/kiln/${name}`)),
- ]),
- ),
- ),
- }),
-);
diff --git a/hosting/src/account-actions.ts b/hosting/src/account-actions.ts
deleted file mode 100644
index fda5679f..00000000
--- a/hosting/src/account-actions.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-import type { OAuthHelpers } from '@cloudflare/workers-oauth-provider';
-import { IDENTITY_ISSUERS } from './accounts';
-import type { SignInEnv } from './auth';
-import { BROWSER_COOKIE_ATTRIBUTES, browserToken, randomBrowserToken } from './browser-cookies';
-import { D1BrowserSessions, type BrowserSession } from './browser-sessions';
-import { D1Connections } from './connections';
-import { githubAuthorizationUrl, githubIdentity } from './github';
-import { googleAuthorizationUrl, googleIdentity } from './google';
-import { HttpFailure, sha256 } from './http';
-import type { SignInProvider } from './login-intents';
-
-const COOKIE = '__Host-kiln-action';
-const invalid = () =>
- new HttpFailure(
- 400,
- 'Invalid or expired account confirmation; return to your account and try again',
- );
-const denied = () =>
- new HttpFailure(403, 'Account action unavailable; return to your account and try again');
-const hash = (origin: string, kind: 'state' | 'binding', value: string) =>
- sha256(JSON.stringify(['kiln-account-action-v1', origin, kind, value]));
-const clearCookie = `${COOKIE}=; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=0`;
-
-export async function beginAccountAction(
- request: Request,
- origin: string,
- env: SignInEnv,
-): Promise<Response> {
- if (request.method !== 'POST')
- return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });
- if (new URL(request.url).search || request.headers.get('origin') !== origin) throw denied();
- if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')
- throw new HttpFailure(415, 'Expected form data');
- const form = await request.formData();
- const fields = ['csrf', 'action', 'connectionId', 'provider'];
- if (
- fields.some((key) => form.getAll(key).length !== 1) ||
- [...form.keys()].some((key) => !fields.includes(key))
- )
- throw denied();
- const provider = form.get('provider');
- const target = String(form.get('connectionId'));
- if (
- (provider !== 'google' && provider !== 'github') ||
- form.get('action') !== 'disconnect' ||
- !/^kc_[a-f0-9]{32}$/.test(target)
- )
- throw denied();
- const session = await new D1BrowserSessions(env.ACCOUNTS, origin).authorizeForm(
- request,
- String(form.get('csrf')),
- );
- const binding = randomBrowserToken();
- const flow = {
- state: `ka1_${randomBrowserToken()}`,
- verifier: randomBrowserToken(),
- nonce: randomBrowserToken(),
- selectAccount: true,
- };
- const now = Date.now();
- const previous = browserToken(request, origin, COOKIE);
- const database = env.ACCOUNTS.withSession('first-primary');
- const rows = await database.batch([
- database
- .prepare(`DELETE FROM kiln_account_actions WHERE state_hash IN
- (SELECT state_hash FROM kiln_account_actions WHERE expires_at<=? LIMIT 128)`)
- .bind(now),
- database
- .prepare('DELETE FROM kiln_account_actions WHERE binding_hash=?')
- .bind(previous ? await hash(origin, 'binding', previous) : ''),
- database
- .prepare(`INSERT INTO kiln_account_actions
- (state_hash,binding_hash,session_hash,account_id,account_epoch,provider,purpose,target,verifier,nonce,expires_at)
- SELECT ?,?,s.token_hash,s.account_id,s.account_epoch,?,'disconnect',?,?,?,? FROM kiln_browser_sessions s
- JOIN kiln_accounts a ON a.id=s.account_id WHERE s.token_hash=? AND s.csrf=? AND s.account_epoch=?
- AND s.account_id=? AND a.state='active' AND a.authorization_epoch=s.account_epoch AND s.expires_at>? AND s.idle_expires_at>?
- AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=s.account_id AND i.issuer=?)
- AND EXISTS (SELECT 1 FROM kiln_connections c WHERE c.id=? AND c.account_id=s.account_id AND c.account_epoch=s.account_epoch
- AND c.state IN ('pending','active') AND c.expires_at>?)
- AND (SELECT COUNT(*) FROM kiln_account_actions WHERE account_id=s.account_id)<4
- AND (SELECT COUNT(*) FROM kiln_account_actions)<4096 RETURNING state_hash`)
- .bind(
- await hash(origin, 'state', flow.state),
- await hash(origin, 'binding', binding),
- provider,
- target,
- flow.verifier,
- flow.nonce,
- now + 600_000,
- session.binding,
- session.csrf,
- session.accountEpoch,
- session.accountId,
- now,
- now,
- IDENTITY_ISSUERS[provider],
- target,
- now,
- ),
- ]);
- if (rows[2]?.results.length !== 1) throw denied();
- const location =
- provider === 'google'
- ? await googleAuthorizationUrl(origin, flow, env, request.signal)
- : await githubAuthorizationUrl(origin, flow.state, flow.verifier, env, true);
- return new Response(null, {
- status: 302,
- headers: {
- location,
- 'set-cookie': `${COOKIE}=${binding}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=600`,
- },
- });
-}
-
-export async function finishAccountAction(
- request: Request,
- origin: string,
- env: SignInEnv,
- provider: SignInProvider,
- oauth: OAuthHelpers,
- ctx: ExecutionContext,
-): Promise<Response> {
- const url = new URL(request.url);
- const state = url.searchParams.get('state') ?? '';
- const binding = browserToken(request, origin, COOKIE);
- if (
- request.method !== 'GET' ||
- url.pathname !== `/oauth/${provider}/callback` ||
- url.searchParams.getAll('state').length !== 1 ||
- !/^ka1_[a-f0-9]{64}$/.test(state) ||
- !binding
- )
- throw invalid();
- const sessions = new D1BrowserSessions(env.ACCOUNTS, origin);
- let session: BrowserSession;
- try {
- session = await sessions.read(request);
- } catch (error) {
- if (error instanceof HttpFailure && error.status === 401) throw invalid();
- throw error;
- }
- const now = Date.now();
- const flow = await env.ACCOUNTS.withSession('first-primary')
- .prepare(
- `DELETE FROM kiln_account_actions WHERE state_hash=? AND binding_hash=? AND provider=? AND purpose='disconnect'
- AND session_hash=? AND account_id=? AND account_epoch=? AND expires_at>?
- AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_account_actions.account_id AND a.state='active' AND a.authorization_epoch=kiln_account_actions.account_epoch)
- RETURNING target,verifier,nonce`,
- )
- .bind(
- await hash(origin, 'state', state),
- await hash(origin, 'binding', binding),
- provider,
- session.binding,
- session.accountId,
- session.accountEpoch,
- now,
- )
- .first<{ target: string; verifier: string; nonce: string }>();
- if (!flow) throw invalid();
- if (url.searchParams.has('error'))
- return new Response('Confirmation was cancelled. Return to your account to try again.', {
- status: 400,
- headers: { 'set-cookie': clearCookie },
- });
- const code = url.searchParams.get('code');
- if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1) throw invalid();
- const identity =
- provider === 'google'
- ? await googleIdentity(request, origin, { ...flow, state }, env)
- : await githubIdentity(code, flow.verifier, origin, env);
- const grantId = await new D1Connections(env.ACCOUNTS).revoke(session, identity, flow.target);
- // The primary deny is already committed. KV cleanup is supplemental and may
- // propagate later; failure cannot re-enable a connection, and records have TTLs.
- if (grantId) ctx.waitUntil(oauth.revokeGrant(grantId, session.accountId).catch(() => {}));
- const renewed = await sessions.renew(identity, session, request);
- const headers = new Headers({ location: '/account' });
- headers.append('set-cookie', clearCookie);
- headers.append('set-cookie', renewed.cookie);
- return new Response(null, { status: 303, headers });
-}
diff --git a/hosting/src/account-deletions.ts b/hosting/src/account-deletions.ts
deleted file mode 100644
index 74df5d3f..00000000
--- a/hosting/src/account-deletions.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-import { IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';
-import type { BrowserSession } from './browser-sessions';
-import { HttpFailure, sha256 } from './http';
-
-type Phase = 'compute' | 'storage' | 'grants' | 'identity' | 'complete';
-interface Claim {
- id: string;
- account_id: string;
- phase: Exclude<Phase, 'complete'>;
- lease_token: string;
- attempts: number;
-}
-export interface DeletionPorts {
- retireCompute(accountId: string): Promise<void>;
- retireStorage(accountId: string): Promise<boolean>;
- revokeGrants(accountId: string): Promise<boolean>;
-}
-const denied = () => new HttpFailure(403, 'Account deletion could not be confirmed');
-const RECEIPT_LIFETIME = 7 * 86400_000;
-
-/** Primary revocation plus a durable, leased outbox. No caller supplies a job ID. */
-export class D1AccountDeletions {
- constructor(
- private readonly database: D1Database,
- private readonly origin: string,
- private readonly ports?: DeletionPorts,
- private readonly now: () => number = Date.now,
- ) {
- const url = new URL(origin);
- if (url.protocol !== 'https:' || url.origin !== origin)
- throw new Error('Invalid deletion origin');
- }
-
- private hash(receipt: string) {
- return sha256(JSON.stringify(['kiln-deletion-receipt-v1', this.origin, receipt]));
- }
-
- /** Call only after consuming a purpose-bound flow and verifying its provider. */
- async request(proof: BrowserSession, identity: VerifiedIdentity, receipt: string) {
- if (
- !proof ||
- !identity ||
- typeof receipt !== 'string' ||
- !/^[a-f0-9]{64}(?![\s\S])/.test(receipt) ||
- typeof proof.accountId !== 'string' ||
- !/^ka_[a-f0-9]{32}(?![\s\S])/.test(proof.accountId) ||
- !Number.isSafeInteger(proof.accountEpoch) ||
- proof.accountEpoch < 1 ||
- typeof proof.binding !== 'string' ||
- typeof proof.csrf !== 'string' ||
- !Object.values(IDENTITY_ISSUERS).some((issuer) => issuer === identity.issuer) ||
- typeof identity.subject !== 'string' ||
- !/^[\x21-\x7e]{1,255}(?![\s\S])/.test(identity.subject)
- )
- throw denied();
- const id = `kd_${crypto.randomUUID().replace(/-/g, '')}`,
- now = this.now();
- const database = this.database.withSession('first-primary');
- const result = await database.batch([
- database
- .prepare(`INSERT INTO kiln_deletions
- (id,account_id,receipt_hash,phase,created_at,updated_at,retry_at)
- SELECT ?,a.id,?,'compute',?,?,? FROM kiln_accounts a
- JOIN kiln_browser_sessions s ON s.account_id=a.id
- WHERE a.id=? AND a.state='active' AND a.authorization_epoch=?
- AND s.token_hash=? AND s.csrf=? AND s.account_epoch=a.authorization_epoch
- AND s.expires_at>? AND s.idle_expires_at>?
- AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=a.id AND i.issuer=? AND i.subject=?)
- ON CONFLICT(account_id) DO NOTHING RETURNING id`)
- .bind(
- id,
- await this.hash(receipt),
- now,
- now,
- now,
- proof.accountId,
- proof.accountEpoch,
- proof.binding,
- proof.csrf,
- now,
- now,
- identity.issuer,
- identity.subject,
- ),
- database
- .prepare(`UPDATE kiln_accounts SET state='deleting',authorization_epoch=authorization_epoch+1
- WHERE id=? AND state='active' AND changes()=1
- AND EXISTS (SELECT 1 FROM kiln_deletions WHERE id=? AND account_id=kiln_accounts.id) RETURNING id`)
- .bind(proof.accountId, id),
- database
- .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=? AND changes()=1')
- .bind(proof.accountId),
- database
- .prepare(`UPDATE kiln_connections SET state='revoked' WHERE account_id=?
- AND EXISTS (SELECT 1 FROM kiln_deletions WHERE id=? AND account_id=kiln_connections.account_id)`)
- .bind(proof.accountId, id),
- ]);
- if (result[1]?.results.length !== 1) throw denied();
- return { id };
- }
-
- async status(receipt: unknown) {
- if (typeof receipt !== 'string' || !/^[a-f0-9]{64}(?![\s\S])/.test(receipt))
- throw new HttpFailure(404, 'Deletion receipt unavailable');
- const row = await this.database
- .withSession('first-primary')
- .prepare(`SELECT id,phase,created_at AS createdAt,completed_at AS completedAt
- FROM kiln_deletions WHERE receipt_hash=? AND (completed_at IS NULL OR completed_at>?)`)
- .bind(await this.hash(receipt), this.now() - RECEIPT_LIFETIME)
- .first<{ id: string; phase: Phase; createdAt: number; completedAt: number | null }>();
- if (!row) throw new HttpFailure(404, 'Deletion receipt unavailable');
- return {
- ...row,
- state: row.phase === 'complete' ? ('complete' as const) : ('pending' as const),
- };
- }
-
- private async claim(): Promise<Claim | null> {
- const now = this.now(),
- lease = crypto.randomUUID();
- return this.database
- .withSession('first-primary')
- .prepare(`UPDATE kiln_deletions SET lease_token=?,lease_until=?,attempts=attempts+1,updated_at=?
- WHERE id=(SELECT d.id FROM kiln_deletions d JOIN kiln_accounts a ON a.id=d.account_id
- WHERE d.phase!='complete' AND d.retry_at<=? AND d.lease_until<=? AND a.state='deleting'
- ORDER BY d.retry_at,d.created_at,d.id LIMIT 1)
- RETURNING id,account_id,phase,lease_token,attempts`)
- .bind(lease, now + 60_000, now, now, now)
- .first<Claim>();
- }
-
- private async advance(claim: Claim, phase: Phase, retry = 0): Promise<void> {
- const now = this.now();
- await this.database
- .withSession('first-primary')
- .prepare(`UPDATE kiln_deletions SET attempts=CASE WHEN phase=? THEN attempts ELSE 0 END,
- phase=?,retry_at=?,updated_at=?,lease_token=NULL,lease_until=0
- WHERE id=? AND account_id=? AND phase=? AND lease_token=? AND lease_until>?
- AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_deletions.account_id AND a.state='deleting')`)
- .bind(
- phase,
- phase,
- now + retry,
- now,
- claim.id,
- claim.account_id,
- claim.phase,
- claim.lease_token,
- now,
- )
- .run();
- }
-
- private async finish(claim: Claim): Promise<void> {
- const database = this.database.withSession('first-primary'),
- now = this.now();
- const authorized = `EXISTS (SELECT 1 FROM kiln_deletions d JOIN kiln_accounts a ON a.id=d.account_id
- WHERE d.id=? AND d.account_id=? AND d.phase='identity' AND d.lease_token=? AND d.lease_until>?
- AND a.state='deleting')`;
- const args = [claim.id, claim.account_id, claim.lease_token, now];
- await database.batch([
- ...[
- 'kiln_browser_sessions',
- 'kiln_connections',
- 'kiln_account_events',
- 'kiln_identities',
- ].map((table) =>
- database
- .prepare(`DELETE FROM ${table} WHERE account_id=? AND ${authorized}`)
- .bind(claim.account_id, ...args),
- ),
- database
- .prepare(`DELETE FROM kiln_accounts WHERE id=? AND ${authorized}`)
- .bind(claim.account_id, ...args),
- // The foreign key clears account_id in the same transaction. A failed
- // identity/account delete cannot leave a completed receipt behind.
- database
- .prepare(`UPDATE kiln_deletions SET phase='complete',completed_at=?,updated_at=?,
- lease_token=NULL,lease_until=0,retry_at=0 WHERE id=? AND account_id IS NULL
- AND phase='identity' AND lease_token=? AND changes()=1`)
- .bind(now, now, claim.id, claim.lease_token),
- ]);
- }
-
- /** Called by the trusted scheduled handler, with a bounded immediate attempt after confirmation. */
- async recover(): Promise<{ steps: number }> {
- if (!this.ports) throw new Error('Deletion recovery is not configured');
- await this.database
- .withSession('first-primary')
- .prepare(`DELETE FROM kiln_deletions WHERE id IN
- (SELECT id FROM kiln_deletions WHERE phase='complete' AND completed_at<=? LIMIT 128)`)
- .bind(this.now() - RECEIPT_LIFETIME)
- .run();
- const end = Date.now() + 25_000;
- let steps = 0;
- for (; steps < 4 && Date.now() < end; steps++) {
- const claim = await this.claim();
- if (!claim) break;
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- const work = async () => {
- if (claim.phase === 'compute') {
- await this.ports!.retireCompute(claim.account_id);
- return true;
- }
- if (claim.phase === 'storage') return this.ports!.retireStorage(claim.account_id);
- if (claim.phase === 'grants') return this.ports!.revokeGrants(claim.account_id);
- await this.finish(claim);
- return true;
- };
- const done = await Promise.race([
- work(),
- new Promise<never>((_, reject) => {
- timer = setTimeout(
- () => reject(new Error('Deletion step deadline')),
- Math.max(1, Math.min(20_000, end - Date.now())),
- );
- }),
- ]);
- if (claim.phase !== 'identity') {
- const next = { compute: 'storage', storage: 'grants', grants: 'identity' } as const;
- await this.advance(claim, done ? next[claim.phase] : claim.phase, done ? 0 : 60_000);
- }
- } catch {
- // No exception text or provider data is retained. A late idempotent
- // cleanup cannot advance a replaced lease or reactivate an account.
- await this.advance(
- claim,
- claim.phase,
- Math.min(3600_000, 60_000 * 2 ** Math.min(claim.attempts - 1, 6)),
- );
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
- }
- return { steps };
- }
-}
diff --git a/hosting/src/account-page.ts b/hosting/src/account-page.ts
deleted file mode 100644
index 457d3f85..00000000
--- a/hosting/src/account-page.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { IDENTITY_ISSUERS } from './accounts';
-import { D1BrowserSessions, type BrowserSession } from './browser-sessions';
-import { HttpFailure } from './http';
-import { GOOGLE_SIGN_IN_BUTTON } from './google-button';
-import { D1Connections } from './connections';
-import { validLoginReturn } from './download-path';
-import { escapeHtml, htmlPage } from './html-page';
-
-function page(content: string, status = 200): Response {
- return htmlPage('Your account', content, { status });
-}
-
-export function signInPage(returnTo = '/account'): Response {
- if (!validLoginReturn(returnTo)) throw new HttpFailure(400, 'Invalid sign-in destination');
- return page(
- `<h1>Sign in to Kiln</h1><p>${
- returnTo === '/account'
- ? 'Free hosted access, with private saved assets and a personal usage quota.'
- : 'Sign in to the Kiln account that saved this asset to download it. This link expires after ten minutes; you can request a new link from your connected app.'
- }</p>
-<section><h2>Welcome back</h2><p>Use the same sign-in method as before to reach your saved work. Kiln requests no GitHub repository access or Google Drive access.</p>
-<form class="provider-buttons" method="post" action="/account/login"><input type="hidden" name="returnTo" value="${escapeHtml(returnTo)}"><button class="google-button" name="provider" value="google"><img src="${GOOGLE_SIGN_IN_BUTTON}" width="198" height="44" alt="Sign in with Google"></button>
-<button class="github-button" name="provider" value="github">Sign in with GitHub</button></form></section>`,
- 401,
- );
-}
-
-export function accountNoticePage(message: string): Response {
- return page(
- `<h1>${escapeHtml(message)}</h1><p>Your saved assets and Kiln account stay the same. All browser sessions and connected apps have been signed out.</p><p><a href="/account">Sign in to continue</a>, then reconnect any apps you want to use.</p>`,
- );
-}
-
-export function deletionStatusPage(status: {
- id: string;
- state: 'pending' | 'complete';
- createdAt: number;
-}): Response {
- return page(
- status.state === 'complete'
- ? `<h1>Account deleted</h1><p>Your Kiln account and files have been removed from the active service. Access from this account remains revoked.</p><p>This does not remove copies you previously downloaded or shared. Inaccessible authorization records and provider backups follow the retention policy.</p><p>This private receipt is available for seven days. You can <a href="/account">create a new, empty account</a> if you return.</p>`
- : `<h1>Deletion in progress</h1><p>Access to your account is blocked while Kiln stops outstanding work and removes your files and sign-in records. You can close this page; cleanup continues automatically.</p><p><a href="/account/deletion">Refresh deletion status</a>. If this remains pending, contact support with reference <strong>${escapeHtml(status.id)}</strong>.</p><p>Requested ${escapeHtml(new Date(status.createdAt).toISOString())}.</p>`,
- );
-}
-
-export async function accountPage(
- request: Request,
- database: D1Database,
- origin: string,
-): Promise<Response> {
- const url = new URL(request.url);
- if (url.search) throw new HttpFailure(400, 'Query parameters are not supported on account pages');
- const sessions = new D1BrowserSessions(database, origin);
- if (url.pathname === '/account/logout') {
- if (request.method !== 'POST')
- return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });
- if (request.headers.get('origin') !== origin)
- throw new HttpFailure(403, 'Invalid account form');
- if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')
- throw new HttpFailure(415, 'Expected form data');
- const form = await request.formData();
- if (form.getAll('csrf').length !== 1 || [...form.keys()].some((key) => key !== 'csrf'))
- throw new HttpFailure(403, 'Invalid account form');
- const cookie = await sessions.logout(request, String(form.get('csrf')));
- return new Response(null, {
- status: 303,
- headers: { location: '/account', 'set-cookie': cookie },
- });
- }
- if (request.method !== 'GET')
- return new Response('Method not allowed', { status: 405, headers: { allow: 'GET' } });
- let session: BrowserSession;
- try {
- session = await sessions.read(request);
- } catch (error) {
- if (!(error instanceof HttpFailure) || error.status !== 401) throw error;
- return signInPage();
- }
- const identities = await database
- .withSession('first-primary')
- .prepare('SELECT issuer FROM kiln_identities WHERE account_id=? ORDER BY issuer LIMIT 3')
- .bind(session.accountId)
- .all<{ issuer: string }>();
- const providers = identities.results.map(({ issuer }) =>
- issuer === IDENTITY_ISSUERS.google
- ? 'Google'
- : issuer === IDENTITY_ISSUERS.github
- ? 'GitHub'
- : 'Unknown provider',
- );
- const connections = await new D1Connections(database).list(
- session.accountId,
- session.accountEpoch,
- );
- const providerOptions = identities.results
- .flatMap(({ issuer }) =>
- issuer === IDENTITY_ISSUERS.google
- ? ['<option value="google">Google</option>']
- : issuer === IDENTITY_ISSUERS.github
- ? ['<option value="github">GitHub</option>']
- : [],
- )
- .join('');
- const connectionCards = connections
- .map(
- (connection) => `<article><h3>${escapeHtml(connection.clientName)}</h3>
-<p>${connection.clientDomain ? `Client domain: ${escapeHtml(connection.clientDomain)}.` : 'This client registered its own name; that name is not verified.'}
-Return address: ${escapeHtml(new URL(connection.redirectUri).host)}.</p>
-<p>${connection.state === 'pending' ? 'Waiting for the app to finish connecting.' : 'Connected'} · ${escapeHtml(new Date(connection.createdAt).toISOString().slice(0, 16).replace('T', ' '))} UTC</p>
-<form method="post" action="/account/action"><input type="hidden" name="csrf" value="${escapeHtml(session.csrf)}">
-<input type="hidden" name="action" value="disconnect"><input type="hidden" name="connectionId" value="${escapeHtml(connection.id)}">
-<label>Confirm using <select name="provider">${providerOptions}</select></label> <button type="submit">Disconnect this app</button></form></article>`,
- )
- .join('');
- const identityControls = (['google', 'github'] as const)
- .map((target) => {
- const linked = identities.results.some(({ issuer }) => issuer === IDENTITY_ISSUERS[target]);
- const confirmer = (['google', 'github'] as const).find(
- (provider) =>
- provider !== target &&
- identities.results.some(({ issuer }) => issuer === IDENTITY_ISSUERS[provider]),
- );
- if (!confirmer) return '';
- const label = target === 'google' ? 'Google' : 'GitHub';
- return `<form method="post" action="/account/identity"><input type="hidden" name="csrf" value="${escapeHtml(session.csrf)}">
-<input type="hidden" name="action" value="${linked ? 'unlink' : 'link'}"><input type="hidden" name="target" value="${target}">
-<input type="hidden" name="provider" value="${confirmer}"><button type="submit">${linked ? 'Remove' : 'Add'} ${label}</button></form>`;
- })
- .join('');
- const events = await database
- .withSession('first-primary')
- .prepare(
- 'SELECT kind,provider,created_at AS createdAt FROM kiln_account_events WHERE account_id=? ORDER BY created_at DESC,id DESC LIMIT 20',
- )
- .bind(session.accountId)
- .all<{ kind: 'link' | 'unlink'; provider: string; createdAt: number }>();
- const activity = events.results
- .map(
- (event) =>
- `<li>${event.kind === 'link' ? 'Sign-in method added' : 'Sign-in method removed'}: ${event.provider === 'google' ? 'Google' : 'GitHub'} · ${escapeHtml(new Date(event.createdAt).toISOString().slice(0, 16).replace('T', ' '))} UTC</li>`,
- )
- .join('');
- return page(`<h1>Your Kiln account</h1><p>Free hosted access, with private saved assets and a personal usage quota.</p>
-<section><h2>Sign-in methods</h2><ul>${providers.map((provider) => `<li>${escapeHtml(provider)}</li>`).join('')}</ul>
-<p>Adding a method asks you to confirm your current provider, then the new one. Removing a method asks you to confirm the one you will keep. Each change signs out all browsers and connected apps. Saved assets stay in this account. Already separate Kiln accounts cannot be merged.</p><div class="provider-buttons">${identityControls}</div></section>
-<section><h2>Recent security activity</h2>${activity ? `<ul>${activity}</ul>` : '<p>No sign-in method changes.</p>'}<p>Kiln shows security notices in the app. It does not send email alerts for sign-in method changes or account deletion.</p></section>
-<section><h2>Connected apps</h2><p>Disconnecting blocks new requests from that connection. Confirm with a sign-in method to continue.</p>${connectionCards || '<p>No connected apps.</p>'}</section>
-<section><h2>This browser</h2><p>Signing out here leaves your connected apps working.</p>
-<form method="post" action="/account/logout"><input type="hidden" name="csrf" value="${escapeHtml(session.csrf)}">
-<button type="submit">Sign out of this browser</button></form></section>
-<section><h2>Delete your account</h2><p>This permanently removes your hosted Kiln account and saved files. Download anything you want to keep first. Your local npm package and local files are unaffected.</p>
-<form method="post" action="/account/delete"><input type="hidden" name="csrf" value="${escapeHtml(session.csrf)}">
-<p><label><input type="checkbox" name="confirmation" value="delete-my-account" required> I understand that my hosted files will be deleted.</label></p>
-<p><label>Confirm using <select name="provider">${providerOptions}</select></label></p><button type="submit">Confirm account deletion</button></form>
-<p>Next, confirm control of a linked sign-in method. Cancelling that step leaves your account unchanged. After confirmation, access is revoked and deletion cannot be undone.</p></section>`);
-}
diff --git a/hosting/src/accounts.ts b/hosting/src/accounts.ts
deleted file mode 100644
index ad68c788..00000000
--- a/hosting/src/accounts.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { HttpFailure } from './http';
-
-export const IDENTITY_ISSUERS = {
- google: 'https://accounts.google.com',
- github: 'https://github.com',
-} as const;
-
-/** Identity inputs may only come from a successfully verified provider adapter. */
-export interface VerifiedIdentity {
- issuer: string;
- subject: string;
-}
-
-export interface KilnAccount {
- id: string;
- state: 'active' | 'disabled' | 'deleting';
- authorizationEpoch: number;
-}
-
-export interface AccountDirectory {
- /** Reuses a binding or atomically creates it; never links existing accounts. */
- resolveIdentity(identity: VerifiedIdentity): Promise<KilnAccount>;
- /** Reads current primary state, including disabled/deleting and revocation epoch. */
- getAccount(id: string): Promise<KilnAccount | null>;
-}
-
-/** A grant can outlive sign-in, but never the account's current authorization epoch. */
-export async function isCurrentAccountGrant(
- database: D1Database,
- userId: unknown,
- props: unknown,
-): Promise<boolean> {
- if (
- typeof userId !== 'string' ||
- !/^ka_[a-f0-9]{32}$/.test(userId) ||
- !props ||
- typeof props !== 'object'
- )
- return false;
- const grant = props as Record<string, unknown>;
- if (
- grant.userId !== userId ||
- !Number.isSafeInteger(grant.accountEpoch) ||
- Number(grant.accountEpoch) < 1
- )
- return false;
- const account = await new D1AccountDirectory(database).getAccount(userId);
- return account?.state === 'active' && account.authorizationEpoch === grant.accountEpoch;
-}
-
-const accountColumns = 'id, state, authorization_epoch AS authorizationEpoch';
-
-export class D1AccountDirectory implements AccountDirectory {
- constructor(private readonly database: D1Database) {}
-
- async resolveIdentity(identity: VerifiedIdentity): Promise<KilnAccount> {
- if (
- !identity ||
- !Object.values(IDENTITY_ISSUERS).some((issuer) => issuer === identity.issuer) ||
- typeof identity.subject !== 'string' ||
- !/^[\x21-\x7e]{1,255}$/.test(identity.subject)
- ) {
- throw new HttpFailure(400, 'Invalid sign-in identity');
- }
- const { issuer, subject } = identity;
- const id = `ka_${crypto.randomUUID().replace(/-/g, '')}`;
- const created = Date.now();
- // A fresh primary-backed session per operation, never a client bookmark.
- const session = this.database.withSession('first-primary');
- // D1 batches are transactions. Registration cannot leave an orphan account
- // when binding fails, or allocate several owners under concurrent callbacks.
- const results = await session.batch<KilnAccount>([
- session
- .prepare(`INSERT INTO kiln_accounts (id, created_at)
- SELECT ?, ? WHERE NOT EXISTS (
- SELECT 1 FROM kiln_identities WHERE issuer=? AND subject=?
- )`)
- .bind(id, created, issuer, subject),
- session
- .prepare(`INSERT INTO kiln_identities (issuer, subject, account_id, created_at)
- SELECT ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM kiln_accounts WHERE id=?)
- ON CONFLICT (issuer, subject) DO NOTHING`)
- .bind(issuer, subject, id, created, id),
- session
- .prepare(`SELECT ${accountColumns} FROM kiln_accounts WHERE id=(
- SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=?
- )`)
- .bind(issuer, subject),
- ]);
- const account = results[2]?.results[0];
- if (!account) throw new Error('Account registration failed');
- if (account.state !== 'active') throw new HttpFailure(403, 'Account unavailable');
- return account;
- }
-
- async getAccount(id: string): Promise<KilnAccount | null> {
- if (typeof id !== 'string' || !/^ka_[a-f0-9]{32}$/.test(id))
- throw new HttpFailure(400, 'Invalid account');
- return this.database
- .withSession('first-primary')
- .prepare(`SELECT ${accountColumns} FROM kiln_accounts WHERE id=?`)
- .bind(id)
- .first<KilnAccount>();
- }
-}
diff --git a/hosting/src/admission-worker.ts b/hosting/src/admission-worker.ts
deleted file mode 100644
index aad5d2c9..00000000
--- a/hosting/src/admission-worker.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import { ComputeAdmission, admissionFailure } from './admission';
-import type { KilnNativeRequest } from './request-worker';
-
-interface ComputeBinding {
- ADMISSION: DurableObjectNamespace<KilnAdmission>;
-}
-interface AdmissionEnv extends ComputeBinding {
- REQUESTS: DurableObjectNamespace<KilnNativeRequest>;
- COMPUTE_MAX_CONCURRENT: string;
- COMPUTE_TENANT_PER_MINUTE: string;
- COMPUTE_TENANT_PER_DAY: string;
- COMPUTE_GLOBAL_PER_DAY: string;
- COMPUTE_GLOBAL_PER_MONTH: string;
- COMPUTE_DEADLINE_MS: string;
-}
-
-function limit(value: string): number {
- if (typeof value !== 'string' || !/^[1-9][0-9]*$/.test(value))
- throw new Error('Missing compute policy');
- return Number(value);
-}
-
-export class KilnAdmission extends DurableObject<AdmissionEnv> {
- private readonly admission: ComputeAdmission;
- constructor(ctx: DurableObjectState, env: AdmissionEnv) {
- super(ctx, env);
- this.admission = new ComputeAdmission(
- ctx.storage,
- {
- run: (id, tenant, request, deadline) =>
- env.REQUESTS.getByName(id).run(tenant, request, deadline),
- cancel: async (id) => {
- await env.REQUESTS.getByName(id).cancel();
- },
- },
- {
- maxConcurrent: limit(env.COMPUTE_MAX_CONCURRENT),
- tenantPerMinute: limit(env.COMPUTE_TENANT_PER_MINUTE),
- tenantPerDay: limit(env.COMPUTE_TENANT_PER_DAY),
- globalPerDay: limit(env.COMPUTE_GLOBAL_PER_DAY),
- globalPerMonth: limit(env.COMPUTE_GLOBAL_PER_MONTH),
- deadlineMs: limit(env.COMPUTE_DEADLINE_MS),
- },
- );
- }
- async dispatch(tenant: string, request: Request): Promise<Response> {
- try {
- return await this.admission.dispatch(tenant, request);
- } catch (error) {
- return admissionFailure(error);
- }
- }
- status() {
- return this.admission.status();
- }
- async setPaused(paused: boolean) {
- await this.admission.setPaused(paused);
- return this.admission.status();
- }
- retireTenant(tenant: string): Promise<void> {
- return this.admission.retireTenant(tenant);
- }
- alarm(): Promise<void> {
- return this.admission.alarm();
- }
-}
-
-/** Gateway receives only this binding, never a selectable DO namespace. */
-export class KilnCompute extends WorkerEntrypoint<ComputeBinding> {
- fetch(): Response {
- return new Response('Not found', { status: 404 });
- }
- /** Aggregate read-only health, with no tenant identifiers or operator controls. */
- health() {
- return this.env.ADMISSION.getByName('global-v1').status();
- }
- async dispatch(tenant: string, request: Request): Promise<Response> {
- try {
- return await this.env.ADMISSION.getByName('global-v1').dispatch(tenant, request);
- } catch (error) {
- return admissionFailure(error);
- }
- }
- /** Only the gateway's verified account-deletion controller may call this. */
- retireTenant(tenant: string): Promise<void> {
- return this.env.ADMISSION.getByName('global-v1').retireTenant(tenant);
- }
-}
-
-/** Bind only to an authenticated operator service; never to the public gateway. */
-export class KilnComputeControl extends WorkerEntrypoint<ComputeBinding> {
- fetch(): Response {
- return new Response('Not found', { status: 404 });
- }
- status() {
- return this.env.ADMISSION.getByName('global-v1').status();
- }
- setPaused(paused: boolean) {
- return this.env.ADMISSION.getByName('global-v1').setPaused(paused);
- }
-}
-
-export default {
- fetch(): Response {
- return new Response('Not found', { status: 404 });
- },
-};
diff --git a/hosting/src/admission.ts b/hosting/src/admission.ts
deleted file mode 100644
index 3facb72e..00000000
--- a/hosting/src/admission.ts
+++ /dev/null
@@ -1,391 +0,0 @@
-import { boundedRequest, HttpFailure, privateResponse, serviceFailure } from './http';
-import { nativeRequestHeaders } from './request-job';
-
-const MINUTE = 60_000;
-const DAY = 86_400_000;
-const RECOVERY_DELAY = 30_000;
-const CLEANUP_DEADLINE = 15_000;
-
-export interface ComputePolicy {
- maxConcurrent: number;
- tenantPerMinute: number;
- tenantPerDay: number;
- globalPerDay: number;
- globalPerMonth: number;
- deadlineMs: number;
-}
-export interface ComputePorts {
- run(id: string, tenant: string, request: Request, deadlineAt: number): Promise<Response>;
- cancel(id: string): Promise<void>;
-}
-type Active = {
- id: string;
- tenant: string;
- state: string;
- deadline_at: number;
- recover_at: number;
-};
-type Bucket = { owner: string; period: string; start: number; end: number; limit: number };
-
-class QuotaFailure extends HttpFailure {
- constructor(readonly retryAfter: number) {
- super(429, 'Compute quota or capacity reached');
- }
-}
-export function admissionFailure(error: unknown): Response {
- const response = serviceFailure(error);
- if (error instanceof QuotaFailure) response.headers.set('retry-after', String(error.retryAfter));
- return privateResponse(response);
-}
-
-/** One global SQLite authority. Expiration starts cleanup; it never releases capacity. */
-export class ComputeAdmission {
- private readonly sql: SqlStorage;
- private readonly closing = new Map<string, Promise<void>>();
-
- constructor(
- private readonly storage: DurableObjectStorage,
- private readonly ports: ComputePorts,
- private readonly policy: ComputePolicy,
- private readonly now: () => number = Date.now,
- ) {
- for (const key of [
- 'maxConcurrent',
- 'tenantPerMinute',
- 'tenantPerDay',
- 'globalPerDay',
- 'globalPerMonth',
- 'deadlineMs',
- ] as const) {
- const value = policy[key];
- if (!Number.isSafeInteger(value) || value < 1 || value > 1_000_000)
- throw new Error('Invalid compute policy');
- }
- if (policy.maxConcurrent > 16 || policy.deadlineMs > 120_000)
- throw new Error('Invalid compute capacity');
- this.sql = storage.sql;
- this.sql.exec(`
- CREATE TABLE IF NOT EXISTS compute_format (version INTEGER NOT NULL);
- CREATE TABLE IF NOT EXISTS compute_active (
- id TEXT PRIMARY KEY, tenant TEXT NOT NULL UNIQUE, state TEXT NOT NULL,
- deadline_at INTEGER NOT NULL, recover_at INTEGER NOT NULL
- );
- CREATE INDEX IF NOT EXISTS compute_recovery ON compute_active(recover_at);
- CREATE TABLE IF NOT EXISTS compute_usage (
- owner TEXT NOT NULL, period TEXT NOT NULL, window_start INTEGER NOT NULL,
- used INTEGER NOT NULL, expires_at INTEGER NOT NULL, PRIMARY KEY(owner,period)
- );
- CREATE INDEX IF NOT EXISTS compute_expiry ON compute_usage(expires_at);
- CREATE TABLE IF NOT EXISTS compute_control (id INTEGER PRIMARY KEY, paused INTEGER NOT NULL);
- CREATE TABLE IF NOT EXISTS compute_retired (tenant TEXT PRIMARY KEY NOT NULL);
- INSERT OR IGNORE INTO compute_control VALUES (1,0);
- `);
- const versions = this.sql
- .exec<{ version: number }>('SELECT version FROM compute_format')
- .toArray();
- if (!versions.length) this.sql.exec('INSERT INTO compute_format VALUES (1)');
- else if (versions.length !== 1 || versions[0]?.version !== 1)
- throw new Error('Unsupported compute format');
- }
-
- private active(id: string): Active | undefined {
- return this.sql.exec<Active>('SELECT * FROM compute_active WHERE id = ?', id).toArray()[0];
- }
- private paused(): boolean {
- return (
- this.sql.exec<{ paused: number }>('SELECT paused FROM compute_control WHERE id = 1').one()
- .paused !== 0
- );
- }
- private assertAvailable(tenant: string): void {
- if (this.sql.exec('SELECT 1 FROM compute_retired WHERE tenant=?', tenant).toArray().length)
- throw new HttpFailure(410, 'Account compute has been retired');
- }
- status(): {
- paused: boolean;
- activeRequests: number;
- pendingCleanup: number;
- maxConcurrent: number;
- } {
- const counts = this.sql
- .exec<{ total: number; closing: number }>(
- "SELECT COUNT(*) AS total, COALESCE(SUM(state = 'closing'),0) AS closing FROM compute_active",
- )
- .one();
- return {
- paused: this.paused(),
- activeRequests: counts.total,
- pendingCleanup: counts.closing,
- maxConcurrent: this.policy.maxConcurrent,
- };
- }
- private buckets(tenant: string, now: number): Bucket[] {
- const minute = Math.floor(now / MINUTE) * MINUTE;
- const day = Math.floor(now / DAY) * DAY;
- const date = new Date(now);
- const month = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1);
- const nextMonth = Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1);
- return [
- {
- owner: tenant,
- period: 'minute',
- start: minute,
- end: minute + MINUTE,
- limit: this.policy.tenantPerMinute,
- },
- { owner: tenant, period: 'day', start: day, end: day + DAY, limit: this.policy.tenantPerDay },
- {
- owner: 'global',
- period: 'day',
- start: day,
- end: day + DAY,
- limit: this.policy.globalPerDay,
- },
- {
- owner: 'global',
- period: 'month',
- start: month,
- end: nextMonth,
- limit: this.policy.globalPerMonth,
- },
- ];
- }
-
- // Call inside a storage transaction so records and their recovery alarm commit together.
- private async schedule(): Promise<void> {
- const active = this.sql
- .exec<{ at: number | null }>('SELECT MIN(recover_at) AS at FROM compute_active')
- .one().at;
- const expiry = this.sql
- .exec<{ at: number | null }>('SELECT MIN(expires_at) AS at FROM compute_usage')
- .one().at;
- const maintenance = expiry === null ? Infinity : Math.max(this.now() + RECOVERY_DELAY, expiry);
- const next = Math.min(active ?? Infinity, maintenance);
- if (Number.isFinite(next)) await this.storage.setAlarm(next);
- else await this.storage.deleteAlarm();
- }
-
- private async reserve(tenant: string): Promise<Active> {
- return this.storage.transaction(async () => {
- const now = this.now();
- this.assertAvailable(tenant);
- if (this.paused()) throw new HttpFailure(503, 'Compute is temporarily paused');
- const count = this.sql
- .exec<{ total: number }>('SELECT COUNT(*) AS total FROM compute_active')
- .one().total;
- if (
- count >= this.policy.maxConcurrent ||
- this.sql.exec('SELECT 1 FROM compute_active WHERE tenant = ?', tenant).toArray().length
- )
- throw new QuotaFailure(30);
- const buckets = this.buckets(tenant, now).map((bucket) => {
- const existing = this.sql
- .exec<{ window_start: number; used: number }>(
- 'SELECT window_start,used FROM compute_usage WHERE owner = ? AND period = ?',
- bucket.owner,
- bucket.period,
- )
- .toArray()[0];
- const used = existing?.window_start === bucket.start ? existing.used : 0;
- if (used >= bucket.limit)
- throw new QuotaFailure(Math.max(1, Math.ceil((bucket.end - now) / 1000)));
- return { ...bucket, used };
- });
- for (const bucket of buckets)
- this.sql.exec(
- 'INSERT OR REPLACE INTO compute_usage VALUES (?,?,?,?,?)',
- bucket.owner,
- bucket.period,
- bucket.start,
- bucket.used + 1,
- bucket.end,
- );
- const record: Active = {
- id: crypto.randomUUID(),
- tenant,
- state: 'running',
- deadline_at: now + this.policy.deadlineMs,
- recover_at: now + this.policy.deadlineMs,
- };
- this.sql.exec(
- 'INSERT INTO compute_active VALUES (?,?,?,?,?)',
- record.id,
- record.tenant,
- record.state,
- record.deadline_at,
- record.recover_at,
- );
- await this.schedule();
- return record;
- });
- }
-
- async dispatch(tenant: string, request: Request): Promise<Response> {
- nativeRequestHeaders(tenant, request);
- const bounded = await boundedRequest(request, 1024 * 1024);
- if (request.signal.aborted) throw new HttpFailure(499, 'Request cancelled');
- const record = await this.reserve(tenant);
- let response: Response | undefined;
- let received: Response | undefined;
- let timer: ReturnType<typeof setTimeout> | undefined;
- let onAbort: () => void = () => {};
- let done = false;
- let failed = false;
- let failure: unknown;
- try {
- this.assertAvailable(tenant);
- // Pause/recovery may have run while the durable reservation was committing.
- if (this.paused() || this.active(record.id)?.state !== 'running')
- throw new HttpFailure(503, 'Compute is temporarily paused');
- if (this.now() >= record.deadline_at) throw new HttpFailure(504, 'Compute timed out');
- if (request.signal.aborted) throw new HttpFailure(499, 'Request cancelled');
- const cancelled = new Promise<never>((_, reject) => {
- onAbort = () => reject(new HttpFailure(499, 'Request cancelled'));
- request.signal.addEventListener('abort', onAbort, { once: true });
- timer = setTimeout(
- () => reject(new HttpFailure(504, 'Compute timed out')),
- Math.max(0, record.deadline_at - this.now()),
- );
- });
- const pending = this.ports
- .run(record.id, tenant, bounded, record.deadline_at)
- .then((result) => {
- received = result;
- if (done) void result.body?.cancel().catch(() => {});
- return result;
- });
- response = await Promise.race([pending, cancelled]);
- if (this.now() >= record.deadline_at) throw new HttpFailure(504, 'Compute timed out');
- } catch (error) {
- failed = true;
- failure = error;
- } finally {
- done = true;
- if (timer !== undefined) clearTimeout(timer);
- request.signal.removeEventListener('abort', onAbort);
- }
- if (failed) void received?.body?.cancel().catch(() => {});
- // Failed cleanup takes precedence over any response, including successful work.
- try {
- await this.close(record.id);
- } catch (error) {
- void received?.body?.cancel().catch(() => {});
- throw error;
- }
- if (failed) {
- throw failure;
- }
- // A completed result cannot escape after account retirement interleaved with
- // the run or its verified cleanup. Previously delivered bytes cannot be recalled.
- try {
- this.assertAvailable(tenant);
- } catch (error) {
- void response?.body?.cancel().catch(() => {});
- throw error;
- }
- if (!response) throw new Error('Missing compute result');
- return response;
- }
-
- private close(id: string): Promise<void> {
- const existing = this.closing.get(id);
- if (existing) return existing;
- const work = this.closeOnce(id);
- this.closing.set(id, work);
- const clear = () => {
- if (this.closing.get(id) === work) this.closing.delete(id);
- };
- void work.then(clear, clear);
- return work;
- }
-
- private async closeOnce(id: string): Promise<void> {
- const present = await this.storage.transaction(async () => {
- if (!this.active(id)) return false;
- this.sql.exec(
- "UPDATE compute_active SET state = 'closing', recover_at = ? WHERE id = ?",
- this.now() + RECOVERY_DELAY,
- id,
- );
- await this.schedule();
- return true;
- });
- if (!present) return;
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- // This acknowledgement includes the coordinator and all of its children.
- // The parent's durable cancellation fence also prevents a late run RPC.
- await Promise.race([
- this.ports.cancel(id),
- new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(new Error('Cleanup not confirmed')), CLEANUP_DEADLINE);
- }),
- ]);
- await this.storage.transaction(async () => {
- this.sql.exec('DELETE FROM compute_active WHERE id = ?', id);
- await this.schedule();
- });
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
- }
-
- async setPaused(paused: boolean): Promise<void> {
- if (typeof paused !== 'boolean') throw new Error('Invalid pause setting');
- const active = await this.storage.transaction(async () => {
- this.sql.exec('UPDATE compute_control SET paused = ? WHERE id = 1', paused ? 1 : 0);
- const active = paused ? this.sql.exec<Active>('SELECT * FROM compute_active').toArray() : [];
- if (paused)
- this.sql.exec("UPDATE compute_active SET state = 'closing', recover_at = ?", this.now());
- await this.schedule();
- return active;
- });
- await Promise.allSettled(active.map((row) => this.close(row.id)));
- }
-
- /** Permanent account-deletion fence, followed by verified whole-request cleanup. */
- async retireTenant(tenant: string): Promise<void> {
- if (typeof tenant !== 'string' || !/^[A-Za-z0-9_-]{43}(?![\s\S])/.test(tenant))
- throw new HttpFailure(400, 'Invalid compute identity');
- const active = await this.storage.transaction(async () => {
- this.sql.exec('INSERT OR IGNORE INTO compute_retired VALUES (?)', tenant);
- const active = this.sql
- .exec<Active>('SELECT * FROM compute_active WHERE tenant=?', tenant)
- .toArray()[0];
- if (active)
- this.sql.exec(
- "UPDATE compute_active SET state='closing',recover_at=? WHERE id=?",
- this.now(),
- active.id,
- );
- await this.schedule();
- return active;
- });
- // Cleanup failure deliberately rejects: a caller must not proceed as if the
- // tenant is drained. The deny and the active lease survive eviction/retry.
- if (active) await this.close(active.id);
- await this.storage.transaction(async () => {
- if (this.sql.exec('SELECT 1 FROM compute_active WHERE tenant=?', tenant).toArray().length)
- throw new Error('Account compute cleanup is not confirmed');
- this.sql.exec('DELETE FROM compute_usage WHERE owner=?', tenant);
- // Global counters retain the cost of admitted work. The opaque deny record
- // persists without its own alarm and cannot be cleared by pause/resume.
- await this.schedule();
- });
- }
-
- async alarm(): Promise<void> {
- const due = this.sql
- .exec<Active>('SELECT * FROM compute_active WHERE recover_at <= ?', this.now())
- .toArray();
- await Promise.allSettled(due.map((row) => this.close(row.id)));
- await this.storage.transaction(async () => {
- // Bound each maintenance batch, including after a long idle period.
- this.sql.exec(
- 'DELETE FROM compute_usage WHERE rowid IN (SELECT rowid FROM compute_usage WHERE expires_at <= ? LIMIT 256)',
- this.now(),
- );
- await this.schedule();
- });
- }
-}
diff --git a/hosting/src/artifact-store.ts b/hosting/src/artifact-store.ts
deleted file mode 100644
index 099af470..00000000
--- a/hosting/src/artifact-store.ts
+++ /dev/null
@@ -1,681 +0,0 @@
-import { HttpFailure } from './http';
-
-const DAY = 24 * 60 * 60 * 1000;
-const UPLOAD_GRACE = 15 * 60 * 1000;
-const filenamePattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/;
-const idPattern = /^[a-f0-9]{32}$/;
-const mediaTypes = new Set([
- 'application/octet-stream',
- 'model/gltf-binary',
- 'image/png',
- 'application/javascript',
- 'application/json',
- 'application/zip',
-]);
-type ArtifactRow = {
- id: string;
- object_key: string;
- sha256: string;
- bytes: number;
- filename: string;
- media_type: string;
- created_at: number;
- expires_at: number;
- state: string;
-};
-type GroupRow = {
- id: string;
- logical_key: string;
- metadata: string;
- files: string;
- bytes: number;
- created_at: number;
-};
-
-export interface StoragePolicy {
- maxBytes: number;
- maxObjects: number;
- maxGroups: number;
-}
-
-export class ArtifactStore {
- private readonly sql: SqlStorage;
- private readonly prefix: string;
- private purging?: Promise<ReturnType<ArtifactStore['retirementStatus']>>;
-
- constructor(
- private readonly ctx: DurableObjectState,
- private readonly bucket: R2Bucket,
- private readonly policy: StoragePolicy,
- private readonly now: () => number = Date.now,
- private readonly uploadDeadlineMs = 60_000,
- ) {
- for (const limit of Object.values(policy)) {
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1024 ** 4)
- throw new Error('Invalid storage policy');
- }
- if (
- !Number.isSafeInteger(uploadDeadlineMs) ||
- uploadDeadlineMs < 1 ||
- uploadDeadlineMs > 60_000
- ) {
- throw new Error('Invalid upload deadline');
- }
- this.sql = ctx.storage.sql;
- this.prefix = `tenants/${ctx.id.toString()}/artifacts/`;
- this.sql.exec('CREATE TABLE IF NOT EXISTS storage_format (version INTEGER NOT NULL)');
- const version = this.sql
- .exec<{ version: number }>('SELECT version FROM storage_format')
- .toArray();
- if (!version.length) this.sql.exec('INSERT INTO storage_format VALUES (1)');
- else if (version.length !== 1 || version[0]?.version !== 1)
- throw new Error('Unsupported storage format');
- this.sql.exec(`CREATE TABLE IF NOT EXISTS artifacts (
- id TEXT PRIMARY KEY, object_key TEXT NOT NULL UNIQUE, sha256 TEXT NOT NULL,
- bytes INTEGER NOT NULL, filename TEXT NOT NULL, media_type TEXT NOT NULL,
- created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, state TEXT NOT NULL
- );
- CREATE TABLE IF NOT EXISTS saved_groups (
- id TEXT PRIMARY KEY, logical_key TEXT NOT NULL UNIQUE, metadata TEXT NOT NULL,
- files TEXT NOT NULL, bytes INTEGER NOT NULL, created_at INTEGER NOT NULL
- );
- CREATE TABLE IF NOT EXISTS group_files (
- group_id TEXT NOT NULL, filename TEXT NOT NULL, artifact_id TEXT NOT NULL,
- PRIMARY KEY (group_id, filename)
- );
- CREATE INDEX IF NOT EXISTS artifact_pins ON group_files(artifact_id);
- CREATE INDEX IF NOT EXISTS artifact_expiry ON artifacts(state, expires_at);
- CREATE INDEX IF NOT EXISTS artifact_content ON artifacts(sha256, filename, media_type);
- CREATE TABLE IF NOT EXISTS maintenance (id INTEGER PRIMARY KEY, cursor TEXT NOT NULL);
- CREATE TABLE IF NOT EXISTS storage_retirement (id INTEGER PRIMARY KEY, state TEXT NOT NULL);
- CREATE TABLE IF NOT EXISTS artifact_writes (artifact_id TEXT PRIMARY KEY NOT NULL)`);
- }
-
- retirementStatus() {
- const state =
- this.sql
- .exec<{ state: 'retiring' | 'purged' }>('SELECT state FROM storage_retirement WHERE id=1')
- .toArray()[0]?.state ?? 'active';
- return {
- state,
- pendingWrites: this.sql.exec<{ n: number }>('SELECT COUNT(*) AS n FROM artifact_writes').one()
- .n,
- remainingObjects: this.sql.exec<{ n: number }>('SELECT COUNT(*) AS n FROM artifacts').one().n,
- };
- }
-
- assertActive(): void {
- if (this.sql.exec('SELECT 1 FROM storage_retirement WHERE id=1').toArray().length)
- throw new HttpFailure(410, 'Account storage has been retired');
- }
-
- /** Caller must first revoke account access and verify compute retirement. */
- async retire(revokeDownloads: () => void = () => {}) {
- await this.ctx.storage.transaction(async () => {
- this.sql.exec("INSERT OR IGNORE INTO storage_retirement VALUES (1,'retiring')");
- // The tenant's ticket store shares this SQLite transaction. No issuance
- // can interleave between revocation and the durable storage deny.
- revokeDownloads();
- // Preserve evidence of old interrupted uploads too. Absence in R2 alone is
- // not proof that an unacknowledged write can no longer arrive.
- this.sql.exec(
- "INSERT OR IGNORE INTO artifact_writes SELECT id FROM artifacts WHERE state='uploading'",
- );
- this.sql.exec("UPDATE artifacts SET state='deleting'");
- this.sql.exec('DELETE FROM group_files; DELETE FROM saved_groups; DELETE FROM maintenance');
- if (this.retirementStatus().state !== 'purged') await this.schedule(this.now() + 30_000);
- });
- return this.purge();
- }
-
- purge(): Promise<ReturnType<ArtifactStore['retirementStatus']>> {
- if (this.purging) return this.purging;
- const work = this.purgeOnce();
- this.purging = work;
- const clear = () => {
- if (this.purging === work) this.purging = undefined;
- };
- void work.then(clear, clear);
- return work;
- }
-
- private async purgeOnce() {
- if (this.retirementStatus().state === 'active')
- throw new HttpFailure(409, 'Storage is not retired');
- let retry = 30_000;
- try {
- // A matching immutable R2 object is positive evidence that its unique,
- // create-only put committed. This also recovers a lost acknowledgement.
- const pending = this.sql
- .exec<ArtifactRow>(`SELECT a.* FROM artifacts a
- JOIN artifact_writes w ON w.artifact_id=a.id LIMIT 32`)
- .toArray();
- for (const row of pending) {
- await this.settleCommittedWrite(row);
- }
- const candidates = this.sql
- .exec<ArtifactRow>(`SELECT * FROM artifacts a
- WHERE NOT EXISTS (SELECT 1 FROM artifact_writes w WHERE w.artifact_id=a.id) LIMIT 32`)
- .toArray();
- if (candidates.length) {
- await this.bucket.delete(candidates.map((row) => row.object_key));
- for (const row of candidates) this.sql.exec('DELETE FROM artifacts WHERE id=?', row.id);
- }
- // Delete all retired-prefix orphans, including recent/nonstandard keys.
- // Never delete a key whose put is still unresolved, or any other prefix.
- const listing = await this.bucket.list({ prefix: this.prefix, limit: 100 });
- const keys = listing.objects
- .filter(
- (object) =>
- !this.sql
- .exec(
- 'SELECT 1 FROM artifact_writes WHERE artifact_id=?',
- object.key.slice(this.prefix.length),
- )
- .toArray().length,
- )
- .map((object) => object.key);
- if (keys.length) await this.bucket.delete(keys);
- const status = this.retirementStatus();
- if (!status.pendingWrites && !status.remainingObjects) {
- const remaining = await this.bucket.list({ prefix: this.prefix, limit: 1 });
- if (!remaining.objects.length && !remaining.truncated)
- this.sql.exec("UPDATE storage_retirement SET state='purged' WHERE id=1");
- }
- if (listing.truncated || candidates.length === 32) retry = 10_000;
- // Unknown writes after a crash retain a daily recovery alarm. They are not
- // declared erased based on a timeout. Positive commit evidence or a live
- // failed-put acknowledgement can settle them on a later pass.
- else if (this.retirementStatus().pendingWrites) retry = DAY;
- return this.retirementStatus();
- } finally {
- await this.ctx.storage.transaction(async () => {
- if (this.retirementStatus().state === 'purged') await this.ctx.storage.deleteAlarm();
- else await this.schedule(this.now() + retry);
- });
- }
- }
-
- private pendingWrite(id: string): boolean {
- return (
- this.sql.exec('SELECT 1 FROM artifact_writes WHERE artifact_id=?', id).toArray().length > 0
- );
- }
-
- private async settleCommittedWrite(row: ArtifactRow): Promise<void> {
- if (!this.pendingWrite(row.id)) return;
- const object = await this.bucket.head(row.object_key);
- const digest = object?.checksums.sha256;
- const hex = digest
- ? Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')
- : '';
- if (object && object.size === row.bytes && hex === row.sha256)
- this.sql.exec('DELETE FROM artifact_writes WHERE artifact_id=?', row.id);
- }
-
- private artifact(id: string): ArtifactRow | undefined {
- if (!idPattern.test(id)) return undefined;
- return this.sql.exec<ArtifactRow>('SELECT * FROM artifacts WHERE id = ?', id).toArray()[0];
- }
-
- private pinned(id: string): boolean {
- return (
- this.sql.exec('SELECT 1 FROM group_files WHERE artifact_id = ? LIMIT 1', id).toArray()
- .length > 0
- );
- }
-
- private readable(row: ArtifactRow | undefined): row is ArtifactRow {
- return (
- !this.sql.exec('SELECT 1 FROM storage_retirement WHERE id=1').toArray().length &&
- !!row &&
- row.state === 'ready' &&
- (row.expires_at > this.now() || this.pinned(row.id))
- );
- }
-
- usage() {
- const objects = this.sql
- .exec<{ bytes: number; objects: number }>(
- 'SELECT COALESCE(SUM(bytes), 0) AS bytes, COUNT(*) AS objects FROM artifacts',
- )
- .one();
- const groups = this.sql
- .exec<{ metadataBytes: number; groups: number }>(
- 'SELECT COALESCE(SUM(bytes), 0) AS metadataBytes, COUNT(*) AS groups FROM saved_groups',
- )
- .one();
- return {
- ...objects,
- ...groups,
- totalBytes: objects.bytes + groups.metadataBytes,
- limits: this.policy,
- };
- }
-
- private receipt(row: ArtifactRow) {
- return {
- id: row.id,
- sha256: row.sha256,
- bytes: row.bytes,
- filename: row.filename,
- mediaType: row.media_type,
- createdAt: row.created_at,
- expiresAt: this.pinned(row.id) ? null : row.expires_at,
- };
- }
-
- private async schedule(at = this.now() + DAY): Promise<void> {
- const existing = await this.ctx.storage.getAlarm();
- // An older upload or maintenance pass may resume after account retirement.
- if (this.retirementStatus().state === 'purged') return;
- if (existing === null || existing > at) await this.ctx.storage.setAlarm(at);
- }
-
- findContent(sha256: string, filename: string, mediaType: string) {
- const rows = this.sql
- .exec<ArtifactRow>(
- "SELECT * FROM artifacts WHERE sha256 = ? AND filename = ? AND media_type = ? AND state = 'ready' ORDER BY created_at DESC",
- sha256,
- filename,
- mediaType,
- )
- .toArray();
- const row = rows.find((candidate) => this.readable(candidate));
- return row ? this.receipt(row) : undefined;
- }
-
- contentStats(filename: string, mediaType: string) {
- const rows = this.sql
- .exec<{ bytes: number }>(
- `SELECT MAX(bytes) AS bytes FROM artifacts
- WHERE filename = ? AND media_type = ? AND state = 'ready'
- AND (expires_at > ? OR EXISTS (SELECT 1 FROM group_files WHERE artifact_id = artifacts.id))
- GROUP BY sha256`,
- filename,
- mediaType,
- this.now(),
- )
- .toArray();
- return { entries: rows.length, bytes: rows.reduce((sum, row) => sum + row.bytes, 0) };
- }
-
- async upload(request: Request) {
- this.assertActive();
- const rawSize = request.headers.get('content-length') ?? '';
- const bytes = Number(rawSize);
- const sha256 = request.headers.get('x-artifact-sha256') ?? '';
- const filename = request.headers.get('x-artifact-name') ?? '';
- const mediaType = request.headers.get('content-type') ?? '';
- if (
- !/^\d+$/.test(rawSize) ||
- !Number.isSafeInteger(bytes) ||
- bytes > 64 * 1024 * 1024 ||
- !/^[a-f0-9]{64}$/.test(sha256) ||
- !filenamePattern.test(filename) ||
- !mediaTypes.has(mediaType)
- ) {
- throw new HttpFailure(400, 'Invalid artifact declaration');
- }
- // Schedule recovery before reserving storage or starting an external write.
- await this.schedule(this.now() + UPLOAD_GRACE);
- const id = crypto.randomUUID().replace(/-/g, '');
- const createdAt = this.now();
- const row: ArtifactRow = {
- id,
- object_key: this.prefix + id,
- sha256,
- bytes,
- filename,
- media_type: mediaType,
- created_at: createdAt,
- expires_at: createdAt + 7 * DAY,
- state: 'uploading',
- };
- this.ctx.storage.transactionSync(() => {
- this.assertActive();
- const usage = this.usage();
- if (
- usage.objects >= this.policy.maxObjects ||
- usage.totalBytes + bytes > this.policy.maxBytes
- ) {
- throw new HttpFailure(507, 'Tenant storage quota exceeded');
- }
- this.sql.exec(
- 'INSERT INTO artifacts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
- id,
- row.object_key,
- sha256,
- bytes,
- filename,
- mediaType,
- row.created_at,
- row.expires_at,
- row.state,
- );
- this.sql.exec('INSERT INTO artifact_writes VALUES (?)', id);
- });
- const abort = new AbortController();
- let timer: ReturnType<typeof setTimeout> | undefined;
- let timedOut = false;
- const timeout = new Promise<never>((_, reject) => {
- timer = setTimeout(() => {
- timedOut = true;
- abort.abort();
- reject(new Error('Upload deadline exceeded'));
- }, this.uploadDeadlineMs);
- });
- const fixed = new FixedLengthStream(bytes);
- const pipe = (request.body ?? new Blob([]).stream()).pipeTo(fixed.writable, {
- signal: abort.signal,
- });
- const put = Promise.resolve()
- .then(() => {
- this.assertActive();
- return this.bucket.put(row.object_key, fixed.readable, {
- sha256,
- onlyIf: { etagDoesNotMatch: '*' },
- httpMetadata: { contentType: mediaType },
- });
- })
- .finally(() => {
- this.sql.exec('DELETE FROM artifact_writes WHERE artifact_id=?', id);
- });
- try {
- const [, stored] = await Promise.race([Promise.all([pipe, put]), timeout]);
- if (!stored || stored.size !== bytes) throw new Error('Artifact write did not complete');
- this.assertActive();
- const updated = this.sql
- .exec<{ id: string }>(
- "UPDATE artifacts SET state = 'ready' WHERE id = ? AND state = 'uploading' RETURNING id",
- id,
- )
- .toArray();
- if (!updated.length) throw new Error('Upload reservation expired');
- row.state = 'ready';
- return this.receipt(row);
- } catch {
- abort.abort();
- // A failed/unknown write is never visible. Its durable deletion intent keeps
- // quota reserved until R2 cleanup succeeds, and alarms retry after a crash.
- this.sql.exec("UPDATE artifacts SET state = 'deleting' WHERE id = ?", id);
- const cleanup = (async () => {
- await Promise.allSettled([pipe, put]);
- this.sql.exec('DELETE FROM artifact_writes WHERE artifact_id=?', id);
- try {
- await this.bucket.delete(row.object_key);
- this.sql.exec("DELETE FROM artifacts WHERE id = ? AND state = 'deleting'", id);
- } catch {
- /* Retain intent and reserved quota until maintenance succeeds. */
- }
- })();
- // R2 does not expose cancellation of a put. A late acknowledgement may only
- // trigger cleanup; it cannot make this request successful or publish bytes.
- this.ctx.waitUntil(cleanup);
- if (!timedOut) {
- try {
- await Promise.race([cleanup, timeout]);
- } catch {
- /* Alarm owns recovery. */
- }
- }
- throw new HttpFailure(502, 'Artifact upload failed integrity or storage checks');
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
- }
-
- async download(id: string, head = false): Promise<Response> {
- const row = this.artifact(id);
- if (!this.readable(row)) throw new HttpFailure(404, 'Artifact not found');
- let object: R2Object | null;
- let body: ReadableStream | null = null;
- if (head) object = await this.bucket.head(row.object_key);
- else {
- const loaded = await this.bucket.get(row.object_key);
- object = loaded;
- body = loaded?.body ?? null;
- }
- const checksum = object?.checksums.sha256;
- const hex = checksum
- ? Array.from(new Uint8Array(checksum), (byte) => byte.toString(16).padStart(2, '0')).join('')
- : '';
- if (!object || object.size !== row.bytes || hex !== row.sha256) {
- void body?.cancel().catch(() => {});
- throw new HttpFailure(502, 'Stored artifact integrity check failed');
- }
- // Recheck after the external read: deletion can interleave with an R2 await.
- if (!this.readable(this.artifact(id))) {
- void body?.cancel().catch(() => {});
- throw new HttpFailure(404, 'Artifact not found');
- }
- return new Response(body, {
- headers: {
- 'content-type': row.media_type,
- 'content-length': String(row.bytes),
- etag: `"${row.sha256}"`,
- 'content-disposition': `attachment; filename="${row.filename}"`,
- 'cache-control': 'private, no-store',
- 'x-content-type-options': 'nosniff',
- 'content-security-policy': "default-src 'none'; sandbox",
- },
- });
- }
-
- assertFileNames(files: Record<string, string>): void {
- for (const [name, id] of Object.entries(files)) {
- const row = this.artifact(id);
- if (!this.readable(row)) throw new HttpFailure(404, 'Artifact not found');
- if (row.filename !== name) throw new HttpFailure(400, 'Saved filename mismatch');
- }
- }
-
- save(input: unknown, conditions: { parentKey?: string; absentPrefix?: string } = {}) {
- this.assertActive();
- if (!input || typeof input !== 'object' || Array.isArray(input))
- throw new HttpFailure(400, 'Invalid saved revision');
- const { key, files, metadata } = input as Record<string, unknown>;
- if (
- typeof key !== 'string' ||
- !/^[A-Za-z0-9_./-]{1,240}$/.test(key) ||
- !files ||
- typeof files !== 'object' ||
- Array.isArray(files)
- )
- throw new HttpFailure(400, 'Invalid saved revision');
- const entries = Object.entries(files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
- if (
- !entries.length ||
- entries.length > 256 ||
- entries.some(
- ([name, id]) =>
- !filenamePattern.test(name) || typeof id !== 'string' || !idPattern.test(id),
- )
- ) {
- throw new HttpFailure(400, 'Invalid saved file inventory');
- }
- const filesJson = JSON.stringify(Object.fromEntries(entries));
- const metadataJson = JSON.stringify(metadata ?? {});
- const bytes = new TextEncoder().encode(key + filesJson + metadataJson).byteLength;
- if (bytes > 65_536) throw new HttpFailure(413, 'Saved metadata too large');
- return this.ctx.storage.transactionSync(() => {
- const existing = this.sql
- .exec<GroupRow>('SELECT * FROM saved_groups WHERE logical_key = ?', key)
- .toArray()[0];
- if (existing) {
- if (existing.files !== filesJson || existing.metadata !== metadataJson)
- throw new HttpFailure(409, 'Saved revision is immutable');
- return { created: false, record: this.groupReceipt(existing) };
- }
- if (conditions.parentKey) this.groupByKey(conditions.parentKey);
- if (conditions.absentPrefix && this.groupPage(conditions.absentPrefix).records.length)
- throw new HttpFailure(409, 'An existing asset requires parentRevision');
- for (const [, id] of entries)
- if (!this.readable(this.artifact(id as string)))
- throw new HttpFailure(404, 'Artifact not found');
- const usage = this.usage();
- if (usage.groups >= this.policy.maxGroups || usage.totalBytes + bytes > this.policy.maxBytes)
- throw new HttpFailure(507, 'Tenant storage quota exceeded');
- const row: GroupRow = {
- id: crypto.randomUUID().replace(/-/g, ''),
- logical_key: key,
- files: filesJson,
- metadata: metadataJson,
- bytes,
- created_at: this.now(),
- };
- this.sql.exec(
- 'INSERT INTO saved_groups VALUES (?, ?, ?, ?, ?, ?)',
- row.id,
- key,
- metadataJson,
- filesJson,
- bytes,
- row.created_at,
- );
- for (const [name, id] of entries)
- this.sql.exec('INSERT INTO group_files VALUES (?, ?, ?)', row.id, name, id as string);
- return { created: true, record: this.groupReceipt(row) };
- });
- }
-
- private groupReceipt(row: GroupRow) {
- return {
- id: row.id,
- key: row.logical_key,
- files: JSON.parse(row.files) as Record<string, string>,
- metadata: JSON.parse(row.metadata) as unknown,
- createdAt: row.created_at,
- };
- }
-
- group(id: string) {
- const row = this.sql.exec<GroupRow>('SELECT * FROM saved_groups WHERE id = ?', id).toArray()[0];
- if (!row) throw new HttpFailure(404, 'Saved revision not found');
- return this.groupReceipt(row);
- }
-
- groupByKey(key: string) {
- const row = this.sql
- .exec<GroupRow>('SELECT * FROM saved_groups WHERE logical_key = ?', key)
- .toArray()[0];
- if (!row) throw new HttpFailure(404, 'Saved revision not found');
- return this.groupReceipt(row);
- }
-
- groupPage(prefix: string, after = '') {
- const rows = this.sql
- .exec<GroupRow>(
- `SELECT * FROM saved_groups WHERE logical_key >= ? AND logical_key < ? AND logical_key > ?
- ORDER BY logical_key LIMIT 33`,
- prefix,
- `${prefix}\uffff`,
- after,
- )
- .toArray();
- return {
- records: rows.slice(0, 32).map((row) => this.groupReceipt(row)),
- next: rows.length > 32 ? rows[31]!.logical_key : null,
- };
- }
-
- async deleteGroup(id: string): Promise<void> {
- await this.schedule(this.now() + 60_000);
- this.ctx.storage.transactionSync(() => {
- const group = this.group(id);
- this.sql.exec('DELETE FROM group_files WHERE group_id = ?', id);
- this.sql.exec('DELETE FROM saved_groups WHERE id = ?', id);
- for (const artifact of new Set(Object.values(group.files))) {
- if (!this.pinned(artifact))
- this.sql.exec("UPDATE artifacts SET state = 'deleting' WHERE id = ?", artifact);
- }
- });
- await this.sweep();
- }
-
- async discard(input: unknown): Promise<void> {
- if (
- !Array.isArray(input) ||
- input.length > 16 ||
- input.some((id) => typeof id !== 'string' || !idPattern.test(id))
- )
- throw new HttpFailure(400, 'Invalid staging inventory');
- await this.schedule(this.now() + 60_000);
- this.ctx.storage.transactionSync(() => {
- for (const id of input)
- if (!this.pinned(id))
- this.sql.exec(
- "UPDATE artifacts SET state = 'deleting' WHERE id = ? AND state = 'ready'",
- id,
- );
- });
- await this.sweep();
- }
-
- async sweep(): Promise<{ removed: number }> {
- if (this.retirementStatus().state !== 'active') {
- const before = this.retirementStatus().remainingObjects;
- const after = await this.purge();
- return { removed: before - after.remainingObjects };
- }
- const now = this.now();
- let removed = 0;
- try {
- let candidates = this.sql
- .exec<ArtifactRow>(
- `SELECT * FROM artifacts WHERE state = 'deleting'
- OR (state = 'uploading' AND created_at <= ?)
- OR (state = 'ready' AND expires_at <= ? AND NOT EXISTS
- (SELECT 1 FROM group_files WHERE artifact_id = artifacts.id))
- ORDER BY EXISTS (SELECT 1 FROM artifact_writes WHERE artifact_id=artifacts.id)
- LIMIT 32`,
- now - UPLOAD_GRACE,
- now,
- )
- .toArray();
- for (const row of candidates)
- this.sql.exec("UPDATE artifacts SET state = 'deleting' WHERE id = ?", row.id);
- for (const row of candidates) await this.settleCommittedWrite(row);
- if (this.retirementStatus().state !== 'active') return { removed };
- candidates = candidates.filter((row) => !this.pendingWrite(row.id));
- if (candidates.length) {
- await this.bucket.delete(candidates.map((row) => row.object_key));
- this.ctx.storage.transactionSync(() => {
- for (const row of candidates)
- this.sql.exec("DELETE FROM artifacts WHERE id = ? AND state = 'deleting'", row.id);
- });
- removed += candidates.length;
- }
- // Reconcile aged orphan objects after a crash between an R2 write and its
- // local acknowledgement. Never scan or delete outside this tenant prefix.
- const cursor = this.sql
- .exec<{ cursor: string }>('SELECT cursor FROM maintenance WHERE id = 1')
- .toArray()[0]?.cursor;
- const listing = await this.bucket.list({
- prefix: this.prefix,
- limit: 100,
- cursor: cursor || undefined,
- });
- if (this.retirementStatus().state !== 'active') return { removed };
- const orphans = listing.objects.filter(
- (object) =>
- object.uploaded.getTime() <= now - UPLOAD_GRACE &&
- idPattern.test(object.key.slice(this.prefix.length)) &&
- !this.artifact(object.key.slice(this.prefix.length)),
- );
- if (orphans.length) await this.bucket.delete(orphans.map((object) => object.key));
- if (this.retirementStatus().state !== 'active') return { removed };
- this.sql.exec(
- 'INSERT OR REPLACE INTO maintenance VALUES (1, ?)',
- listing.truncated ? listing.cursor : '',
- );
- removed += orphans.length;
- if (candidates.length === 32 || listing.truncated) await this.schedule(now + 10_000);
- return { removed };
- } finally {
- // Daily reconciliation also covers a late orphan after a prior interrupted
- // request. An operator account-deletion flow must retire this alarm last.
- await this.schedule(now + DAY);
- }
- }
-}
diff --git a/hosting/src/asset-downloads.ts b/hosting/src/asset-downloads.ts
deleted file mode 100644
index b9b04bb1..00000000
--- a/hosting/src/asset-downloads.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import type { ArtifactStore } from './artifact-store';
-import type { AssetIndex } from './asset-index';
-import { HttpFailure, sha256 } from './http';
-import { DOWNLOAD_FILES, DOWNLOAD_TOKEN } from './download-path';
-
-const LIFETIME_MS = 600_000;
-const MAX_TICKETS = 128;
-const MAX_TRANSFERS = 32;
-const denied = () => new HttpFailure(404, 'Download link unavailable; request a new link');
-type Ticket = { token_hash: string; group_id: string; expires_at: number; uses: number };
-
-/**
- * Tenant-local download selection, not authentication. The browser gateway must
- * select this tenant from a current signed-in account before presenting a ticket.
- * A link alone never authorizes a caller to select another tenant or an R2 key.
- */
-export class AssetDownloadTickets {
- private readonly sql: SqlStorage;
- constructor(
- private readonly storage: DurableObjectStorage,
- private readonly artifacts: Pick<ArtifactStore, 'group' | 'download'>,
- private readonly assets: Pick<AssetIndex, 'read'>,
- private readonly now: () => number = Date.now,
- ) {
- this.sql = storage.sql;
- this.sql.exec(`CREATE TABLE IF NOT EXISTS asset_download_tickets (
- token_hash TEXT PRIMARY KEY NOT NULL,
- group_id TEXT NOT NULL,
- expires_at INTEGER NOT NULL,
- uses INTEGER NOT NULL DEFAULT 0 CHECK (uses >= 0 AND uses <= 32)
- );
- CREATE INDEX IF NOT EXISTS asset_download_expiry ON asset_download_tickets(expires_at)`);
- }
-
- revokeAll(): void {
- this.sql.exec('DELETE FROM asset_download_tickets');
- }
-
- async issue(collection: unknown, assetId: unknown, revisionId: unknown) {
- const group = this.assets.read(collection, assetId, revisionId);
- const files = Object.keys(group.files).sort();
- if (!files.length || files.some((name) => !DOWNLOAD_FILES.has(name))) throw denied();
- const token = Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) =>
- byte.toString(16).padStart(2, '0'),
- ).join('');
- const tokenHash = await this.hash(token);
- const expiresAt = this.now() + LIFETIME_MS;
- this.storage.transactionSync(() => {
- // Hashing yields. Recheck the immutable revision before granting a link.
- this.artifacts.group(group.id);
- this.sweep();
- if (
- this.sql
- .exec<{ count: number }>('SELECT COUNT(*) AS count FROM asset_download_tickets')
- .one().count >= MAX_TICKETS
- )
- throw new HttpFailure(
- 429,
- 'Download link limit reached; try again after existing links expire',
- );
- this.sql.exec(
- 'INSERT INTO asset_download_tickets(token_hash,group_id,expires_at,uses) VALUES (?,?,?,0)',
- tokenHash,
- group.id,
- expiresAt,
- );
- });
- return { ticket: token, expiresAt, files };
- }
-
- private hash(token: string): Promise<string> {
- return sha256(JSON.stringify(['kiln-asset-download-v1', token]));
- }
- private current(hash: string): Ticket {
- const row = this.sql
- .exec<Ticket>(
- 'SELECT * FROM asset_download_tickets WHERE token_hash=? AND expires_at>?',
- hash,
- this.now(),
- )
- .toArray()[0];
- if (!row) throw denied();
- return row;
- }
- private file(row: Ticket, name: string): string {
- const group = this.artifacts.group(row.group_id);
- const id = group.files[name];
- if (!id) throw denied();
- return id;
- }
-
- async download(token: string, filename: string, headOnly = false): Promise<Response> {
- if (
- typeof token !== 'string' ||
- !DOWNLOAD_TOKEN.test(token) ||
- !DOWNLOAD_FILES.has(filename) ||
- typeof headOnly !== 'boolean'
- )
- throw denied();
- const hash = await this.hash(token);
- const selected = this.storage.transactionSync(() => {
- const row = this.current(hash);
- const id = this.file(row, filename);
- if (row.uses >= MAX_TRANSFERS)
- throw new HttpFailure(429, 'Download link limit reached; request a new link');
- this.sql.exec('UPDATE asset_download_tickets SET uses=uses+1 WHERE token_hash=?', hash);
- return { id, groupId: row.group_id };
- });
- // Failed reads still consume an attempt; requests cannot refund their own quota.
- const response = await this.artifacts.download(selected.id, headOnly);
- try {
- const current = this.current(hash);
- if (current.group_id !== selected.groupId || this.file(current, filename) !== selected.id)
- throw denied();
- return response;
- } catch (error) {
- void response.body?.cancel().catch(() => {});
- throw error;
- }
- }
-
- /** Bounded by the fixed 128-row per-tenant ceiling; never extends asset retention. */
- sweep(): void {
- this.sql.exec('DELETE FROM asset_download_tickets WHERE expires_at<=?', this.now());
- }
-}
diff --git a/hosting/src/asset-index.ts b/hosting/src/asset-index.ts
deleted file mode 100644
index e0fb5986..00000000
--- a/hosting/src/asset-index.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import type { ArtifactStore } from './artifact-store';
-import { HttpFailure } from './http';
-
-const id = /^[a-z][a-z0-9_-]{0,79}(?![\s\S])/;
-const filesAllowed = new Set([
- 'asset.glb',
- 'source.kiln.js',
- 'preview.png',
- 'manifest.json',
- 'materials.kiln.json',
-]);
-const invalid = () => new HttpFailure(400, 'Invalid saved asset');
-function object(value: unknown): Record<string, unknown> {
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalid();
- return value as Record<string, unknown>;
-}
-function collection(value: unknown): string {
- if (value !== 'project' && value !== 'library') throw invalid();
- return value;
-}
-function identity(value: unknown): string {
- if (typeof value !== 'string' || !id.test(value)) throw invalid();
- return value;
-}
-const key = (collection: string, assetId: string, revisionId: string) =>
- `assets/${collection}/${assetId}/${revisionId}`;
-
-/** Storage ownership/indexing only. Native engine code verifies the actual asset records. */
-export class AssetIndex {
- constructor(private readonly artifacts: ArtifactStore) {}
-
- commit(input: unknown) {
- const value = object(input);
- const target = collection(value.collection);
- const assetId = identity(value.assetId);
- const revisionId = identity(value.revisionId);
- const parentRevision =
- value.parentRevision === undefined ? undefined : identity(value.parentRevision);
- if (parentRevision === revisionId || !['save', 'import'].includes(String(value.mode)))
- throw invalid();
- const entries = Object.entries(object(value.files));
- if (
- !entries.some(([name]) => name === 'manifest.json') ||
- !entries.some(([name]) => name === 'asset.glb') ||
- entries.some(
- ([name, fileId]) =>
- !filesAllowed.has(name) ||
- typeof fileId !== 'string' ||
- !/^[a-f0-9]{32}(?![\s\S])/.test(fileId),
- )
- )
- throw invalid();
- const files = Object.fromEntries(entries) as Record<string, string>;
- this.artifacts.assertFileNames(files);
- return this.artifacts.save(
- {
- key: key(target, assetId, revisionId),
- files,
- metadata: {
- kind: 'kiln.hosted-asset.v1',
- collection: target,
- assetId,
- revisionId,
- ...(parentRevision ? { parentRevision } : {}),
- },
- },
- value.mode === 'save'
- ? parentRevision
- ? { parentKey: key(target, assetId, parentRevision) }
- : { absentPrefix: `assets/${target}/${assetId}/` }
- : {},
- );
- }
-
- read(target: unknown, assetId: unknown, revisionId: unknown) {
- return this.artifacts.groupByKey(
- key(collection(target), identity(assetId), identity(revisionId)),
- );
- }
-
- list(input: unknown) {
- const value = object(input);
- const prefix = `assets/${collection(value.collection)}/`;
- const after = value.after ?? '';
- if (
- typeof after !== 'string' ||
- (after !== '' &&
- (!after.startsWith(prefix) || !/^[A-Za-z0-9_./-]{1,240}(?![\s\S])/.test(after)))
- )
- throw invalid();
- return this.artifacts.groupPage(prefix, after);
- }
-}
diff --git a/hosting/src/auth.ts b/hosting/src/auth.ts
deleted file mode 100644
index 437eca8c..00000000
--- a/hosting/src/auth.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-import {
- AuthorizationError,
- authorizationErrorRedirect,
- type ConsentDescription,
- type OAuthHelpers,
-} from '@cloudflare/workers-oauth-provider';
-import { HttpFailure } from './http';
-import { githubAuthorizationUrl, githubIdentity, type GitHubEnv } from './github';
-import { D1BrowserSessions } from './browser-sessions';
-import { finishBrowserLogin } from './browser-login';
-import { D1Connections } from './connections';
-import { finishAccountAction } from './account-actions';
-import { finishIdentityAction } from './identity-actions';
-import { finishDeletionAction } from './deletion-actions';
-import { googleAuthorizationUrl, type GoogleEnv, googleIdentity } from './google';
-import { D1LoginIntents, type SignInProvider } from './login-intents';
-import { escapeHtml, htmlPage } from './html-page';
-import { GOOGLE_SIGN_IN_BUTTON } from './google-button';
-
-export const SCOPES = ['kiln:use', 'offline_access'];
-export interface SignInEnv extends GoogleEnv, GitHubEnv {
- ACCOUNTS: D1Database;
-}
-interface SignInTransaction {
- intentId: string;
- provider: SignInProvider;
- purpose: 'sign-in';
- verifier: string;
- nonce: string;
-}
-function consentPage(details: ConsentDescription, handle: string, headers: Headers): Response {
- const descriptions: Record<string, string> = {
- 'kiln:use':
- 'Create, inspect, edit, save, download and delete your Kiln assets within your quota.',
- offline_access: 'Keep this connection working without signing in again for up to 30 days.',
- };
- return htmlPage(
- 'Connect to Kiln',
- `<h1>Connect ${escapeHtml(details.clientName)} to Kiln</h1>
-<section><h2>Review this connection</h2><p class="client-detail">${details.clientDomain ? `Client domain: <strong>${escapeHtml(details.clientDomain)}</strong>.` : 'This client registered its own name; that name is not verified.'}</p>
-<p class="client-detail">Access will be returned to <strong>${escapeHtml(details.redirectHost)}</strong>.</p>
-${details.redirectIsLoopback ? '<p>This connects an app on your computer. Continue only if you started that connection.</p>' : ''}
-<ul class="permission-list">${details.scope.map((scope) => `<li>${escapeHtml(descriptions[scope] ?? scope)}</li>`).join('')}</ul></section>
-<p>Hosted access is free within your quota. Sign in to keep saved assets private. Kiln requests no GitHub repository access or Google Drive access.</p>
-<p>Use the same sign-in method when returning to your library.</p>
-<form method="post" action="/authorize"><input type="hidden" name="handle" value="${escapeHtml(handle)}">
-<div class="provider-buttons"><button class="google-button" name="decision" value="google" aria-label="Continue with Google"><img src="${GOOGLE_SIGN_IN_BUTTON}" width="198" height="44" alt="Sign in with Google"></button>
-<button class="github-button" name="decision" value="github">Continue with GitHub</button></div>
-<p><button class="secondary" name="decision" value="deny">Cancel connection</button></p></form>`,
- { headers },
- );
-}
-
-export async function authorize(
- request: Request,
- oauth: OAuthHelpers,
- origin: string,
- env: SignInEnv,
- ctx: ExecutionContext,
-): Promise<Response> {
- const url = new URL(request.url);
- const intents = new D1LoginIntents(env.ACCOUNTS, origin);
- if (url.pathname === '/authorize' && request.method === 'GET') {
- const auth = await oauth.parseAuthRequest(request);
- if (
- url.searchParams.getAll('resource').length !== 1 ||
- !url.searchParams.get('resource') ||
- auth.codeChallengeMethod !== 'S256' ||
- !auth.codeChallenge ||
- auth.scope.length === 0 ||
- auth.scope.some((scope) => !SCOPES.includes(scope))
- ) {
- throw new HttpFailure(
- 400,
- 'Request requires a Kiln resource, S256 PKCE and supported scopes',
- );
- }
- const details = await oauth.describeConsent(auth);
- const consent = await oauth.beginConsent(auth);
- return consentPage(details, consent.handle, consent.headers);
- }
- if (url.pathname === '/authorize' && request.method === 'POST') {
- if (request.headers.get('origin') !== origin) throw new HttpFailure(403, 'Invalid form origin');
- if (
- request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded'
- ) {
- throw new HttpFailure(415, 'Expected form data');
- }
- const form = await request.formData();
- if (form.getAll('handle').length !== 1 || form.getAll('decision').length !== 1)
- throw new HttpFailure(400, 'Invalid sign-in form');
- const handle = String(form.get('handle') ?? '');
- const decision = form.get('decision');
- if (decision === 'deny') {
- const result = await oauth.denyConsent(request, handle);
- await intents.claimConsent(handle);
- return new Response(null, { status: 302, headers: result.headers });
- }
- if (decision !== 'google' && decision !== 'github')
- throw new HttpFailure(400, 'Choose how to connect');
- const approved = await oauth.approveConsent(request, handle);
- await intents.claimConsent(handle);
- const verifier = crypto.randomUUID().replace(/-/g, '') + crypto.randomUUID().replace(/-/g, '');
- const data: SignInTransaction = {
- intentId: crypto.randomUUID(),
- provider: decision,
- purpose: 'sign-in',
- verifier,
- nonce: crypto.randomUUID().replace(/-/g, ''),
- };
- const upstream = await oauth.beginUpstream(approved.request, {
- data,
- headers: approved.headers,
- });
- await intents.create({
- id: data.intentId,
- state: upstream.state,
- provider: data.provider,
- purpose: data.purpose,
- });
- if (decision === 'google') {
- upstream.headers.set(
- 'location',
- await googleAuthorizationUrl(
- origin,
- { state: upstream.state, verifier, nonce: data.nonce },
- env,
- request.signal,
- ),
- );
- return new Response(null, { status: 302, headers: upstream.headers });
- }
- upstream.headers.set(
- 'location',
- await githubAuthorizationUrl(origin, upstream.state, verifier, env),
- );
- return new Response(null, { status: 302, headers: upstream.headers });
- }
- const callbackProvider =
- url.pathname === '/oauth/google/callback'
- ? 'google'
- : url.pathname === '/oauth/github/callback'
- ? 'github'
- : null;
- if (callbackProvider && request.method === 'GET') {
- if (url.searchParams.getAll('state').length !== 1)
- throw new HttpFailure(400, 'Invalid sign-in state');
- if (url.searchParams.get('state')?.startsWith('kb1_'))
- return finishBrowserLogin(request, origin, env, callbackProvider);
- if (url.searchParams.get('state')?.startsWith('ka1_'))
- return finishAccountAction(request, origin, env, callbackProvider, oauth, ctx);
- if (url.searchParams.get('state')?.startsWith('ki1_'))
- return finishIdentityAction(request, origin, env, callbackProvider);
- if (url.searchParams.get('state')?.startsWith('kd1_'))
- return finishDeletionAction(request, origin, env, callbackProvider);
- const resumed = await oauth.finishUpstream<SignInTransaction>(request);
- if (
- !resumed.data ||
- resumed.data.provider !== callbackProvider ||
- resumed.data.purpose !== 'sign-in'
- )
- throw new HttpFailure(400, 'Invalid sign-in provider');
- const state = url.searchParams.get('state') ?? '';
- // The library validates this state against its browser-bound transaction;
- // D1 additionally compares its server-retained hash and atomically consumes it.
- await intents.consume({
- id: resumed.data.intentId,
- state,
- provider: callbackProvider,
- purpose: resumed.data.purpose,
- });
- if (url.searchParams.has('error')) {
- resumed.headers.set('location', authorizationErrorRedirect(resumed.request, 'access_denied'));
- return new Response(null, { status: 302, headers: resumed.headers });
- }
- const code = url.searchParams.get('code');
- if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1)
- throw new HttpFailure(400, 'Missing sign-in code');
- const identity =
- callbackProvider === 'google'
- ? await googleIdentity(
- request,
- origin,
- { state, verifier: resumed.data.verifier, nonce: resumed.data.nonce },
- env,
- )
- : await githubIdentity(code, resumed.data.verifier, origin, env);
- const browser = await new D1BrowserSessions(env.ACCOUNTS, origin).issue(identity, request);
- const account = browser.account;
- const userId = account.id;
- const connections = new D1Connections(env.ACCOUNTS);
- const props = await connections.create(
- account,
- resumed.request,
- await oauth.describeConsent(resumed.request),
- );
- let redirectTo: string;
- try {
- ({ redirectTo } = await oauth.completeAuthorization({
- request: resumed.request,
- userId,
- metadata: { connectionId: props.connectionId },
- scope: resumed.request.scope,
- props,
- // Each consent is an independently revocable connection. Do not silently
- // revoke another installation that shares this MCP client's identifier.
- revokeExistingGrants: false,
- }));
- } catch (error) {
- await connections.cancelPending(props);
- throw error;
- }
- resumed.headers.set('location', redirectTo);
- resumed.headers.append('set-cookie', browser.cookie);
- return new Response(null, { status: 302, headers: resumed.headers });
- }
- return new Response('Method not allowed', { status: 405 });
-}
-
-export function authorizationFailure(error: unknown): Response {
- // Never echo provider response bodies, URLs, request headers or exceptions.
- if (error instanceof AuthorizationError)
- return new Response('Invalid or expired authorization request; restart sign-in', {
- status: 400,
- });
- if (error instanceof HttpFailure) return new Response(error.message, { status: error.status });
- return new Response('Service temporarily unavailable', { status: 503 });
-}
diff --git a/hosting/src/browser-cookies.ts b/hosting/src/browser-cookies.ts
deleted file mode 100644
index 4ca839e1..00000000
--- a/hosting/src/browser-cookies.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/** Browser credentials are accepted only once, from a host-scoped cookie. */
-export function browserToken(request: Request, origin: string, name: string): string | null {
- if (new URL(request.url).origin !== origin) return null;
- const header = request.headers.get('cookie') ?? '';
- if (header.length > 8192) return null;
- const values = header
- .split(';')
- .map((item) => item.trim())
- .filter((item) => item.split('=', 1)[0] === name);
- if (values.length !== 1) return null;
- const token = values[0]!.slice(name.length + 1);
- return /^[a-f0-9]{64}$/.test(token) ? token : null;
-}
-
-export function randomBrowserToken(): string {
- return Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) =>
- byte.toString(16).padStart(2, '0'),
- ).join('');
-}
-
-export const BROWSER_COOKIE_ATTRIBUTES = 'Path=/; Secure; HttpOnly; SameSite=Lax';
diff --git a/hosting/src/browser-download.ts b/hosting/src/browser-download.ts
deleted file mode 100644
index 5a3d26b5..00000000
--- a/hosting/src/browser-download.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { signInPage } from './account-page';
-import { D1BrowserSessions, type BrowserSession } from './browser-sessions';
-import { parseDownloadPath } from './download-path';
-import { HttpFailure } from './http';
-import { tenantForAccount } from './tenant-identity';
-import { limitAccount, type RequestLimitEnv } from './request-limits';
-
-export async function browserDownload(
- request: Request,
- env: { ACCOUNTS: D1Database; TENANTS: DurableObjectNamespace } & Pick<
- RequestLimitEnv,
- 'ACCOUNT_REQUEST_LIMIT'
- >,
- origin: string,
-): Promise<Response> {
- const url = new URL(request.url);
- if (url.origin !== origin || url.search || url.hash)
- throw new HttpFailure(400, 'Invalid download link');
- const selected = parseDownloadPath(url.pathname);
- if (!selected) throw new HttpFailure(404, 'Download link unavailable; request a new link');
- if (!['GET', 'HEAD'].includes(request.method))
- return new Response('Method not allowed', { status: 405, headers: { allow: 'GET, HEAD' } });
- const incomingOrigin = request.headers.get('origin');
- const site = request.headers.get('sec-fetch-site');
- if (
- (incomingOrigin !== null && incomingOrigin !== origin) ||
- ((site === 'cross-site' || site === 'same-site') &&
- (request.headers.get('sec-fetch-mode') !== 'navigate' ||
- request.headers.get('sec-fetch-dest') !== 'document'))
- )
- throw new HttpFailure(403, 'Open the download link directly');
- const sessions = new D1BrowserSessions(env.ACCOUNTS, origin);
- let session: BrowserSession;
- try {
- session = await sessions.read(request);
- } catch (error) {
- if (!(error instanceof HttpFailure) || error.status !== 401) throw error;
- return request.method === 'HEAD'
- ? new Response(null, { status: 401 })
- : signInPage(url.pathname);
- }
- const limited = await limitAccount(request, env, origin, session.accountId);
- if (limited) return limited;
- const tenant = await tenantForAccount(origin, session.accountId);
- // Forward no caller headers, cookies, bearer tokens or object selectors.
- const response = await env.TENANTS.getByName(tenant).fetch(
- new Request(
- `https://tenant.internal/internal/downloads/${selected.token}/${selected.filename}`,
- {
- method: request.method,
- signal: request.signal,
- redirect: 'manual',
- },
- ),
- );
- try {
- // Storage reads yield. Revocation must be checked again before releasing bytes.
- const current = await sessions.read(request);
- if (current.accountId !== session.accountId || current.accountEpoch !== session.accountEpoch)
- throw new HttpFailure(401, 'Sign in to continue');
- return response;
- } catch (error) {
- void response.body?.cancel().catch(() => {});
- throw error;
- }
-}
diff --git a/hosting/src/browser-login.ts b/hosting/src/browser-login.ts
deleted file mode 100644
index 7d826362..00000000
--- a/hosting/src/browser-login.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import type { SignInEnv } from './auth';
-import { BROWSER_COOKIE_ATTRIBUTES, browserToken, randomBrowserToken } from './browser-cookies';
-import { D1BrowserSessions } from './browser-sessions';
-import { githubAuthorizationUrl, githubIdentity } from './github';
-import { googleAuthorizationUrl, googleIdentity } from './google';
-import { HttpFailure, sha256 } from './http';
-import type { SignInProvider } from './login-intents';
-import { validLoginReturn } from './download-path';
-
-const COOKIE = '__Host-kiln-login';
-const invalid = () => new HttpFailure(400, 'Invalid or expired sign-in; restart sign-in');
-const hash = (origin: string, kind: 'binding' | 'state', value: string) =>
- sha256(JSON.stringify(['kiln-browser-login-v1', origin, kind, value]));
-const clearCookie = `${COOKIE}=; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=0`;
-
-export async function beginBrowserLogin(
- request: Request,
- origin: string,
- env: SignInEnv,
-): Promise<Response> {
- if (request.method !== 'POST')
- return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });
- if (request.headers.get('origin') !== origin) throw new HttpFailure(403, 'Invalid sign-in form');
- if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')
- throw new HttpFailure(415, 'Expected form data');
- if (new URL(request.url).search) throw invalid();
- const form = await request.formData();
- const provider = form.get('provider');
- const returnTo = form.get('returnTo') ?? '/account';
- if (
- form.getAll('provider').length !== 1 ||
- form.getAll('returnTo').length > 1 ||
- !validLoginReturn(returnTo) ||
- [...form.keys()].some((key) => key !== 'provider' && key !== 'returnTo') ||
- (provider !== 'google' && provider !== 'github')
- )
- throw invalid();
- const flow = {
- state: `kb1_${randomBrowserToken()}`,
- verifier: randomBrowserToken(),
- nonce: randomBrowserToken(),
- };
- const binding = randomBrowserToken();
- const now = Date.now();
- const previous = browserToken(request, origin, COOKIE);
- const database = env.ACCOUNTS.withSession('first-primary');
- const results = await database.batch([
- database
- .prepare(`DELETE FROM kiln_browser_logins WHERE state_hash IN
- (SELECT state_hash FROM kiln_browser_logins WHERE expires_at<=? LIMIT 128)`)
- .bind(now),
- database
- .prepare('DELETE FROM kiln_browser_logins WHERE binding_hash=?')
- .bind(previous ? await hash(origin, 'binding', previous) : ''),
- database
- .prepare(`INSERT INTO kiln_browser_logins(state_hash, binding_hash, provider, verifier, nonce, expires_at, return_to)
- SELECT ?, ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM kiln_browser_logins)<4096 RETURNING state_hash`)
- .bind(
- await hash(origin, 'state', flow.state),
- await hash(origin, 'binding', binding),
- provider,
- flow.verifier,
- flow.nonce,
- now + 600_000,
- returnTo,
- ),
- ]);
- if (results[2]?.results.length !== 1)
- throw new HttpFailure(429, 'Sign-in is busy; please try again later');
- const target =
- provider === 'google'
- ? await googleAuthorizationUrl(origin, flow, env, request.signal)
- : await githubAuthorizationUrl(origin, flow.state, flow.verifier, env);
- return new Response(null, {
- status: 302,
- headers: {
- location: target,
- 'set-cookie': `${COOKIE}=${binding}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=600`,
- },
- });
-}
-
-/** A separate server-retained transaction; no synthetic MCP client or issuer. */
-export async function finishBrowserLogin(
- request: Request,
- origin: string,
- env: SignInEnv,
- provider: SignInProvider,
-): Promise<Response> {
- const url = new URL(request.url);
- const state = url.searchParams.get('state') ?? '';
- const binding = browserToken(request, origin, COOKIE);
- if (
- request.method !== 'GET' ||
- url.pathname !== `/oauth/${provider}/callback` ||
- url.searchParams.getAll('state').length !== 1 ||
- !/^kb1_[a-f0-9]{64}$/.test(state) ||
- !binding
- )
- throw invalid();
- const flow = await env.ACCOUNTS.withSession('first-primary')
- .prepare(
- `DELETE FROM kiln_browser_logins WHERE state_hash=? AND binding_hash=? AND provider=? AND expires_at>?
- RETURNING verifier, nonce, return_to AS returnTo`,
- )
- .bind(
- await hash(origin, 'state', state),
- await hash(origin, 'binding', binding),
- provider,
- Date.now(),
- )
- .first<{ verifier: string; nonce: string; returnTo: string }>();
- if (!flow || !validLoginReturn(flow.returnTo)) throw invalid();
- if (url.searchParams.has('error'))
- return new Response('Sign-in was cancelled. Return to the account page to try again.', {
- status: 400,
- headers: { 'set-cookie': clearCookie },
- });
- const code = url.searchParams.get('code');
- if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1) throw invalid();
- const identity =
- provider === 'google'
- ? await googleIdentity(request, origin, { ...flow, state }, env)
- : await githubIdentity(code, flow.verifier, origin, env);
- const session = await new D1BrowserSessions(env.ACCOUNTS, origin).issue(identity, request);
- const headers = new Headers({ location: flow.returnTo });
- headers.append('set-cookie', clearCookie);
- headers.append('set-cookie', session.cookie);
- return new Response(null, { status: 303, headers });
-}
diff --git a/hosting/src/browser-sessions.ts b/hosting/src/browser-sessions.ts
deleted file mode 100644
index 408f371b..00000000
--- a/hosting/src/browser-sessions.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-import { D1AccountDirectory, type KilnAccount, type VerifiedIdentity } from './accounts';
-import { HttpFailure, sha256 } from './http';
-import {
- BROWSER_COOKIE_ATTRIBUTES as cookieAttributes,
- browserToken,
- randomBrowserToken,
-} from './browser-cookies';
-
-const COOKIE = '__Host-kiln-session';
-export const clearBrowserSessionCookie = `${COOKIE}=; ${cookieAttributes}; Max-Age=0`;
-const LIFETIME_MS = 86_400_000;
-const IDLE_MS = 1_800_000;
-const denied = () => new HttpFailure(401, 'Sign in to continue');
-
-export interface BrowserSession {
- /** Server-only session binding. Never render it or accept it as a credential. */
- binding: string;
- accountId: string;
- accountEpoch: number;
- authenticatedAt: number;
- expiresAt: number;
- csrf: string;
-}
-
-export class D1BrowserSessions {
- constructor(
- private readonly database: D1Database,
- private readonly origin: string,
- ) {
- const url = new URL(origin);
- if (url.protocol !== 'https:' || url.origin !== origin)
- throw new Error('Invalid browser-session origin');
- }
-
- /** Call only after a provider adapter has verified a fresh sign-in response. */
- async issue(identity: VerifiedIdentity, previousRequest?: Request) {
- const account = await new D1AccountDirectory(this.database).resolveIdentity(identity);
- return this.issueAccount(account, previousRequest);
- }
-
- async renew(identity: VerifiedIdentity, proof: BrowserSession, request: Request) {
- if ((await this.requestHash(request)) !== proof.binding) throw denied();
- const account = await new D1AccountDirectory(this.database).getAccount(proof.accountId);
- const binding = await this.database
- .withSession('first-primary')
- .prepare(
- 'SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=? AND account_id=?',
- )
- .bind(identity.issuer, identity.subject, proof.accountId)
- .first();
- if (
- account?.state !== 'active' ||
- account.authorizationEpoch !== proof.accountEpoch ||
- !binding
- )
- throw denied();
- return this.issueAccount(account, request);
- }
-
- private async issueAccount(account: KilnAccount, previousRequest?: Request) {
- const token = randomBrowserToken();
- const hash = await this.hash(token);
- const csrf = randomBrowserToken();
- const now = Date.now();
- let previousHash = '';
- if (previousRequest) {
- try {
- previousHash = await this.requestHash(previousRequest);
- } catch (error) {
- if (!(error instanceof HttpFailure) || error.status !== 401) throw error;
- }
- }
- const session = this.database.withSession('first-primary');
- const results = await session.batch([
- session
- .prepare(`DELETE FROM kiln_browser_sessions WHERE token_hash IN (
- SELECT token_hash FROM kiln_browser_sessions WHERE expires_at<=? LIMIT 128
- )`)
- .bind(now),
- session.prepare('DELETE FROM kiln_browser_sessions WHERE token_hash=?').bind(previousHash),
- session
- .prepare(`DELETE FROM kiln_browser_sessions WHERE token_hash IN (
- SELECT token_hash FROM kiln_browser_sessions WHERE account_id=?
- ORDER BY authenticated_at DESC, token_hash DESC LIMIT -1 OFFSET 7
- ) AND EXISTS (SELECT 1 FROM kiln_accounts WHERE id=? AND state='active'
- AND authorization_epoch=?)`)
- .bind(account.id, account.id, account.authorizationEpoch),
- session
- .prepare(`INSERT INTO kiln_browser_sessions
- (token_hash, account_id, account_epoch, authenticated_at, expires_at, idle_expires_at, csrf)
- SELECT ?, id, authorization_epoch, ?, ?, ?, ? FROM kiln_accounts
- WHERE id=? AND state='active' AND authorization_epoch=? RETURNING token_hash`)
- .bind(
- hash,
- now,
- now + LIFETIME_MS,
- now + IDLE_MS,
- csrf,
- account.id,
- account.authorizationEpoch,
- ),
- ]);
- if (results[3]?.results.length !== 1) throw denied();
- return {
- account,
- csrf,
- cookie: `${COOKIE}=${token}; ${cookieAttributes}; Max-Age=${LIFETIME_MS / 1000}`,
- };
- }
-
- async read(request: Request): Promise<BrowserSession> {
- return this.readCurrent(request, null);
- }
-
- async authorizeForm(request: Request, csrf: string): Promise<BrowserSession> {
- if (
- request.method !== 'POST' ||
- request.headers.get('origin') !== this.origin ||
- typeof csrf !== 'string' ||
- !/^[a-f0-9]{64}$/.test(csrf)
- )
- throw new HttpFailure(403, 'Invalid account form');
- return this.readCurrent(request, csrf);
- }
-
- private async readCurrent(request: Request, csrf: string | null): Promise<BrowserSession> {
- const hash = await this.requestHash(request);
- const now = Date.now();
- const session = await this.database
- .withSession('first-primary')
- .prepare(`UPDATE kiln_browser_sessions SET idle_expires_at=MIN(expires_at, ?)
- WHERE token_hash=? AND expires_at>? AND idle_expires_at>? AND (? IS NULL OR csrf=?)
- AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_browser_sessions.account_id
- AND a.state='active' AND a.authorization_epoch=kiln_browser_sessions.account_epoch)
- RETURNING token_hash AS binding, account_id AS accountId, account_epoch AS accountEpoch,
- authenticated_at AS authenticatedAt, expires_at AS expiresAt, csrf`)
- .bind(now + IDLE_MS, hash, now, now, csrf, csrf)
- .first<BrowserSession>();
- if (!session) throw csrf === null ? denied() : new HttpFailure(403, 'Invalid account form');
- return session;
- }
-
- async logout(request: Request, csrf: string): Promise<string> {
- if (
- request.method !== 'POST' ||
- request.headers.get('origin') !== this.origin ||
- typeof csrf !== 'string' ||
- !/^[a-f0-9]{64}$/.test(csrf)
- )
- throw new HttpFailure(403, 'Invalid account form');
- const hash = await this.requestHash(request);
- const row = await this.database
- .withSession('first-primary')
- .prepare(`DELETE FROM kiln_browser_sessions WHERE token_hash=? AND csrf=?
- AND expires_at>? AND idle_expires_at>? AND EXISTS (SELECT 1 FROM kiln_accounts a
- WHERE a.id=kiln_browser_sessions.account_id AND a.state='active'
- AND a.authorization_epoch=kiln_browser_sessions.account_epoch)
- RETURNING token_hash`)
- .bind(hash, csrf, Date.now(), Date.now())
- .first();
- if (!row) throw new HttpFailure(403, 'Invalid account form');
- return clearBrowserSessionCookie;
- }
-
- private hash(token: string): Promise<string> {
- return sha256(JSON.stringify(['kiln-browser-session-v1', this.origin, token]));
- }
-
- private requestHash(request: Request): Promise<string> {
- const token = browserToken(request, this.origin, COOKIE);
- if (!token) throw denied();
- return this.hash(token);
- }
-}
diff --git a/hosting/src/connections.ts b/hosting/src/connections.ts
deleted file mode 100644
index 2548a73d..00000000
--- a/hosting/src/connections.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-import type {
- AuthRequest,
- ConsentDescription,
- GrantType,
-} from '@cloudflare/workers-oauth-provider';
-import type { KilnAccount, VerifiedIdentity } from './accounts';
-import type { BrowserSession } from './browser-sessions';
-import { HttpFailure } from './http';
-
-export interface ConnectionProps {
- userId: string;
- accountEpoch: number;
- connectionId: string;
-}
-
-export interface KilnConnection {
- id: string;
- clientName: string;
- clientDomain: string | null;
- redirectUri: string;
- scope: string;
- state: 'pending' | 'active' | 'revoked';
- createdAt: number;
- expiresAt: number;
-}
-
-function validProps(userId: unknown, props: unknown): props is ConnectionProps {
- if (
- typeof userId !== 'string' ||
- !/^ka_[a-f0-9]{32}$/.test(userId) ||
- !props ||
- typeof props !== 'object'
- )
- return false;
- const value = props as Record<string, unknown>;
- return (
- value.userId === userId &&
- Number.isSafeInteger(value.accountEpoch) &&
- Number(value.accountEpoch) > 0 &&
- typeof value.connectionId === 'string' &&
- /^kc_[a-f0-9]{32}$/.test(value.connectionId)
- );
-}
-
-const activeAccount = `EXISTS (SELECT 1 FROM kiln_accounts a
- WHERE a.id=kiln_connections.account_id AND a.state='active'
- AND a.authorization_epoch=kiln_connections.account_epoch)`;
-
-/** This primary SQL authority complements, and never replaces, library token validation. */
-export class D1Connections {
- constructor(private readonly database: D1Database) {}
-
- async create(
- account: KilnAccount,
- request: AuthRequest,
- details: ConsentDescription,
- ): Promise<ConnectionProps> {
- const connectionId = `kc_${crypto.randomUUID().replace(/-/g, '')}`;
- const now = Date.now();
- const session = this.database.withSession('first-primary');
- const rows = await session.batch([
- session
- .prepare(`DELETE FROM kiln_connections WHERE id IN (
- SELECT id FROM kiln_connections WHERE expires_at<=? OR (state='pending' AND created_at<=?) LIMIT 128
- )`)
- .bind(now, now - 600_000),
- session
- .prepare(`INSERT INTO kiln_connections
- (id, account_id, account_epoch, client_id, client_name, client_domain, redirect_uri, scope, created_at, expires_at)
- SELECT ?, id, authorization_epoch, ?, ?, ?, ?, ?, ?, ? FROM kiln_accounts
- WHERE id=? AND state='active' AND authorization_epoch=? AND
- (SELECT COUNT(*) FROM kiln_connections WHERE account_id=? AND account_epoch=?
- AND state IN ('pending','active') AND expires_at>?)<32 RETURNING id`)
- .bind(
- connectionId,
- request.clientId,
- details.clientName,
- details.clientDomain ?? null,
- request.redirectUri,
- request.scope.join(' '),
- now,
- now + 30 * 86_400_000,
- account.id,
- account.authorizationEpoch,
- account.id,
- account.authorizationEpoch,
- now,
- ),
- ]);
- if (rows[1]?.results.length !== 1)
- throw new HttpFailure(
- 429,
- 'Cannot add a connection; sign in again or disconnect an unused app',
- );
- return { userId: account.id, accountEpoch: account.authorizationEpoch, connectionId };
- }
-
- async cancelPending(props: ConnectionProps): Promise<void> {
- await this.database
- .withSession('first-primary')
- .prepare(
- "DELETE FROM kiln_connections WHERE id=? AND account_id=? AND account_epoch=? AND state='pending'",
- )
- .bind(props.connectionId, props.userId, props.accountEpoch)
- .run();
- }
-
- /** Claim authorization-code exchange once, before the library writes any token. */
- async exchange(
- userId: string,
- props: unknown,
- clientId: string,
- grantId: string,
- kind: GrantType,
- ): Promise<boolean> {
- if (!validProps(userId, props) || !/^[A-Za-z0-9_-]{1,255}$/.test(grantId)) return false;
- const now = Date.now();
- const session = this.database.withSession('first-primary');
- const predicate = `id=? AND account_id=? AND account_epoch=? AND client_id=? AND expires_at>? AND ${activeAccount}`;
- if (kind === 'authorization_code') {
- const row = await session
- .prepare(`UPDATE kiln_connections SET state='active', grant_id=?
- WHERE ${predicate} AND state='pending' AND grant_id IS NULL AND created_at>?
- RETURNING id`)
- .bind(grantId, props.connectionId, userId, props.accountEpoch, clientId, now, now - 600_000)
- .first();
- return row !== null;
- }
- const row = await session
- .prepare(`SELECT id FROM kiln_connections WHERE ${predicate}
- AND state='active' AND grant_id=?`)
- .bind(props.connectionId, userId, props.accountEpoch, clientId, now, grantId)
- .first();
- return row !== null;
- }
-
- async accepts(userId: string, props: unknown, clientId: string): Promise<boolean> {
- if (!validProps(userId, props)) return false;
- const row = await this.database
- .withSession('first-primary')
- .prepare(
- `SELECT id FROM kiln_connections WHERE id=? AND account_id=? AND account_epoch=? AND client_id=?
- AND state='active' AND grant_id IS NOT NULL AND expires_at>? AND ${activeAccount}`,
- )
- .bind(props.connectionId, userId, props.accountEpoch, clientId, Date.now())
- .first();
- return row !== null;
- }
-
- async list(accountId: string, epoch: number): Promise<KilnConnection[]> {
- const now = Date.now();
- const rows = await this.database
- .withSession('first-primary')
- .prepare(
- `SELECT id, client_name AS clientName, client_domain AS clientDomain, redirect_uri AS redirectUri,
- scope, state, created_at AS createdAt, expires_at AS expiresAt FROM kiln_connections
- WHERE account_id=? AND account_epoch=? AND state IN ('pending','active') AND expires_at>?
- AND (state='active' OR created_at>?) AND ${activeAccount}
- ORDER BY created_at DESC, id LIMIT 32`,
- )
- .bind(accountId, epoch, now, now - 600_000)
- .all<KilnConnection>();
- return rows.results;
- }
-
- /** Only a consumed action and a newly verified, already-linked identity reach this method. */
- async revoke(
- proof: BrowserSession,
- identity: VerifiedIdentity,
- connectionId: string,
- ): Promise<string | null> {
- const now = Date.now();
- const row = await this.database
- .withSession('first-primary')
- .prepare(
- `UPDATE kiln_connections SET state='revoked' WHERE id=? AND account_id=? AND account_epoch=?
- AND state IN ('pending','active') AND expires_at>? AND ${activeAccount}
- AND EXISTS (SELECT 1 FROM kiln_browser_sessions s WHERE s.token_hash=? AND s.account_id=kiln_connections.account_id
- AND s.account_epoch=kiln_connections.account_epoch AND s.expires_at>? AND s.idle_expires_at>?)
- AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=kiln_connections.account_id AND i.issuer=? AND i.subject=?)
- RETURNING grant_id AS grantId`,
- )
- .bind(
- connectionId,
- proof.accountId,
- proof.accountEpoch,
- now,
- proof.binding,
- now,
- now,
- identity.issuer,
- identity.subject,
- )
- .first<{ grantId: string | null }>();
- if (!row)
- throw new HttpFailure(
- 403,
- 'Could not verify this account action; return to your account and try again',
- );
- return row.grantId;
- }
-}
diff --git a/hosting/src/container-job.ts b/hosting/src/container-job.ts
deleted file mode 100644
index c81ec264..00000000
--- a/hosting/src/container-job.ts
+++ /dev/null
@@ -1,353 +0,0 @@
-import { EXECUTION_PROFILES, type ExecutionKind } from './execution-profiles';
-
-type FailureCode =
- | 'INPUT_INVALID'
- | 'JOB_ALREADY_USED'
- | 'ISOLATION_UNAVAILABLE'
- | 'WORKER_FAILED'
- | 'OUTPUT_LIMIT_EXCEEDED'
- | 'DEADLINE_EXCEEDED'
- | 'CANCELLED'
- | 'CLEANUP_FAILED';
-
-export class ContainerJobFailure extends Error {
- constructor(readonly code: FailureCode) {
- super(code);
- }
-}
-
-interface JobRecord {
- state: 'running' | 'finished';
- deadlineAt: number;
- cancelled?: boolean;
- outcome?: FailureCode | 'completed';
-}
-
-/** Private host limits, deliberately below the engine protocol's general limits. */
-const STDERR_BYTES = 16 * 1024;
-const CLEANUP_MS = 5_000;
-
-function boundedInteger(value: number, max: number): boolean {
- return Number.isSafeInteger(value) && value >= 1 && value <= max;
-}
-
-async function capture(
- stream: ReadableStream<Uint8Array> | null,
- limit: number,
- check: () => void,
-) {
- if (!stream) throw new ContainerJobFailure('WORKER_FAILED');
- const reader = stream.getReader();
- // Tiny chunks must not turn a byte allowance into an unbounded array of objects.
- const bytes = new Uint8Array(limit);
- let size = 0;
- try {
- for (;;) {
- check();
- const { value, done } = await reader.read();
- check();
- if (done) break;
- if (!(value instanceof Uint8Array)) throw new ContainerJobFailure('WORKER_FAILED');
- if (size + value.byteLength > limit) throw new ContainerJobFailure('OUTPUT_LIMIT_EXCEEDED');
- bytes.set(value, size);
- size += value.byteLength;
- }
- return bytes.slice(0, size);
- } catch (error) {
- void reader.cancel().catch(() => {});
- throw error;
- } finally {
- reader.releaseLock();
- }
-}
-
-export async function destroyContainer(container: Container): Promise<void> {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- await Promise.race([
- (async () => {
- await container.destroy();
- // Keep the watchdog and suppress output unless the provider confirms
- // destruction. Inspection shares the cleanup deadline, including errors
- // and a hung readback; a successful destroy acknowledgement alone is
- // insufficient to release admission for an unconfirmed VM.
- const remaining = await container.inspect();
- if (container.running || remaining !== null)
- throw new ContainerJobFailure('CLEANUP_FAILED');
- })(),
- new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(new ContainerJobFailure('CLEANUP_FAILED')), CLEANUP_MS);
- }),
- ]);
- } catch {
- throw new ContainerJobFailure('CLEANUP_FAILED');
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
-}
-
-/**
- * One private Durable Object per job. Bytes returned here remain untrusted;
- * the caller must validate the engine's versioned evaluator response.
- * Unit tests cover orchestration, not the provider's isolation guarantees.
- */
-class ContainerExecutionJob {
- private readonly verifiedOutputs = new WeakMap<Uint8Array, string>();
- private readonly cancellation = new AbortController();
- private activeRun?: Promise<Uint8Array>;
- private cancellationWork?: Promise<void>;
-
- constructor(
- private readonly context: Pick<DurableObjectState, 'container' | 'storage'>,
- private readonly kind: ExecutionKind,
- ) {}
-
- /** Only a returned output after verified image inspection and complete VM cleanup. */
- executionImage(output: Uint8Array): string | undefined {
- return this.verifiedOutputs.get(output);
- }
-
- run(
- request: Uint8Array,
- controls: { deadlineMs: number; maxResponseBytes: number; signal?: AbortSignal },
- ): Promise<Uint8Array> {
- if (this.activeRun) return Promise.reject(new ContainerJobFailure('JOB_ALREADY_USED'));
- const pending = this.runOnce(request, {
- ...controls,
- signal: controls.signal
- ? AbortSignal.any([controls.signal, this.cancellation.signal])
- : this.cancellation.signal,
- }).then(({ output, image }) => {
- this.verifiedOutputs.set(output, image);
- return output;
- });
- this.activeRun = pending;
- const finished = () => {
- if (this.activeRun === pending) this.activeRun = undefined;
- };
- void pending.then(finished, finished);
- return pending;
- }
-
- /**
- * Private parent-controller RPC: fence even an as-yet-undelivered child request.
- * Keep one controller per DO instance so cancellation reaches a pending claim
- * before it can start compute. Durable state protects subsequent incarnations.
- * Success means no child VM remains; failure must retain outer admission.
- */
- cancel(): Promise<void> {
- if (this.cancellationWork) return this.cancellationWork;
- const pending = this.cancelOnce().catch(() => {
- throw new ContainerJobFailure('CLEANUP_FAILED');
- });
- this.cancellationWork = pending;
- const finished = () => {
- if (this.cancellationWork === pending) this.cancellationWork = undefined;
- };
- void pending.then(finished, finished);
- return pending;
- }
-
- private async cancelOnce(): Promise<void> {
- this.cancellation.abort();
- await this.context.storage.transaction(async (transaction) => {
- const job = await transaction.get<JobRecord>('job');
- if (job?.state === 'finished') return;
- if (!job) {
- // A VM is never started before its durable record exists. This tombstone
- // denies a request still in transport, including after this DO is evicted.
- await transaction.put('job', {
- state: 'finished',
- deadlineAt: Date.now(),
- outcome: 'CANCELLED',
- } satisfies JobRecord);
- return;
- }
- await transaction.put('job', { ...job, cancelled: true } satisfies JobRecord);
- await transaction.setAlarm(Date.now());
- });
- // A live run owns its cleanup. Do not race its pending startup with a separate
- // destruction and then return success while that run can still resume.
- await this.activeRun?.catch(() => {});
- const job = await this.context.storage.get<JobRecord>('job');
- if (job?.state === 'running') await this.recover(job);
- }
-
- private async runOnce(
- request: Uint8Array,
- controls: { deadlineMs: number; maxResponseBytes: number; signal?: AbortSignal },
- ): Promise<{ output: Uint8Array; image: string }> {
- const container = this.context.container;
- if (!container) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');
- const profile = EXECUTION_PROFILES[this.kind];
- const image = container.images[profile.image];
- if (
- typeof image !== 'string' ||
- image.length > 512 ||
- !/^[a-zA-Z0-9._:/-]+@sha256:[a-f0-9]{64}$/.test(image) ||
- !(request instanceof Uint8Array) ||
- request.byteLength === 0 ||
- request.byteLength > profile.requestBytes ||
- !boundedInteger(controls.deadlineMs, profile.deadlineMs) ||
- !boundedInteger(controls.maxResponseBytes, profile.responseBytes)
- )
- throw new ContainerJobFailure('INPUT_INVALID');
- if (controls.signal?.aborted) throw new ContainerJobFailure('CANCELLED');
-
- const job: JobRecord = { state: 'running', deadlineAt: Date.now() + controls.deadlineMs };
- // Persist the watchdog before starting compute. Never reuse a completed ID.
- // Another request's failed claim must not destroy the first request's VM.
- const admitted = await this.context.storage.transaction(async (transaction) => {
- if (await transaction.get('job')) return false;
- await transaction.put('job', job);
- await transaction.setAlarm(job.deadlineAt);
- return true;
- });
- if (!admitted) throw new ContainerJobFailure('JOB_ALREADY_USED');
-
- let failure: ContainerJobFailure | undefined;
- let closing = false;
- let rejectStopped: (error: ContainerJobFailure) => void = () => {};
- const stopped = new Promise<never>((_, reject) => {
- rejectStopped = reject;
- });
- void stopped.catch(() => {});
- const stop = (code: FailureCode) => {
- if (closing || failure) return;
- failure = new ContainerJobFailure(code);
- rejectStopped(failure);
- };
- const check = () => {
- if (failure) throw failure;
- if (closing) throw new ContainerJobFailure('WORKER_FAILED');
- if (Date.now() >= job.deadlineAt) {
- stop('DEADLINE_EXCEEDED');
- throw failure;
- }
- };
- const onAbort = () => stop('CANCELLED');
- controls.signal?.addEventListener('abort', onAbort, { once: true });
- if (controls.signal?.aborted) onAbort();
- const timer = setTimeout(
- () => stop('DEADLINE_EXCEEDED'),
- Math.max(0, job.deadlineAt - Date.now()),
- );
-
- try {
- const execute = async () => {
- check();
- if (container.running) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');
- container.start({
- image,
- enableInternet: false,
- instance: 'standard-2',
- entrypoint: ['/usr/bin/sleep', 'infinity'],
- env: {},
- });
- void container.monitor().then(
- () => stop('WORKER_FAILED'),
- () => stop('WORKER_FAILED'),
- );
- // A fallback for abandoned requests, never a substitute for the watchdog.
- await container.setInactivityTimeout(120_000);
- check();
- const process = await container.exec(['/usr/local/bin/node', profile.entry], {
- // Native exec requires numeric uid:gid; the pinned image's node user
- // is 1000:1000. This selects file ownership, not an isolation boundary.
- user: '1000:1000',
- env: profile.env,
- stdin: 'pipe',
- stdout: 'pipe',
- stderr: 'pipe',
- });
- check();
- const observed = await container.inspect();
- check();
- if (observed?.image !== image) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');
- if (!process.stdin) throw new ContainerJobFailure('WORKER_FAILED');
- const write = async () => {
- const writer = process.stdin!.getWriter();
- try {
- await writer.write(request);
- await writer.close();
- } finally {
- writer.releaseLock();
- }
- };
- const [, stdout, , exitCode] = await Promise.all([
- write(),
- capture(process.stdout, controls.maxResponseBytes, check),
- capture(process.stderr, STDERR_BYTES, check),
- process.exitCode,
- ]);
- check();
- if (exitCode !== 0 || stdout.byteLength === 0)
- throw new ContainerJobFailure('WORKER_FAILED');
- return stdout;
- };
- return { output: await Promise.race([execute(), stopped]), image };
- } catch (error) {
- failure =
- error instanceof ContainerJobFailure ? error : new ContainerJobFailure('WORKER_FAILED');
- throw failure;
- } finally {
- closing = true;
- clearTimeout(timer);
- controls.signal?.removeEventListener('abort', onAbort);
- // A process kill can leave children running. Wait for destruction of the VM
- // before accepting output or releasing its admission reservation.
- await destroyContainer(container);
- await this.context.storage.put('job', {
- ...job,
- state: 'finished',
- outcome: failure?.code ?? 'completed',
- } satisfies JobRecord);
- await this.context.storage.deleteAlarm();
- }
- }
-
- async alarm(): Promise<void> {
- const job = await this.context.storage.get<JobRecord>('job');
- if (!job || job.state === 'finished') {
- await this.context.storage.deleteAlarm();
- return;
- }
- // Coalesce an at-least-once alarm with a live parent cancellation instead of
- // starting a second cleanup while the run still owns its destruction.
- if (job.cancelled) return this.cancel();
- if (Date.now() < job.deadlineAt) {
- await this.context.storage.setAlarm(job.deadlineAt);
- return;
- }
- await this.recover(job);
- }
-
- private async recover(job: JobRecord): Promise<void> {
- const container = this.context.container;
- if (!container) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');
- try {
- await destroyContainer(container);
- await this.context.storage.put('job', {
- ...job,
- state: 'finished',
- outcome: job.cancelled ? 'CANCELLED' : 'DEADLINE_EXCEEDED',
- } satisfies JobRecord);
- await this.context.storage.deleteAlarm();
- } catch {
- await this.context.storage.setAlarm(Date.now() + 30_000);
- throw new ContainerJobFailure('CLEANUP_FAILED');
- }
- }
-}
-
-export class ContainerEvaluationJob extends ContainerExecutionJob {
- constructor(context: Pick<DurableObjectState, 'container' | 'storage'>) {
- super(context, 'evaluation');
- }
-}
-
-export class ContainerRenderJob extends ContainerExecutionJob {
- constructor(context: Pick<DurableObjectState, 'container' | 'storage'>) {
- super(context, 'render');
- }
-}
diff --git a/hosting/src/deletion-actions.ts b/hosting/src/deletion-actions.ts
deleted file mode 100644
index 619cda2e..00000000
--- a/hosting/src/deletion-actions.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import { IDENTITY_ISSUERS } from './accounts';
-import { D1AccountDeletions } from './account-deletions';
-import { deletionStatusPage } from './account-page';
-import type { SignInEnv } from './auth';
-import { BROWSER_COOKIE_ATTRIBUTES, browserToken, randomBrowserToken } from './browser-cookies';
-import {
- D1BrowserSessions,
- clearBrowserSessionCookie,
- type BrowserSession,
-} from './browser-sessions';
-import { githubAuthorizationUrl, githubIdentity } from './github';
-import { googleAuthorizationUrl, googleIdentity } from './google';
-import { HttpFailure, sha256 } from './http';
-import type { SignInProvider } from './login-intents';
-
-const COOKIE = '__Host-kiln-delete';
-const RECEIPT_COOKIE = '__Host-kiln-deletion-receipt';
-const clearCookie = `${COOKIE}=; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=0`;
-const denied = () => new HttpFailure(403, 'Account deletion could not be confirmed');
-const invalid = () =>
- new HttpFailure(
- 400,
- 'Invalid or expired deletion confirmation; return to your account to start again',
- );
-const hash = (origin: string, kind: 'state' | 'binding', value: string) =>
- sha256(JSON.stringify(['kiln-delete-action-v1', origin, kind, value]));
-
-export async function beginDeletionAction(
- request: Request,
- origin: string,
- env: SignInEnv,
-): Promise<Response> {
- if (request.method !== 'POST')
- return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });
- if (new URL(request.url).search || request.headers.get('origin') !== origin) throw denied();
- if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')
- throw new HttpFailure(415, 'Expected form data');
- const form = await request.formData(),
- fields = ['csrf', 'provider', 'confirmation'];
- if (
- fields.some((field) => form.getAll(field).length !== 1) ||
- [...form.keys()].some((field) => !fields.includes(field))
- )
- throw denied();
- const provider = form.get('provider');
- if (
- (provider !== 'google' && provider !== 'github') ||
- form.get('confirmation') !== 'delete-my-account'
- )
- throw denied();
- const proof = await new D1BrowserSessions(env.ACCOUNTS, origin).authorizeForm(
- request,
- String(form.get('csrf')),
- );
- const flow = {
- state: `kd1_${randomBrowserToken()}`,
- verifier: randomBrowserToken(),
- nonce: randomBrowserToken(),
- selectAccount: true,
- };
- const binding = randomBrowserToken(),
- now = Date.now();
- const previous = browserToken(request, origin, COOKIE);
- const database = env.ACCOUNTS.withSession('first-primary');
- const rows = await database.batch([
- database
- .prepare(`DELETE FROM kiln_deletion_actions WHERE state_hash IN
- (SELECT state_hash FROM kiln_deletion_actions WHERE expires_at<=? LIMIT 128)`)
- .bind(now),
- database
- .prepare('DELETE FROM kiln_deletion_actions WHERE binding_hash=?')
- .bind(previous ? await hash(origin, 'binding', previous) : ''),
- database
- .prepare(`INSERT INTO kiln_deletion_actions
- (state_hash,binding_hash,session_hash,account_id,account_epoch,provider,verifier,nonce,expires_at)
- SELECT ?,?,s.token_hash,s.account_id,s.account_epoch,?,?,?,? FROM kiln_browser_sessions s
- JOIN kiln_accounts a ON a.id=s.account_id
- WHERE s.token_hash=? AND s.account_id=? AND s.account_epoch=? AND s.csrf=?
- AND s.expires_at>? AND s.idle_expires_at>? AND a.state='active' AND a.authorization_epoch=s.account_epoch
- AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=a.id AND i.issuer=?)
- AND (SELECT COUNT(*) FROM kiln_deletion_actions WHERE account_id=a.id)<4
- AND (SELECT COUNT(*) FROM kiln_deletion_actions)<4096 RETURNING state_hash`)
- .bind(
- await hash(origin, 'state', flow.state),
- await hash(origin, 'binding', binding),
- provider,
- flow.verifier,
- flow.nonce,
- now + 300_000,
- proof.binding,
- proof.accountId,
- proof.accountEpoch,
- proof.csrf,
- now,
- now,
- IDENTITY_ISSUERS[provider],
- ),
- ]);
- if (rows[2]?.results.length !== 1) throw denied();
- const location =
- provider === 'google'
- ? await googleAuthorizationUrl(origin, flow, env, request.signal)
- : await githubAuthorizationUrl(origin, flow.state, flow.verifier, env, true);
- return new Response(null, {
- status: 302,
- headers: {
- location,
- 'set-cookie': `${COOKIE}=${binding}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=300`,
- },
- });
-}
-
-export async function finishDeletionAction(
- request: Request,
- origin: string,
- env: SignInEnv,
- provider: SignInProvider,
-): Promise<Response> {
- const url = new URL(request.url),
- state = url.searchParams.get('state') ?? '';
- const binding = browserToken(request, origin, COOKIE);
- if (
- request.method !== 'GET' ||
- url.pathname !== `/oauth/${provider}/callback` ||
- url.searchParams.getAll('state').length !== 1 ||
- !/^kd1_[a-f0-9]{64}(?![\s\S])/.test(state) ||
- !binding
- )
- throw invalid();
- let proof: BrowserSession;
- try {
- proof = await new D1BrowserSessions(env.ACCOUNTS, origin).read(request);
- } catch (error) {
- if (error instanceof HttpFailure && error.status === 401) throw invalid();
- throw error;
- }
- const flow = await env.ACCOUNTS.withSession('first-primary')
- .prepare(`DELETE FROM kiln_deletion_actions WHERE state_hash=? AND binding_hash=? AND provider=?
- AND session_hash=? AND account_id=? AND account_epoch=? AND expires_at>?
- AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_deletion_actions.account_id
- AND a.state='active' AND a.authorization_epoch=kiln_deletion_actions.account_epoch)
- RETURNING verifier,nonce,expires_at AS expiresAt`)
- .bind(
- await hash(origin, 'state', state),
- await hash(origin, 'binding', binding),
- provider,
- proof.binding,
- proof.accountId,
- proof.accountEpoch,
- Date.now(),
- )
- .first<{ verifier: string; nonce: string; expiresAt: number }>();
- if (!flow) throw invalid();
- if (url.searchParams.has('error'))
- return new Response('Deletion was cancelled. Your account is unchanged.', {
- status: 400,
- headers: { 'set-cookie': clearCookie },
- });
- const code = url.searchParams.get('code');
- if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1) throw invalid();
- const identity =
- provider === 'google'
- ? await googleIdentity(request, origin, { ...flow, state }, env)
- : await githubIdentity(code, flow.verifier, origin, env);
- if (Date.now() >= flow.expiresAt || identity.issuer !== IDENTITY_ISSUERS[provider])
- throw invalid();
- const receipt = randomBrowserToken();
- await new D1AccountDeletions(env.ACCOUNTS, origin).request(proof, identity, receipt);
- const headers = new Headers({ location: '/account/deletion' });
- headers.append('set-cookie', clearCookie);
- headers.append('set-cookie', clearBrowserSessionCookie);
- headers.append(
- 'set-cookie',
- `${RECEIPT_COOKIE}=${receipt}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=2592000`,
- );
- return new Response(null, { status: 303, headers });
-}
-
-export async function accountDeletionStatus(
- request: Request,
- database: D1Database,
- origin: string,
-): Promise<Response> {
- if (new URL(request.url).search)
- throw new HttpFailure(400, 'Query parameters are not supported on deletion status');
- if (request.method !== 'GET')
- return new Response('Method not allowed', { status: 405, headers: { allow: 'GET' } });
- const receipt = browserToken(request, origin, RECEIPT_COOKIE);
- return deletionStatusPage(await new D1AccountDeletions(database, origin).status(receipt));
-}
diff --git a/hosting/src/deletion-recovery.ts b/hosting/src/deletion-recovery.ts
deleted file mode 100644
index feb57ed4..00000000
--- a/hosting/src/deletion-recovery.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import type { OAuthHelpers } from '@cloudflare/workers-oauth-provider';
-import { D1AccountDeletions, type DeletionPorts } from './account-deletions';
-import type { TenantEnv } from './gateway';
-import { readBounded } from './http';
-import { tenantForAccount } from './tenant-identity';
-
-export function deletionPorts(
- env: TenantEnv & { ACCOUNTS: D1Database },
- origin: string,
- oauth: Pick<OAuthHelpers, 'listUserGrants' | 'revokeGrant'>,
-): DeletionPorts {
- return {
- async retireCompute(accountId) {
- if (!env.NATIVE_COMPUTE) throw new Error('Compute retirement is not configured');
- await env.NATIVE_COMPUTE.retireTenant(await tenantForAccount(origin, accountId));
- },
- async retireStorage(accountId) {
- const tenant = await tenantForAccount(origin, accountId);
- const response = await env.TENANTS.getByName(tenant).fetch(
- 'https://tenant.internal/internal/account-deletion',
- { method: 'POST' },
- );
- if (!response.ok) {
- void response.body?.cancel().catch(() => {});
- throw new Error('Storage retirement failed');
- }
- const value: unknown = JSON.parse(
- new TextDecoder().decode(await readBounded(response.body, 1024)),
- );
- if (!value || typeof value !== 'object' || Array.isArray(value))
- throw new Error('Invalid storage retirement response');
- const result = value as Record<string, unknown>;
- if (
- Object.keys(result).some(
- (key) => !['state', 'pendingWrites', 'remainingObjects'].includes(key),
- ) ||
- !['retiring', 'purged'].includes(String(result.state)) ||
- !Number.isSafeInteger(result.pendingWrites) ||
- Number(result.pendingWrites) < 0 ||
- !Number.isSafeInteger(result.remainingObjects) ||
- Number(result.remainingObjects) < 0
- )
- throw new Error('Invalid storage retirement response');
- if (
- result.state === 'purged' &&
- (result.pendingWrites !== 0 || result.remainingObjects !== 0)
- )
- throw new Error('Storage purge is unconfirmed');
- return result.state === 'purged';
- },
- async revokeGrants(accountId) {
- const database = env.ACCOUNTS.withSession('first-primary');
- const known = await database
- .prepare(
- 'SELECT DISTINCT grant_id AS id FROM kiln_connections WHERE account_id=? AND grant_id IS NOT NULL LIMIT 4',
- )
- .bind(accountId)
- .all<{ id: string }>();
- const listed = await oauth.listUserGrants(accountId, { limit: 4 });
- if (listed.items.length > 4 || listed.items.some((grant) => grant.userId !== accountId))
- throw new Error('Invalid grant cleanup inventory');
- const ids = [
- ...new Set([...known.results.map((row) => row.id), ...listed.items.map((row) => row.id)]),
- ].slice(0, 4);
- for (const id of ids) {
- if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}(?![\s\S])/.test(id))
- throw new Error('Invalid grant cleanup identifier');
- await oauth.revokeGrant(id, accountId);
- await database
- .prepare('UPDATE kiln_connections SET grant_id=NULL WHERE account_id=? AND grant_id=?')
- .bind(accountId, id)
- .run();
- }
- // Empty eventually-consistent KV is not an immediate erasure guarantee.
- // Primary deletion already denies all old grants. Late/stale library records
- // retain their configured TTL; privacy documentation must say so.
- return ids.length === 0 && !listed.cursor;
- },
- };
-}
-
-export function recoverAccountDeletions(
- env: TenantEnv & { ACCOUNTS: D1Database },
- origin: string,
- oauth: OAuthHelpers,
-) {
- return new D1AccountDeletions(env.ACCOUNTS, origin, deletionPorts(env, origin, oauth)).recover();
-}
diff --git a/hosting/src/download-path.ts b/hosting/src/download-path.ts
deleted file mode 100644
index 95ceded6..00000000
--- a/hosting/src/download-path.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/** One exact route grammar for native links, browser reads and sign-in resumption. */
-export const DOWNLOAD_FILES = new Set([
- 'asset.glb',
- 'source.kiln.js',
- 'preview.png',
- 'manifest.json',
- 'materials.kiln.json',
-]);
-export const DOWNLOAD_TOKEN = /^[a-f0-9]{64}(?![\s\S])/;
-
-export function parseDownloadPath(path: unknown): { token: string; filename: string } | null {
- if (typeof path !== 'string') return null;
- const parts = path.match(/^\/downloads\/([a-f0-9]{64})\/([a-z.]+)(?![\s\S])/);
- if (!parts || !DOWNLOAD_FILES.has(parts[2]!)) return null;
- return { token: parts[1]!, filename: parts[2]! };
-}
-
-export function validLoginReturn(path: unknown): path is string {
- return path === '/account' || parseDownloadPath(path) !== null;
-}
diff --git a/hosting/src/edge-mcp.ts b/hosting/src/edge-mcp.ts
deleted file mode 100644
index feb90149..00000000
--- a/hosting/src/edge-mcp.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import {
- createMcpHandler,
- Server,
- ProtocolError,
- ProtocolErrorCode,
- type Tool,
-} from '@modelcontextprotocol/server';
-import { createDiscoveryService } from '../../src/discovery/service';
-import { discoveryInputSchema } from '../../src/discovery/query-schema';
-import { describeInputError, schemaFields } from '../../src/tools/actions';
-import { parseCatalog } from '../../src/discovery/catalog-schema';
-import { createLexicalDiscoveryIndex } from '../../src/discovery/lexical-index';
-import { REMOVED_AUTHORING_HELPERS } from '../../src/geometry-catalog';
-import manifest from './generated/edge-manifest.json';
-import { privateResponse, readBounded } from './http';
-import { createPublicTools, hostedInstructions } from './public-tools';
-
-const surface = createPublicTools(manifest.tools as unknown as Tool[]);
-const catalog = parseCatalog(manifest.catalog);
-const discover = createDiscoveryService(
- catalog,
- createLexicalDiscoveryIndex(catalog),
- async () => {
- throw new Error('Live capabilities require the native host');
- },
- REMOVED_AUTHORING_HELPERS,
-);
-const fixedCache = { ttlMs: 86_400_000, cacheScope: 'public' as const };
-const handler = createMcpHandler(
- () => {
- const server = new Server(manifest.serverInfo, {
- capabilities: manifest.capabilities,
- instructions: hostedInstructions,
- cacheHints: {
- 'server/discover': fixedCache,
- 'tools/list': fixedCache,
- 'resources/list': fixedCache,
- 'resources/templates/list': fixedCache,
- },
- });
- server.setRequestHandler('tools/list', () => ({ tools: surface.tools }));
- server.setRequestHandler('resources/list', () => ({ resources: manifest.resources }));
- server.setRequestHandler('resources/templates/list', () => ({
- resourceTemplates: manifest.resourceTemplates,
- }));
- server.setRequestHandler('tools/call', async (request) => {
- if (
- request.params.name !== 'kiln_discover' ||
- !surface.resolve(request.params.name, request.params.arguments ?? {})
- )
- throw new ProtocolError(
- ProtocolErrorCode.InvalidParams,
- 'Unknown tool or invalid tool request',
- );
- try {
- const result = await discover(request.params.arguments ?? {});
- const { text, textTruncated, ...structured } = result;
- const content = textTruncated
- ? JSON.stringify(structured)
- : structured.suggestions?.length
- ? `${text}\nSuggestions: ${structured.suggestions.join(', ')}`
- : text;
- return { content: [{ type: 'text', text: content }] };
- } catch (error) {
- const text =
- describeInputError('kiln_discover', error, {
- fields: schemaFields(discoveryInputSchema),
- }) ?? 'Discovery is temporarily unavailable';
- // Match the pinned engine's diagnostic redaction without importing its Node-only core.
- // Native-host parity tests cover both schema errors and caller-supplied path keys.
- const safe = text.replace(
- /(?<![A-Za-z0-9])(?:[A-Za-z]:[\\/]|\\\\[^\s"'`]+|\/(?:home|Users|tmp|var|opt|mnt|root|srv|private)\/)[^\s"'`)\]]*/gu,
- '<local path>',
- );
- return { isError: true, content: [{ type: 'text', text: safe }] };
- }
- });
- return server;
- },
- { legacy: 'stateless', maxRequestBodySize: 1024 * 1024, maxSubscriptions: 0, onerror: () => {} },
-);
-
-const record = (value: unknown): value is Record<string, unknown> =>
- value !== null && typeof value === 'object' && !Array.isArray(value);
-
-function nativeCall(value: unknown): { params?: Record<string, unknown> } | undefined {
- if (
- !record(value) ||
- value.jsonrpc !== '2.0' ||
- !(
- typeof value.id === 'string' ||
- (typeof value.id === 'number' && Number.isFinite(value.id))
- ) ||
- !record(value.params)
- )
- return undefined;
- if (value.method === 'resources/read')
- return typeof value.params.uri === 'string' ? {} : undefined;
- if (value.method !== 'tools/call' || typeof value.params.name !== 'string') return undefined;
- if (value.params.arguments !== undefined && !record(value.params.arguments)) return undefined;
- const resolved = surface.resolve(value.params.name, value.params.arguments ?? {});
- if (!resolved || value.params.name === 'kiln_discover') return undefined;
- return resolved.name === value.params.name ? {} : { params: { ...value.params, ...resolved } };
-}
-
-/** Called only after OAuth and account checks, over the bounded credential-free request. */
-export async function routeEdgeMcp(request: Request): Promise<Response | Request> {
- if (request.method === 'POST') {
- // Inspect a bounded copy; the original stream remains available to native admission.
- const bytes = await readBounded(request.clone().body, 1024 * 1024, request.signal);
- let message: unknown;
- try {
- message = JSON.parse(
- new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes),
- );
- } catch {
- /* The maintained MCP handler owns malformed-message responses. */
- }
- if (record(message) && record(message.params)) {
- const method = request.headers.get('mcp-method');
- const name = request.headers.get('mcp-name');
- const toolName = typeof message.params.name === 'string' ? message.params.name : '';
- const matchesName =
- name === toolName ||
- (/^[\x20-\x7e]+$/.test(toolName) && name === `=?base64?${btoa(toolName)}?=`);
- if (
- (method !== null && method !== message.method) ||
- (name !== null && message.method === 'tools/call' && !matchesName)
- ) {
- return privateResponse(
- Response.json(
- {
- jsonrpc: '2.0',
- id:
- typeof message.id === 'string' || typeof message.id === 'number'
- ? message.id
- : null,
- error: {
- code: ProtocolErrorCode.InvalidParams,
- message: 'MCP routing headers disagree with the request',
- },
- },
- { status: 400 },
- ),
- );
- }
- }
- const native = nativeCall(message);
- if (native) {
- if (!native.params) return request;
- const headers = new Headers(request.headers);
- // Modern MCP checks routing metadata as well as the JSON envelope.
- // Rewrite only a header already matched against the public operation above.
- if (headers.has('mcp-name')) headers.set('mcp-name', String(native.params.name));
- headers.delete('content-length');
- return new Request(request, {
- headers,
- body: JSON.stringify({ ...(message as object), params: native.params }),
- });
- }
- }
- return privateResponse(await handler.fetch(request));
-}
diff --git a/hosting/src/evaluation-request.ts b/hosting/src/evaluation-request.ts
deleted file mode 100644
index 67434153..00000000
--- a/hosting/src/evaluation-request.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { ContainerJobFailure, type ContainerEvaluationJob } from './container-job';
-import { HttpFailure, privateResponse, readBounded, serviceFailure } from './http';
-import { EXECUTION_PROFILES, type ExecutionKind } from './execution-profiles';
-
-const allowedHeaders = new Set([
- 'content-type',
- 'content-length',
- 'x-kiln-deadline-ms',
- 'x-kiln-max-response-bytes',
- // Fetch implementations add these transport fields. None selects identity or work.
- 'accept',
- 'accept-encoding',
- 'accept-language',
- 'connection',
- 'host',
- 'user-agent',
- 'sec-fetch-mode',
-]);
-type ExecutionJob = Pick<ContainerEvaluationJob, 'run'> &
- Partial<Pick<ContainerEvaluationJob, 'executionImage'>>;
-
-function limit(header: string | null, max: number): number {
- if (header === null || !/^[1-9]\d{0,8}$/.test(header) || Number(header) > max)
- throw new HttpFailure(400, 'Invalid evaluation limit');
- return Number(header);
-}
-
-/**
- * Private, single-job HTTP boundary. The outer controller supplies the fresh DO
- * and holds admission; this handler cannot choose a tenant, image or executable.
- * Never expose this route directly from a public Worker.
- */
-async function handleExecutionRequest(
- request: Request,
- job: ExecutionJob,
- kind: ExecutionKind,
-): Promise<Response> {
- const profile = EXECUTION_PROFILES[kind];
- try {
- if (request.url !== profile.url || request.method !== 'POST')
- throw new HttpFailure(400, 'Invalid evaluation request');
- for (const [name, value] of request.headers)
- if (!allowedHeaders.has(name) || value.length > 512)
- throw new HttpFailure(400, 'Invalid evaluation header');
- if (request.headers.get('content-type') !== 'application/json')
- throw new HttpFailure(415, 'Evaluation requires application/json');
- const deadlineMs = limit(request.headers.get('x-kiln-deadline-ms'), profile.deadlineMs);
- const maxResponseBytes = limit(
- request.headers.get('x-kiln-max-response-bytes'),
- profile.responseBytes,
- );
- const declared = limit(request.headers.get('content-length'), profile.requestBytes);
- const deadlineAt = Date.now() + deadlineMs;
- const reading = new AbortController();
- const cancelRead = () => reading.abort();
- let expired = false;
- request.signal.addEventListener('abort', cancelRead, { once: true });
- if (request.signal.aborted) cancelRead();
- const timer = setTimeout(() => {
- expired = true;
- reading.abort();
- }, deadlineMs);
- let body: Uint8Array<ArrayBuffer>;
- try {
- body = await readBounded(request.body, profile.requestBytes, reading.signal);
- } catch (error) {
- if (expired) throw new HttpFailure(504, 'Evaluation deadline exceeded');
- throw error;
- } finally {
- clearTimeout(timer);
- request.signal.removeEventListener('abort', cancelRead);
- }
- if (body.byteLength !== declared) throw new HttpFailure(400, 'Invalid evaluation length');
- const remaining = deadlineAt - Date.now();
- if (remaining < 1) throw new HttpFailure(504, 'Evaluation deadline exceeded');
- // No independent timeout race here: run owns the deadline, durable watchdog
- // and verified VM destruction. Aborting HTTP must not abandon that cleanup.
- const output = await job.run(body, {
- deadlineMs: remaining,
- maxResponseBytes,
- signal: request.signal,
- });
- if (
- !(output instanceof Uint8Array) ||
- output.byteLength === 0 ||
- output.byteLength > maxResponseBytes
- )
- throw new Error('Invalid evaluation output');
- const headers = new Headers({
- 'content-type': 'application/json',
- 'content-length': String(output.byteLength),
- });
- if (kind === 'evaluation') {
- const image = job.executionImage?.(output);
- const digest =
- typeof image === 'string' && image.length <= 512
- ? /^[a-zA-Z0-9._:/-]+@(sha256:[a-f0-9]{64})(?![\s\S])/.exec(image)?.[1]
- : undefined;
- if (!digest) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');
- // This header is outside the VM's stdout and is never copied from a request.
- headers.set('x-kiln-execution-image', digest);
- }
- return privateResponse(
- new Response(output, {
- headers,
- }),
- );
- } catch (error) {
- void request.body?.cancel().catch(() => {});
- if (error instanceof ContainerJobFailure) {
- const statuses = {
- INPUT_INVALID: 400,
- JOB_ALREADY_USED: 409,
- ISOLATION_UNAVAILABLE: 503,
- WORKER_FAILED: 503,
- OUTPUT_LIMIT_EXCEEDED: 502,
- DEADLINE_EXCEEDED: 504,
- CANCELLED: 499,
- CLEANUP_FAILED: 503,
- } as const;
- return privateResponse(
- new Response('Evaluation did not complete', { status: statuses[error.code] }),
- );
- }
- return privateResponse(serviceFailure(error));
- }
-}
-
-export const handleEvaluationRequest = (request: Request, job: ExecutionJob) =>
- handleExecutionRequest(request, job, 'evaluation');
-
-export const handleRenderRequest = (request: Request, job: Pick<ContainerEvaluationJob, 'run'>) =>
- handleExecutionRequest(request, job, 'render');
diff --git a/hosting/src/evaluation-worker.ts b/hosting/src/evaluation-worker.ts
deleted file mode 100644
index 5498f307..00000000
--- a/hosting/src/evaluation-worker.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { DurableObject } from 'cloudflare:workers';
-import { ContainerEvaluationJob } from './container-job';
-import { handleEvaluationRequest } from './evaluation-request';
-
-/** Only the private dispatcher receives this binding; never the public gateway. */
-export class KilnEvaluationJob extends DurableObject {
- private readonly job = new ContainerEvaluationJob(this.ctx);
-
- fetch(request: Request): Promise<Response> {
- return handleEvaluationRequest(request, this.job);
- }
-
- cancel(): Promise<void> {
- return this.job.cancel();
- }
-
- alarm(): Promise<void> {
- return this.job.alarm();
- }
-}
-
-export default {
- fetch(): Response {
- return new Response('Not found', { status: 404 });
- },
-};
diff --git a/hosting/src/execution-profiles.ts b/hosting/src/execution-profiles.ts
deleted file mode 100644
index 509e1101..00000000
--- a/hosting/src/execution-profiles.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { RENDER_LIMITS } from './render-limits';
-
-/** Host-selected profiles only. No HTTP or tool field chooses code, image or environment. */
-export const EXECUTION_PROFILES = {
- evaluation: {
- url: 'http://kiln-evaluator.internal/evaluate',
- image: 'kiln',
- entry: '/opt/kiln/evaluate.mjs',
- env: { KILN_RENDER: 'cpu' } as Record<string, string>,
- requestBytes: 4 * 1024 * 1024,
- responseBytes: 8 * 1024 * 1024,
- deadlineMs: 60_000,
- },
- render: {
- url: 'http://kiln-renderer.internal/render',
- image: 'renderer',
- entry: '/opt/kiln/render.mjs',
- env: {} as Record<string, string>,
- requestBytes: RENDER_LIMITS.requestBytes,
- responseBytes: RENDER_LIMITS.responseBytes,
- deadlineMs: RENDER_LIMITS.deadlineMs,
- },
-} as const;
-export type ExecutionKind = keyof typeof EXECUTION_PROFILES;
diff --git a/hosting/src/gateway.ts b/hosting/src/gateway.ts
deleted file mode 100644
index ce5ce052..00000000
--- a/hosting/src/gateway.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { insufficientScope, type OAuthResourceContext } from '@cloudflare/workers-oauth-provider';
-import { boundedRequest, HttpFailure } from './http';
-import { tenantForAccount } from './tenant-identity';
-import type { KilnCompute } from './admission-worker';
-import { routeEdgeMcp } from './edge-mcp';
-import { limitAccount, type RequestLimitEnv } from './request-limits';
-
-export interface TenantEnv {
- TENANTS: DurableObjectNamespace;
- NATIVE_COMPUTE?: Service<KilnCompute>;
-}
-
-export async function forwardTenant(
- request: Request,
- env: TenantEnv & Pick<RequestLimitEnv, 'ACCOUNT_REQUEST_LIMIT'>,
- ctx: OAuthResourceContext<unknown>,
- origin: string,
-): Promise<Response> {
- if (!ctx.auth.scope.includes('kiln:use')) return insufficientScope(ctx.auth, ['kiln:use']);
- const userId = ctx.auth.userId;
- if (!userId || !/^ka_[a-f0-9]{32}$/.test(userId)) throw new HttpFailure(401, 'Invalid identity');
- const limited = await limitAccount(request, env, origin, userId);
- if (limited) return limited;
- const url = new URL(request.url);
- const isMcp = url.pathname === '/mcp';
- const isArtifact = /^\/mcp\/artifacts\/[A-Za-z0-9_-]{16,128}$/.test(url.pathname);
- if (!isMcp && !isArtifact) return new Response('Not found', { status: 404 });
- const allowed = isMcp ? ['GET', 'POST', 'DELETE'] : ['GET', 'HEAD'];
- if (!allowed.includes(request.method))
- return new Response('Method not allowed', {
- status: 405,
- headers: { allow: allowed.join(', ') },
- });
- if (
- request.method === 'POST' &&
- request.headers.get('content-type')?.split(';')[0] !== 'application/json'
- ) {
- throw new HttpFailure(415, 'MCP requires application/json');
- }
- const bounded = await boundedRequest(request, 1024 * 1024);
- // Only verified authorization identity selects the object. Token, client id,
- // session id, source refs, cookies and caller tenant headers cannot select it.
- const tenant = await tenantForAccount(origin, userId);
- const headers = new Headers();
- for (const name of [
- 'accept',
- 'content-type',
- 'mcp-protocol-version',
- 'mcp-method',
- 'mcp-name',
- 'mcp-session-id',
- 'last-event-id',
- ]) {
- const value = bounded.headers.get(name);
- if (value && value.length > 4096) throw new HttpFailure(431, 'Header too large');
- if (value) headers.set(name, value);
- }
- const internal = new Request(`https://tenant.internal${url.pathname}`, {
- method: bounded.method,
- headers,
- body: bounded.body,
- signal: bounded.signal,
- redirect: 'manual',
- });
- if (isMcp) {
- const edge = await routeEdgeMcp(internal);
- if (edge instanceof Response) return edge;
- if (!env.NATIVE_COMPUTE) throw new HttpFailure(503, 'Native compute is not configured');
- return env.NATIVE_COMPUTE.dispatch(tenant, edge);
- }
- return env.TENANTS.getByName(tenant).fetch(internal);
-}
diff --git a/hosting/src/generated/edge-manifest.json b/hosting/src/generated/edge-manifest.json
deleted file mode 100644
index be15f200..00000000
--- a/hosting/src/generated/edge-manifest.json
+++ /dev/null
@@ -1,12655 +0,0 @@
-{
- "kind": "kiln.hosted-edge.v1",
- "serverInfo": {
- "name": "kiln",
- "version": "1.0.0"
- },
- "capabilities": {
- "tools": {},
- "resources": {},
- "extensions": {
- "io.modelcontextprotocol/ui": {
- "mimeTypes": [
- "text/html;profile=mcp-app"
- ]
- }
- }
- },
- "instructions": "Kiln turns JavaScript you write into GLB assets and returns rendered views. Work by reference: send a program once to kiln_validate or kiln_render, keep the returned programRef exactly, and use it for every later render, inspect, kiln_source and kiln_edit call; never resend a program to change part of it. Call kiln_discover first for helper contracts, with capabilities:true for the host's runtime, project and camera facts. Read viewFidelity before judging materials: a CPU view shows shape, not material; GPU views need the render service in render-service/. Agent Skills for authoring, refining, QA and scenes ship in skills/ beside this server's dist/; read the matching SKILL.md first.",
- "tools": [
- {
- "name": "kiln_discover",
- "description": "Discover Kiln operations, assemblies, recipes, tool-input shapes and current host capabilities. Omit arguments for a compact overview. Search with ordinary modeling language using query; refine with family, kind or tags. Fetch complete contracts/examples with ids (up to six exact IDs, executable names or shape: ids). Overview/search pages default to six summaries. Recipes guide construction without restricting the asset. Search runs locally without models or network calls.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "minLength": 1,
- "maxLength": 500
- },
- "ids": {
- "minItems": 1,
- "maxItems": 6,
- "type": "array",
- "items": {
- "type": "string",
- "minLength": 1,
- "maxLength": 120
- }
- },
- "overview": {
- "type": "boolean",
- "const": true
- },
- "capabilities": {
- "type": "boolean",
- "const": true
- },
- "family": {
- "type": "string",
- "minLength": 1,
- "maxLength": 120
- },
- "kind": {
- "type": "string",
- "enum": [
- "operation",
- "assembly",
- "recipe",
- "shape"
- ]
- },
- "tags": {
- "minItems": 1,
- "maxItems": 8,
- "type": "array",
- "items": {
- "type": "string",
- "minLength": 1,
- "maxLength": 120
- }
- },
- "offset": {
- "type": "integer",
- "minimum": 0,
- "maximum": 10000
- },
- "limit": {
- "type": "integer",
- "minimum": 1,
- "maximum": 12
- }
- },
- "additionalProperties": false
- },
- "annotations": {
- "readOnlyHint": true,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_renderer",
- "description": "Inspect status, or reprobe after renderer setup/repair to refresh this session and reset failed starts. Never installs, starts, stops or renders. Preserves CPU/local/remote selection; environment/credential changes require a host restart. Read viewFidelity after rendering.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "action": {
- "default": "status",
- "type": "string",
- "enum": [
- "status",
- "reprobe"
- ]
- }
- },
- "additionalProperties": false
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_validate",
- "description": "Check program syntax, sandbox rules and retired globals before building. Returns findings with codes, lines and repair hints where available; use kiln_render to evaluate geometry and see the asset. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "code": {
- "description": "New source.",
- "type": "string"
- },
- "programRef": {
- "type": "string",
- "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",
- "description": "Returned p_ handle or full sha256 ref."
- }
- }
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_render",
- "description": "Build and return metrics, part paths and images. If partsTruncated, use kiln_inspect listParts. Omit capture for six views, preset/cells for orbit grids, or kiln.capture.v1/v2 shots for exact orthographic/perspective cameras; v2 adds hide. Check viewFidelity before judging materials. Failed builds return errors without images. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "code": {
- "description": "New source.",
- "type": "string"
- },
- "capture": {
- "description": "Omit for six views; preset/cells for orbit sheets. Use kiln.capture.v1 or v2 with 1..9 shots for exact cameras. v2 adds hide: exact paths or unique names. Framing retains subject bounds.",
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "version": {
- "type": "string",
- "enum": [
- "kiln.capture.v1",
- "kiln.capture.v2"
- ]
- },
- "shots": {
- "minItems": 1,
- "maxItems": 9,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string"
- },
- "subject": {
- "type": "object",
- "properties": {
- "path": {
- "type": "string"
- },
- "name": {
- "type": "string"
- }
- },
- "additionalProperties": false
- },
- "visibility": {
- "type": "string",
- "enum": [
- "context",
- "isolate"
- ]
- },
- "hide": {
- "maxItems": 64,
- "type": "array",
- "items": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1024
- }
- },
- "camera": {
- "oneOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "orbit"
- },
- "azimuthDeg": {
- "type": "number"
- },
- "elevationDeg": {
- "type": "number"
- },
- "relativeTo": {
- "type": "string",
- "enum": [
- "world",
- "asset",
- "part"
- ]
- },
- "padding": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "explicit"
- },
- "projection": {
- "type": "string",
- "enum": [
- "orthographic",
- "perspective"
- ]
- },
- "position": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "target": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "relativeTo": {
- "type": "string",
- "enum": [
- "world",
- "asset",
- "part",
- "local"
- ]
- },
- "frame": {
- "type": "object",
- "properties": {
- "origin": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "rotation": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- }
- },
- "additionalProperties": false
- },
- "framing": {
- "type": "string",
- "enum": [
- "explicit",
- "bounds"
- ]
- },
- "padding": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100
- },
- "targetOffset": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "up": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "halfHeight": {
- "type": "number",
- "exclusiveMinimum": 0
- },
- "fovDeg": {
- "type": "number",
- "exclusiveMinimum": 0,
- "exclusiveMaximum": 180
- },
- "near": {
- "type": "number",
- "exclusiveMinimum": 0
- },
- "far": {
- "type": "number",
- "exclusiveMinimum": 0
- }
- },
- "required": [
- "type",
- "projection",
- "position"
- ],
- "additionalProperties": false
- }
- ]
- }
- },
- "additionalProperties": false
- }
- },
- "cols": {
- "type": "integer",
- "minimum": 1,
- "maximum": 3
- },
- "size": {
- "type": "integer",
- "minimum": 128,
- "maximum": 2048
- },
- "output": {
- "type": "string",
- "enum": [
- "grid",
- "separate"
- ]
- },
- "backdrop": {
- "description": "neutral (default); light for dark parts, dark for light parts.",
- "type": "string",
- "enum": [
- "neutral",
- "dark",
- "light"
- ]
- }
- },
- "required": [
- "version",
- "shots"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "preset": {
- "description": "COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3.",
- "type": "string",
- "enum": [
- "1x1",
- "1x2",
- "2x1",
- "3x1",
- "2x2",
- "3x2",
- "3x3"
- ]
- },
- "cells": {
- "description": "Row-major cameras; omit for preset defaults. Count cannot exceed preset capacity (max 9).",
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "azimuthDeg": {
- "type": "number",
- "description": "0 = front, 90 = right, 180 = back, 270 = left. Wraps."
- },
- "elevationDeg": {
- "type": "number",
- "description": "0 eye level; positive above, negative below. Clamped -89..89."
- },
- "zoom": {
- "description": "Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing.",
- "type": "number"
- },
- "name": {
- "description": "Label; defaults to angles.",
- "type": "string"
- }
- },
- "required": [
- "azimuthDeg",
- "elevationDeg"
- ]
- }
- },
- "backdrop": {
- "description": "neutral (default); light for dark parts, dark for light parts.",
- "type": "string",
- "enum": [
- "neutral",
- "dark",
- "light"
- ]
- }
- },
- "additionalProperties": false
- }
- ]
- },
- "detail": {
- "description": "compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path",
- "type": "string",
- "enum": [
- "lean",
- "compact",
- "full"
- ]
- },
- "programRef": {
- "type": "string",
- "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",
- "description": "Returned p_ handle or full sha256 ref."
- },
- "projectId": {
- "description": "Project; omit for the configured default, null for standalone.",
- "anyOf": [
- {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- {
- "type": "null"
- }
- ]
- },
- "projectRevision": {
- "description": "Exact project revision.",
- "type": "string",
- "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"
- },
- "materialDependencies": {
- "description": "Pins for this call; each replaces the project pin of its resourceId.",
- "maxItems": 512,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- },
- "revisionId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "role": {
- "type": "string",
- "maxLength": 100
- }
- },
- "required": [
- "resourceId",
- "revisionId",
- "sha256"
- ],
- "additionalProperties": false
- }
- }
- }
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_screenshot_animation",
- "description": "Review animation images, poseBounds and loopClosure endpoint evidence. loopIntent is createClip({loop}); open is valid for one-shots; closed endpoints do not prove smooth velocity. Check motion, attachments and requested clearance; sampled bounds do not certify continuous contact or collision safety. Use shot for camera/subject, frameTimes for phases, and framing locked (default) or follow. Add phases when symmetry hides motion. The program must define animate(). Check viewFidelity before judging materials. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "shot": {
- "description": "One exact camera shot. Shape: kiln_discover ids [\"shape:camera-shot\"].",
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- },
- "measureParts": {
- "description": "Exact names or paths of subtrees measured together at each phase, independent of camera selection.",
- "minItems": 1,
- "maxItems": 16,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "path": {
- "type": "string"
- },
- "name": {
- "type": "string"
- }
- },
- "additionalProperties": false
- }
- },
- "frames": {
- "type": "integer",
- "minimum": 2,
- "maximum": 6
- },
- "frameTimes": {
- "description": "Ordered phase fractions 0..1; mutually exclusive with frames.",
- "minItems": 1,
- "maxItems": 9,
- "type": "array",
- "items": {
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "framing": {
- "type": "string",
- "enum": [
- "locked",
- "follow"
- ]
- },
- "size": {
- "description": "Frame size in px; default 256.",
- "type": "integer",
- "minimum": 128,
- "maximum": 1024
- },
- "detail": {
- "description": "compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path",
- "type": "string",
- "enum": [
- "lean",
- "compact",
- "full"
- ]
- },
- "code": {
- "description": "New source.",
- "type": "string"
- },
- "clip": {
- "type": "string",
- "description": "The animation clip to view, by name (e.g. \"walk\", \"attack\"). Must be one your animate() returns."
- },
- "camera": {
- "description": "Camera angle: right (default — side profile, best for leg swing + knee bend direction), front (reveals sideways/lateral motion), back, left, top, or three-quarter.",
- "type": "string"
- },
- "perFrame": {
- "description": "Return the frames as separate high-res images instead of one composite grid. Default false.",
- "type": "boolean"
- },
- "programRef": {
- "type": "string",
- "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",
- "description": "Returned p_ handle or full sha256 ref."
- },
- "projectId": {
- "description": "Project; omit for the configured default, null for standalone.",
- "anyOf": [
- {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- {
- "type": "null"
- }
- ]
- },
- "projectRevision": {
- "description": "Exact project revision.",
- "type": "string",
- "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"
- },
- "materialDependencies": {
- "description": "Pins for this call; each replaces the project pin of its resourceId.",
- "maxItems": 512,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- },
- "revisionId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "role": {
- "type": "string",
- "maxLength": 100
- }
- },
- "required": [
- "resourceId",
- "revisionId",
- "sha256"
- ],
- "additionalProperties": false
- }
- }
- },
- "required": [
- "clip"
- ]
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_view_interior",
- "description": "Render roof-off floor-plan, dollhouse, and eye-level cutaway views. Optional versioned capture selects custom roof-off shots. Select a roof by nodeName or let Kiln resolve its role/name. Review roofsHidden and warnings for unresolved occlusion. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "capture": {
- "description": "Cameras, as kiln_render capture takes them. Shape: kiln_discover ids [\"shape:capture\"].",
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- },
- "code": {
- "description": "New source.",
- "type": "string"
- },
- "nodeName": {
- "description": "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.",
- "type": "string"
- },
- "programRef": {
- "type": "string",
- "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",
- "description": "Returned p_ handle or full sha256 ref."
- },
- "projectId": {
- "description": "Project; omit for the configured default, null for standalone.",
- "anyOf": [
- {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- {
- "type": "null"
- }
- ]
- },
- "projectRevision": {
- "description": "Exact project revision.",
- "type": "string",
- "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"
- },
- "materialDependencies": {
- "description": "Pins for this call; each replaces the project pin of its resourceId.",
- "maxItems": 512,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- },
- "revisionId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "role": {
- "type": "string",
- "maxLength": 100
- }
- },
- "required": [
- "resourceId",
- "revisionId",
- "sha256"
- ],
- "additionalProperties": false
- }
- }
- }
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_inspect",
- "description": "List part paths and inspect joints, clearances and edit preservation. listParts filters names/paths with query; follow partListing.nextOffset on the same programRef/query. measure/surfacePairs return distances, not fit certificates. compare reports static changes and separate animation channel changes; paths adds complete static subtree summaries. image:false skips rendering. Otherwise use part/orbit or exact shot; check viewFidelity for materials. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "image": {
- "description": "False: requires listParts/measure/surfacePairs/compare; no image or camera controls. Default true.",
- "type": "boolean"
- },
- "detail": {
- "description": "compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path",
- "type": "string",
- "enum": [
- "lean",
- "compact",
- "full"
- ]
- },
- "listParts": {
- "description": "List exported-scene paths, including nested parts. Default 80, max 100 per page. Follow partListing.nextOffset with the same programRef/query. image:false avoids rendering.",
- "type": "object",
- "properties": {
- "query": {
- "description": "Case-insensitive substring of name or exact encoded path; not a regex.",
- "type": "string",
- "maxLength": 4096
- },
- "offset": {
- "type": "integer",
- "minimum": 0,
- "maximum": 9007199254740991
- },
- "limit": {
- "type": "integer",
- "minimum": 1,
- "maximum": 100
- },
- "placement": {
- "description": "Add world position, rotation, scale, mirroring and bounds per part; pages of 50.",
- "type": "boolean"
- }
- },
- "additionalProperties": false
- },
- "surfacePairs": {
- "description": "[from,to] pairs of exact listParts paths or unambiguous node names; check surfaceMeasurements.status and each result.",
- "minItems": 1,
- "maxItems": 12,
- "type": "array",
- "items": {
- "minItems": 2,
- "maxItems": 2,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 4096
- }
- }
- },
- "compare": {
- "description": "Static geometry/material/transform/bounds under current host settings. Follow nextOffset; paths adds complete subtrees.",
- "type": "object",
- "properties": {
- "programRef": {
- "type": "string",
- "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])"
- },
- "offset": {
- "type": "integer",
- "minimum": 0,
- "maximum": 9007199254740991
- },
- "limit": {
- "type": "integer",
- "minimum": 1,
- "maximum": 100
- },
- "paths": {
- "description": "Exact baseline node paths, scene-prefixed without primitive children. Complete subtree summaries.",
- "minItems": 1,
- "maxItems": 12,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 4096
- }
- }
- },
- "required": [
- "programRef"
- ],
- "additionalProperties": false
- },
- "measure": {
- "description": "Default anchors: origin/local-point distance. Surface: disjoint mesh triangles, omit points. Rest pose, asset units. Check status/bounds; no solid clearance/attachment proof.",
- "type": "object",
- "properties": {
- "mode": {
- "type": "string",
- "enum": [
- "anchors",
- "surface"
- ]
- },
- "from": {
- "type": "object",
- "properties": {
- "subject": {
- "type": "object",
- "properties": {
- "path": {
- "type": "string"
- },
- "name": {
- "type": "string"
- }
- },
- "additionalProperties": false
- },
- "point": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- }
- },
- "required": [
- "subject"
- ],
- "additionalProperties": false
- },
- "to": {
- "type": "object",
- "properties": {
- "subject": {
- "type": "object",
- "properties": {
- "path": {
- "type": "string"
- },
- "name": {
- "type": "string"
- }
- },
- "additionalProperties": false
- },
- "point": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- }
- },
- "required": [
- "subject"
- ],
- "additionalProperties": false
- }
- },
- "required": [
- "from",
- "to"
- ],
- "additionalProperties": false
- },
- "shot": {
- "description": "One exact camera shot. Shape: kiln_discover ids [\"shape:camera-shot\"].",
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- },
- "code": {
- "description": "New source.",
- "type": "string"
- },
- "part": {
- "description": "Frame named part and descendants (case-insensitive, substring fallback). Omit for whole asset.",
- "type": "string"
- },
- "view": {
- "description": "front/right/back/left/top/three-quarter (default). Orbit angles override.",
- "type": "string"
- },
- "azimuthDeg": {
- "description": "Orbit degrees: 0 front, 90 right, 180 back, 270 left. Wraps.",
- "type": "number"
- },
- "elevationDeg": {
- "description": "Elevation degrees: 0 eye level, positive above. Clamped -89..89.",
- "type": "number"
- },
- "zoom": {
- "description": "Bounds padding 1..4; default 1.2. Larger = more context.",
- "type": "number"
- },
- "isolate": {
- "description": "Hide surrounding geometry. Requires part; default false.",
- "type": "boolean"
- },
- "programRef": {
- "type": "string",
- "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",
- "description": "Returned p_ handle or full sha256 ref."
- },
- "projectId": {
- "description": "Project; omit for the configured default, null for standalone.",
- "anyOf": [
- {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- {
- "type": "null"
- }
- ]
- },
- "projectRevision": {
- "description": "Exact project revision.",
- "type": "string",
- "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"
- },
- "materialDependencies": {
- "description": "Pins for this call; each replaces the project pin of its resourceId.",
- "maxItems": 512,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- },
- "revisionId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "role": {
- "type": "string",
- "maxLength": 100
- }
- },
- "required": [
- "resourceId",
- "revisionId",
- "sha256"
- ],
- "additionalProperties": false
- }
- }
- }
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_edit",
- "description": "Atomically apply ordered exact-string replacements and render. Copy anchors from kiln_source. Supply code OR programRef. Returns programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas), parentRef, diff and preservation comparing static data and animation channels. Review changes; use kiln_inspect compare for more pages or protected subtrees. Failed comparison preserves the repair; render:false leaves preservation not_assessed. capture selects cameras; includeCode adds the patched source, bounded.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "code": {
- "description": "New source.",
- "type": "string"
- },
- "edits": {
- "minItems": 1,
- "maxItems": 20,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "oldString": {
- "type": "string",
- "description": "The exact text to replace, copied verbatim from the program (including whitespace and indentation, and with no line-number prefixes). Must be unique unless replaceAll is true."
- },
- "newString": {
- "type": "string",
- "description": "The replacement text. Use an empty string to delete."
- },
- "replaceAll": {
- "description": "Replace every occurrence instead of failing when oldString matches more than once.",
- "type": "boolean"
- }
- },
- "required": [
- "oldString",
- "newString"
- ]
- },
- "description": "Edits applied in order against the program. If any one fails to match, none are applied and the reply says which. Batch related changes into a single call."
- },
- "render": {
- "description": "Render the patched program and return the views (default true). false = patch only.",
- "type": "boolean"
- },
- "capture": {
- "description": "Cameras, as kiln_render capture takes them. Shape: kiln_discover ids [\"shape:capture\"].",
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- },
- "detail": {
- "description": "compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path",
- "type": "string",
- "enum": [
- "lean",
- "compact",
- "full"
- ]
- },
- "programRef": {
- "type": "string",
- "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",
- "description": "Returned p_ handle or full sha256 ref."
- },
- "includeCode": {
- "description": "Also return the patched source, bounded with the result; kiln_source pages it. Default false.",
- "type": "boolean"
- },
- "projectId": {
- "description": "Project; omit for the configured default, null for standalone.",
- "anyOf": [
- {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- {
- "type": "null"
- }
- ]
- },
- "projectRevision": {
- "description": "Exact project revision.",
- "type": "string",
- "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"
- },
- "materialDependencies": {
- "description": "Pins for this call; each replaces the project pin of its resourceId.",
- "maxItems": 512,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- },
- "revisionId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "role": {
- "type": "string",
- "maxLength": 100
- }
- },
- "required": [
- "resourceId",
- "revisionId",
- "sha256"
- ],
- "additionalProperties": false
- }
- }
- },
- "required": [
- "edits"
- ]
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_source",
- "description": "Read a saved program revision without changing it. Returns exact source text in bounded pages, or searches for literal text with surrounding context. Copy edit anchors from code. Follow nextOffset for more; use matchOffset + 1 to find the next match. Offsets count UTF-16 characters, not bytes.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "programRef": {
- "type": "string",
- "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",
- "description": "Returned p_ handle or full sha256 ref."
- },
- "offset": {
- "default": 0,
- "description": "UTF-16 character offset; use nextOffset to continue.",
- "type": "integer",
- "minimum": 0,
- "maximum": 9007199254740991
- },
- "limit": {
- "default": 8000,
- "description": "Maximum characters returned.",
- "type": "integer",
- "minimum": 1,
- "maximum": 16000
- },
- "query": {
- "description": "Find literal text at or after offset; return bounded surrounding source.",
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- }
- },
- "required": [
- "programRef"
- ]
- },
- "annotations": {
- "readOnlyHint": true,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_material",
- "description": "Manage optional immutable material resources in this workspace. presets discovers shipped architecture, wood, metal, fabric and ground recipes; create-preset bakes one with an explicit seed, creator and license; list returns compact material/revision summaries; get returns full provenance, hashes, map conventions, physical repeat scale and a code-ready portable material spec; create-procedural bakes bounded editable layer recipes including optional height-derived normals; import accepts complete normalized records with embedded PNG bytes. No action downloads URLs or executes source. Pin the returned materialId/revisionId through per-invocation materialDependencies or project dependencies before authored evaluation resolves the resources; no project is required.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "action": {
- "type": "string",
- "enum": [
- "presets",
- "create-preset",
- "list",
- "get",
- "create-procedural",
- "import"
- ]
- },
- "tag": {
- "description": "presets, list: keep one tag.",
- "type": "string",
- "minLength": 1,
- "maxLength": 80
- },
- "presetId": {
- "description": "create-preset: an id from presets.",
- "type": "string",
- "minLength": 1,
- "maxLength": 80
- },
- "seed": {
- "description": "create-preset.",
- "type": "integer",
- "minimum": -2147483648,
- "maximum": 2147483647
- },
- "size": {
- "description": "create-preset: map edge in pixels; default 256.",
- "anyOf": [
- {
- "type": "number",
- "const": 64
- },
- {
- "type": "number",
- "const": 128
- },
- {
- "type": "number",
- "const": 256
- },
- {
- "type": "number",
- "const": 512
- }
- ]
- },
- "creator": {
- "description": "create-preset.",
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "license": {
- "description": "create-preset: spdx, url and attribution.",
- "type": "object",
- "properties": {
- "spdx": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "url": {
- "type": "string",
- "maxLength": 2000,
- "format": "uri"
- },
- "attribution": {
- "type": "string",
- "maxLength": 4000
- }
- },
- "required": [
- "spdx",
- "url",
- "attribution"
- ],
- "additionalProperties": false
- },
- "materialId": {
- "description": "get: the id a project palette lists as resourceId; create-preset: optional id.",
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "revisionId": {
- "description": "get: the immutable revision; omitted, the material's only revision.",
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "draft": {
- "description": "create-procedural: materialId, name, tileable, sources, maps with layered procedural specs; optional tags, physicalSizeMeters, parameters. Shape: kiln_discover({ ids: ['shape:material-draft'] }).",
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- },
- "payload": {
- "description": "import: schemaVersion 1 and complete normalized records with embedded PNG bytes. Shape: kiln_discover({ ids: ['shape:material-import'] }).",
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "action"
- ],
- "additionalProperties": false
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_save",
- "description": "Save a completed source revision into the user-requested collection, or project when none was requested. Persists exact GLB, source, preview and build record. Use programRef returned by render/edit. To revise an asset, pass assetId and parentRevision; earlier revisions stay intact. Returns downloadable resources; draft renders never populate collections.",
- "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."
- },
- "programRef": {
- "type": "string"
- },
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "assetId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "parentRevision": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "tags": {
- "maxItems": 30,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 80
- }
- },
- "brief": {
- "type": "string",
- "maxLength": 8000
- },
- "description": {
- "type": "string",
- "maxLength": 4000
- },
- "attribution": {
- "type": "object",
- "properties": {
- "model": {
- "type": "string",
- "maxLength": 200
- },
- "harness": {
- "type": "string",
- "maxLength": 200
- },
- "author": {
- "type": "string",
- "maxLength": 200
- }
- }
- },
- "backdrop": {
- "description": "Preview backdrop: the one the reviewed sheet used.",
- "type": "string",
- "enum": [
- "neutral",
- "dark",
- "light"
- ]
- },
- "projectId": {
- "description": "Project; omit for the configured default, null for standalone.",
- "anyOf": [
- {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- {
- "type": "null"
- }
- ]
- },
- "projectRevision": {
- "description": "Exact project revision.",
- "type": "string",
- "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"
- },
- "materialDependencies": {
- "description": "Pins for this call; each replaces the project pin of its resourceId.",
- "maxItems": 512,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- },
- "revisionId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "role": {
- "type": "string",
- "maxLength": 100
- }
- },
- "required": [
- "resourceId",
- "revisionId",
- "sha256"
- ],
- "additionalProperties": false
- }
- }
- },
- "required": [
- "programRef",
- "name"
- ]
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_assets",
- "description": "Browse saved assets: collections discovers storage; catalog searches all configured collections; list searches one. Both searches paginate. get returns a build record/downloads; restore loads exact source for kiln_source/kiln_edit. Collection is not project membership. Binary-only assets cannot restore source.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "action": {
- "default": "list",
- "type": "string",
- "enum": [
- "collections",
- "catalog",
- "list",
- "get",
- "restore"
- ]
- },
- "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": {
- "description": "get, restore: the saved revision; omitted, the newest.",
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "query": {
- "type": "string",
- "maxLength": 200
- },
- "offset": {
- "default": 0,
- "type": "integer",
- "minimum": 0,
- "maximum": 9007199254740991
- },
- "limit": {
- "default": 20,
- "type": "integer",
- "minimum": 1,
- "maximum": 50
- }
- }
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- },
- {
- "name": "kiln_present",
- "description": "Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Every host receives exact artifact descriptors with resource URIs in the JSON result; verified hosts may also receive core MCP resource-link blocks. This tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.",
- "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}$"
- }
- },
- "required": [
- "assetId",
- "revisionId"
- ]
- },
- "annotations": {
- "readOnlyHint": true,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- },
- "_meta": {
- "ui": {
- "resourceUri": "ui://kiln/asset-v5.html",
- "visibility": [
- "model"
- ]
- },
- "openai/outputTemplate": "ui://kiln/asset-v5.html",
- "ui/resourceUri": "ui://kiln/asset-v5.html"
- },
- "outputSchema": {
- "type": "object",
- "properties": {
- "ok": {
- "type": "boolean",
- "const": true
- },
- "collection": {
- "type": "string"
- },
- "asset": {
- "type": "object",
- "properties": {
- "assetId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "revisionId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "parentRevision": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "tags": {
- "maxItems": 30,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 80
- }
- },
- "createdAt": {
- "type": "string",
- "format": "date-time",
- "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
- },
- "editable": {
- "type": "boolean"
- },
- "files": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {
- "type": "object",
- "properties": {
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "bytes": {
- "type": "integer",
- "minimum": 0,
- "maximum": 67108864
- }
- },
- "required": [
- "sha256",
- "bytes"
- ],
- "additionalProperties": false
- }
- },
- "build": {
- "type": "object",
- "properties": {
- "engine": {
- "type": "string"
- },
- "rebuild": {
- "type": "string",
- "enum": [
- "engine-required",
- "external-dependencies-required"
- ]
- },
- "warningCount": {
- "type": "integer",
- "minimum": -9007199254740991,
- "maximum": 9007199254740991
- },
- "warnings": {
- "type": "array",
- "items": {
- "type": "string"
- }
- }
- },
- "required": [
- "engine",
- "rebuild",
- "warningCount",
- "warnings"
- ],
- "additionalProperties": false
- }
- },
- "required": [
- "assetId",
- "revisionId",
- "name",
- "tags",
- "createdAt",
- "editable",
- "files"
- ],
- "additionalProperties": false
- },
- "resources": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "resource_link"
- },
- "name": {
- "type": "string"
- },
- "uri": {
- "type": "string"
- },
- "mimeType": {
- "type": "string"
- },
- "size": {
- "type": "integer",
- "minimum": 0,
- "maximum": 9007199254740991
- },
- "annotations": {
- "type": "object",
- "properties": {
- "audience": {
- "type": "array",
- "items": {
- "type": "string",
- "enum": [
- "user",
- "assistant"
- ]
- }
- },
- "priority": {
- "type": "number"
- }
- },
- "required": [
- "audience",
- "priority"
- ],
- "additionalProperties": false
- }
- },
- "required": [
- "type",
- "name",
- "uri",
- "mimeType",
- "size",
- "annotations"
- ],
- "additionalProperties": false
- }
- },
- "downloadUrls": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {
- "type": "string"
- }
- }
- },
- "required": [
- "ok",
- "collection",
- "asset",
- "resources"
- ],
- "additionalProperties": false
- }
- },
- {
- "name": "kiln_export",
- "description": "Export one saved revision. Default editable returns exact GLB, source, preview, and manifest descriptors; configured hosts may include portable editable ZIP download URLs. Opt-in runtime returns a standalone GLB plus a versioned metadata sidecar, moving only Kiln review clips out of GLB extras while preserving native animation and application metadata. Resource URIs remain readable through resources/read. Canonical revisions never change; no binary bytes are placed in tool text.",
- "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}$"
- },
- "profile": {
- "default": "editable",
- "description": "editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.",
- "type": "string",
- "enum": [
- "editable",
- "runtime"
- ]
- }
- },
- "required": [
- "assetId",
- "revisionId"
- ]
- },
- "annotations": {
- "readOnlyHint": true,
- "destructiveHint": false,
- "idempotentHint": true,
- "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.",
- "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}$"
- },
- "sourceCollection": {
- "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."
- }
- },
- "required": [
- "assetId",
- "revisionId"
- ]
- },
- "annotations": {
- "readOnlyHint": false,
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": false
- }
- }
- ],
- "resources": [
- {
- "uri": "ui://kiln/asset-v5.html",
- "name": "kiln-asset-viewer",
- "mimeType": "text/html;profile=mcp-app",
- "description": "Interactive Kiln asset viewer and downloads",
- "_meta": {
- "ui": {
- "prefersBorder": true,
- "csp": {
- "connectDomains": [],
- "resourceDomains": []
- }
- },
- "openai/widgetDescription": "Inspect the saved 3D asset and download its GLB or editable bundle.",
- "openai/widgetPrefersBorder": true
- }
- }
- ],
- "resourceTemplates": [
- {
- "name": "asset-file",
- "uriTemplate": "kiln://assets/{collection}/{asset}/{revision}/{file}",
- "description": "Saved GLB/source/preview/manifest/bundle, or derived runtime GLB and metadata sidecar."
- }
- ],
- "catalog": [
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:projectUV",
- "name": "projectUV",
- "summary": "Generates UV0 explicitly in a rigid geometry-local frame. Planar maps XY; box maps each face; cylindrical wraps frame Y with separate caps and split angular seams. Replaces existing UVs and removes stale tangents. To preserve good UVs use direct sharing or copyGeometry instead.",
- "family": "uv",
- "tags": [
- "uv",
- "texture coordinates"
- ],
- "aliases": [
- "planar projection",
- "box mapping",
- "cylindrical UVs",
- "rotated UV frame"
- ],
- "intents": [
- "generate directional texture coordinates in an explicit frame"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "alternative"
- },
- {
- "id": "operation:remapUV",
- "relation": "companion"
- },
- {
- "id": "operation:autoUnwrap",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/uv-project.ts"
- ],
- "limitations": [
- "Full-wrap seam corners may use U above 1 and require repeat sampling. Side triangles spanning more than half a revolution fail; subdivide the profile. Zero extent maps to 0.5. This is projection, not an atlas or a stretch-free guarantee."
- ],
- "kind": "operation",
- "contract": {
- "signature": "projectUV(geometry: BufferGeometry, opts: { projection: 'planar'|'box'|'cylindrical', frame?: { origin?: [x,y,z], rotation?: [xDeg,yDeg,zDeg] }, seamDegrees?: number, angularRange?: [startDeg,sweepDeg], caps?: 'planar'|'side' })",
- "returns": "THREE.BufferGeometry (owned, non-indexed triangle corners)",
- "units": "UVs are dimensionless; source positions retain authored units.",
- "axes": "Rigid frame in geometry-local coordinates: planar XY, box face planes, cylindrical around Y. Euler XYZ rotations are degrees.",
- "origin": "Frame origin is explicit, default [0,0,0]; geometry positions are preserved.",
- "execution": "sync",
- "ownership": "Owned non-indexed geometry and copied attributes/metadata; input unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Planar/box axes and cylindrical height normalize each geometry extent to 0..1. This is not metre-scaled UV mapping; a shared frame does not preserve texel density or texture continuity across separate pieces. Preserve authored physical UVs or map each face with explicit dimensions when that is required.",
- "projection is required. frame uses origin/rotation. Cylinder seamDegrees defaults to 180, measured from +X toward +Z; angularRange is [start degrees, positive sweep <=360] instead of seamDegrees.",
- "Cylindrical caps default to planar for triangle normals within 1e-6 of frame Y; caps:side uses side mapping. Partial ranges must cover side vertices, allowing 1e-6 radians of Float32 boundary roundoff.",
- "Nonempty finite positions, valid triangle indices and matching per-vertex attributes; morph targets are unsupported. At most 2000000 source samples/corners and 128 MiB expanded attribute storage."
- ],
- "topology": [
- "UV generation does not certify or repair solid topology."
- ],
- "preservation": [
- "Triangle order, positions, normals, matching attributes, material groups and draw range retained. UV0 replaced; tangents removed with a diagnostic. No geometric repair."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in source vertices and triangle corners; indexed meshes expand to one vertex per triangle corner.",
- "example": "const mapped = projectUV(rawGeometry, { projection: 'cylindrical', frame: { rotation: [0,0,-90] }, seamDegrees: 180 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:describeAssembly",
- "name": "describeAssembly",
- "summary": "Describes an existing subtree through common roles, frames, sockets, material slots and root-local bounds. Lookup lists are snapshots with live scene/resource references; bounds are null for geometry-free scaffolds. No asset category is needed.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly",
- "inspection",
- "semantics",
- "bounds",
- "joints"
- ],
- "aliases": [
- "subtree inventory",
- "assembly dimensions",
- "part sockets",
- "semantic joints",
- "wheel pivots"
- ],
- "intents": [
- "inspect an existing multipart object",
- "find roles frames and materials in a part",
- "find joint chain wheel and steering pivots without relying on names"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:replicateAssembly",
- "relation": "companion"
- }
- ],
- "references": [
- "src/assembly.ts"
- ],
- "limitations": [
- "Not a complete rig or solid-validity certificate. Skinning, morphs, instancing and custom node classes are unsupported."
- ],
- "kind": "operation",
- "contract": {
- "signature": "describeAssembly(root: Object3D, opts?: { clips?: readonly AnimationClip[] })",
- "returns": "AssemblyView { version, root, nodes, roles: Map, frames, sockets, materials, bounds, clips, ownership }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Preserves the authored XYZ axes; frames are affine matrices and can include inherited scale/shear.",
- "origin": "The supplied subtree root defines the assembly origin.",
- "execution": "sync",
- "ownership": "Returns snapshot lookup lists, metadata and bounds with borrowed live references to scene nodes/resources and clips. It is not a frozen scene.",
- "coordinates": "Bounds and frame matrices use root-local coordinates, excluding the root transform and ancestors.",
- "parameters": [
- "At most 10,000 nodes and 2,000,000 placed position samples. Bounds scan all position samples, including unused vertices.",
- "Finite invertible local TRS is required. Local shear, zero scale and matrixWorldAutoUpdate=false are unsupported.",
- "Optional clips are combined with clips attached inside the subtree; duplicate names and unsupported tracks fail."
- ],
- "topology": [
- "Supports ordinary Object3D, Group and Mesh subtrees; does not certify manifoldness or whole-asset validity."
- ],
- "preservation": [
- "Scaffold bounds are null. Bounds do not include morph, skin, shader or displacement deformation."
- ],
- "semantics": [
- "Classification roles, semantic frames/sockets, material slots and rigid articulation are inspected without assigning an asset category.",
- "Snapshot node IDs n0,n1,... are not persistent across hierarchy edits. Re-describe after edits.",
- "joints lists semantic articulated, wheel-spin and steering nodes with node IDs, kinds, roles and detached articulated descriptors where present. Names need not start Joint_; duplicate names remain distinct. Match nodeId to frames for wheel axes. This does not infer arbitrary custom joint roles or prove animation target uniqueness."
- ],
- "cost": "Linear in nodes, placed position samples, metadata and animation samples; geometry sharing still incurs bounds work at each placement.",
- "example": "const assembly = describeAssembly(bay); const dimensions = assembly.bounds?.size;"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:replicateAssembly",
- "name": "replicateAssembly",
- "summary": "Replicates a complete supported hierarchy with namespaced semantic and animation references. Owns new nodes/clips; shares geometry/materials unless copy is requested. Revalidates the live source before attaching. Default local placement preserves authored transforms; returns the new subtree as result.root.",
- "family": "instancing",
- "tags": [
- "instancing",
- "assembly",
- "copy",
- "ownership",
- "animation",
- "semantics"
- ],
- "aliases": [
- "clone full hierarchy",
- "repeat multipart object"
- ],
- "intents": [
- "repeat a bay with all child parts",
- "copy a wheel or articulated structure without identity collisions",
- "duplicate animated mechanism",
- "copy articulated hierarchy",
- "independent mutable geometry option"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:describeAssembly",
- "relation": "prerequisite"
- },
- {
- "id": "operation:createInstance",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/assembly.ts"
- ],
- "limitations": [
- "World placement of animated/joint roots needs unsupported track/rest rebasing; use a static wrapper or local placement.",
- "Skinning, morphs, GPU instancing, custom node types and additive clips are unsupported. External preservation is not self-contained acceptance."
- ],
- "kind": "operation",
- "contract": {
- "signature": "replicateAssembly(source: AssemblyView, opts: { namespace: string, parent?: Object3D, space?: 'local' | 'world', geometry?: 'share' | 'copy', materials?: 'share' | 'copy', externalReferences?: 'reject' | 'preserve', unknownMetadata?: 'reject' | 'copy-json' })",
- "returns": "AssemblyReplica extends AssemblyView { nodeMap, nameMap, jointRoleMap, clipMap, externalReferences }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Preserves the authored XYZ axes; frames are affine matrices and can include inherited scale/shear.",
- "origin": "The supplied subtree root defines the assembly origin.",
- "execution": "sync",
- "ownership": "Owns a new hierarchy and copied clips. Geometry/materials default to share; copy clones each unique resource once, retaining sharing inside the replica. Material copying keeps textures shared.",
- "coordinates": "Default space=local preserves root/child local TRS under the chosen parent. space=world reparents the source world matrix only when the new root-local matrix is lossless TRS.",
- "parameters": [
- "At most 10,000 nodes and 2,000,000 placed position samples. Bounds scan all position samples, including unused vertices.",
- "Finite invertible local TRS is required. Local shear, zero scale and matrixWorldAutoUpdate=false are unsupported.",
- "namespace is required: 1–64 characters, lowercase letter first, lowercase letters/digits with single internal underscores or hyphens. Use unique namespaces for detached replicas later composed together.",
- "Defaults: space=local, geometry=share, materials=share, externalReferences=reject, unknownMetadata=reject. Unknown options fail.",
- "externalReferences=preserve keeps and lists external target strings; caller owns their bindings. unknownMetadata=copy-json copies inert finite JSON without guessing reference identity."
- ],
- "topology": [
- "Supports ordinary Object3D, Group and Mesh subtrees; does not certify manifoldness or whole-asset validity."
- ],
- "preservation": [
- "Revalidates current source after edits; attaches the result.root only after successful preflight and construction.",
- "Remaps internal names/UUID references, sockets, joint roles/aliases/parents and rigid rig graphs. Repeated classification roles are preserved; ambiguous targets fail.",
- "Preserves stored clip times/values/duration and LINEAR/STEP interpolation. Returns nodeMap, nameMap, jointRoleMap and clipMap.",
- "Copying custom resource classes/clone hooks/material callbacks fails rather than silently losing behavior. Opaque JSON metadata is not reference-remapped or guaranteed portable to GLB."
- ],
- "semantics": [
- "Classification roles, semantic frames/sockets, material slots and rigid articulation are inspected without assigning an asset category.",
- "New names are namespace-qualified. This is hierarchy replication, not GPU instancing or attachment solving."
- ],
- "cost": "Linear in nodes, placed position samples, metadata and animation samples; geometry sharing still incurs bounds work at each placement. Resource copying adds allocation proportional to unique copied buffers/materials.",
- "example": "const repeated = replicateAssembly(describeAssembly(bay), { namespace: 'bay2', parent: root }); repeated.root.position.x = 3;"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:remapUV",
- "name": "remapUV",
- "summary": "Scales and offsets existing UV0 on an independent geometry. Defaults are scale [1,1], offset [0,0]. Requires finite two-component UVs; does not unwrap or project. Reads interleaved and normalized attributes. Preserves topology and other attributes; nonidentity scaling removes stale tangents with a warning.",
- "family": "uv",
- "tags": [
- "uv",
- "texture",
- "ownership"
- ],
- "aliases": [
- "UV scale and offset",
- "texture atlas region"
- ],
- "intents": [
- "sample a region of a shared texture",
- "mirror or resize texture coordinates",
- "rescale texture repetition",
- "existing UV tiling scale offset",
- "texture coordinates without reshaping geometry"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:projectUV",
- "relation": "prerequisite"
- },
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- }
- ],
- "references": [
- "src/uv-shapes.ts"
- ],
- "limitations": [
- "Requires existing UVs; does not project new coordinates or change texture wrap mode."
- ],
- "kind": "operation",
- "contract": {
- "signature": "remapUV(geometry: BufferGeometry, opts?: { scale?: [u, v], offset?: [u, v] })",
- "returns": "THREE.BufferGeometry (owned clone, UV0 stored as Float32)",
- "units": "Dimensionless UV multipliers and offsets; authored geometry units are unchanged.",
- "axes": "The two components are U then V.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "scale defaults to [1,1]; offset defaults to [0,0]. Both must be finite pairs. Negative and zero scales are permitted.",
- "Requires existing finite UV0 with two components per position vertex. Mapped values must remain finite Float32 values. Unknown options are rejected."
- ],
- "topology": [
- "Preserves source topology; does not generate UVs, unwrap, or repair geometry."
- ],
- "preservation": [
- "Copies geometry attributes, indices and groups, replacing UV0 with an independent Float32 buffer.",
- "Nonidentity scaling drops stale tangents and records a warning; pure offsets preserve tangents. Regenerate tangents for normal mapping when needed."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation.",
- "No material or texture object is copied."
- ],
- "cost": "Linear in vertex UV count plus the cloned geometry buffers.",
- "example": "const strip = remapUV(cylinderGeo(0.4, 0.4, 1), { scale: [1, 0.3], offset: [0, 0] });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:materialBudgetAdvisory",
- "name": "materialBudgetAdvisory",
- "summary": "Counts distinct material object identities and optionally compares an explicit nonnegative integer budget. Without maxMaterials it reports a count with null budget/exceeded and no warnings. Does not measure draw calls, validate geometry, choose an asset category, or establish asset validity.",
- "family": "utility",
- "tags": [
- "utility",
- "metrics",
- "materials",
- "advisory"
- ],
- "aliases": [
- "material count budget"
- ],
- "intents": [
- "compare material diversity against an explicit budget"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:countMaterials",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Does not measure draw calls or validate an asset. Use kiln_validate and applicable QA for acceptance."
- ],
- "kind": "operation",
- "contract": {
- "signature": "materialBudgetAdvisory(root: Object3D, opts?: { maxMaterials?: number })",
- "returns": "{ materialCount, maxMaterials: number | null, exceeded: boolean | null, warnings: string[] }",
- "units": "Counts distinct material object references.",
- "axes": "Not applicable.",
- "origin": "Not applicable.",
- "execution": "sync",
- "ownership": "Read-only traversal; returns a new advisory object and warning array.",
- "coordinates": "Traverses the subtree without modifying transforms.",
- "parameters": [
- "maxMaterials is an optional nonnegative safe integer; there is no default material budget or category policy."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not change geometry, materials, hierarchy or metadata."
- ],
- "semantics": [
- "Returns materialCount, maxMaterials, exceeded and warnings. Omitted budget yields null maxMaterials/exceeded.",
- "An advisory is not an asset acceptance result and contains no valid or errors fields."
- ],
- "cost": "Linear in subtree meshes and material references.",
- "example": "const advisory = materialBudgetAdvisory(root, { maxMaterials: 8 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:copyGeometry",
- "name": "copyGeometry",
- "summary": "Returns an independent geometry with copied vertex buffers. Use before direct mutation of a cached primitive.",
- "family": "instancing",
- "tags": [
- "instancing",
- "ownership",
- "copy"
- ],
- "aliases": [
- "independent geometry copy"
- ],
- "intents": [
- "edit vertices without changing other parts",
- "independent geometry copy",
- "duplicate mesh vertices",
- "edit without changing original"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "copyGeometry(geometry: BufferGeometry)",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Preserves source axes.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "A BufferGeometry."
- ],
- "topology": [
- "Preserves source topology, including any defects."
- ],
- "preservation": [
- "Copies vertex attributes and index buffers; no whole Object3D hierarchy is copied.",
- "Three.js clone semantics apply to groups, morph attributes and userData; arbitrary application object identity is not promised."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in copied geometry buffers.",
- "example": "const editable = copyGeometry(boxGeo(1, 1, 1)); editable.translate(0, 0.5, 0);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:copyMaterial",
- "name": "copyMaterial",
- "summary": "Copies material properties so edits do not change other parts. Referenced textures remain shared.",
- "family": "instancing",
- "tags": [
- "instancing",
- "material",
- "ownership",
- "copy"
- ],
- "aliases": [
- "independent material copy"
- ],
- "intents": [
- "change one part material without recoloring shared parts",
- "independent material copy",
- "edit material without changing original"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "copyMaterial(material: Material)",
- "returns": "THREE.Material (same subtype)",
- "units": "Material property units are preserved; no geometry units apply.",
- "axes": "Not applicable to a material.",
- "origin": "Not applicable to a material.",
- "execution": "sync",
- "ownership": "Returns an independent material object of the same subtype; referenced textures remain shared.",
- "coordinates": "No geometry transform.",
- "parameters": [
- "A Three.js material."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Copies material properties under Three.js clone semantics; does not copy texture bytes or a containing mesh."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Depends on material properties, not scene triangle count.",
- "example": "const red = copyMaterial(steel); red.color.set(0xaa2222);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:meshGeo",
- "name": "meshGeo",
- "summary": "Builds an owned triangle mesh from flat numeric arrays. Validates finite values, attribute lengths and indices; computes normals if absent. Counterclockwise winding.",
- "family": "geometry",
- "tags": [
- "geometry",
- "custom geometry",
- "triangles",
- "owned geometry"
- ],
- "aliases": [
- "raw mesh",
- "indexed triangles"
- ],
- "intents": [
- "build custom vertices and faces"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- }
- ],
- "references": [
- "src/geometry.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "meshGeo({ positions: number[], indices?: number[], normals?: number[], uvs?: number[], tangents?: number[] })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Caller supplies XYZ; triangle winding is counterclockwise when viewed from the front.",
- "origin": "Exactly the supplied vertex positions.",
- "execution": "sync",
- "ownership": "Copies authored numeric arrays into new geometry buffers.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Finite Float32-compatible positions in XYZ triples; indices in range and complete triangles.",
- "Optional normals, UVs and tangents must match vertex counts."
- ],
- "topology": [
- "Accepts triangle meshes with counterclockwise winding; finite/index checks do not certify a manifold, nondegenerate or self-intersection-free solid."
- ],
- "preservation": [
- "Creates supplied UVs/tangents; supplied normals are normalized, otherwise normals are computed.",
- "Computes bounding box and sphere."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in supplied vertex/triangle arrays; no general allocation cap is claimed.",
- "example": "const triangle = meshGeo({ positions: [0,0,0, 1,0,0, 0,1,0], indices: [0,1,2] });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:parametricSurface",
- "name": "parametricSurface",
- "summary": "At most 262,144 endpoint-inclusive samples per call, checked before invoking the sampler. Samples an equation into an owned surface with UVs. Periodic endpoints must agree within 1e-6 of the sampled diagonal, independent of origin and units; UV seams retain matching normals. A surface is not automatically a watertight solid.",
- "family": "geometry",
- "tags": [
- "geometry",
- "custom geometry",
- "surface",
- "equation"
- ],
- "aliases": [
- "equation surface",
- "parametric mesh"
- ],
- "intents": [
- "sample a mathematical surface"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/geometry.ts"
- ],
- "limitations": [
- "Callback termination and self-intersection are not certified.",
- "Use a non-collapsed parameterization or explicit meshGeo fan topology at singular tips. geometryDiagnostics reports degenerate triangles; supplying arbitrary normals does not repair collapsed topology."
- ],
- "kind": "operation",
- "contract": {
- "signature": "parametricSurface(sample: (u,v) => [x,y,z], opts?: { u?: [0,1], v?: [0,1], uSegments?: 24, vSegments?: 24, periodicU?: false, periodicV?: false, orientation?: 'uv'|'vu' })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Sampler returns XYZ; orientation selects uv or vu winding.",
- "origin": "Defined by sampler outputs, not centered automatically.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Positive safe-integer u/v segment counts; finite nonzero domains and domain extents; at most 262,144 samples including endpoints.",
- "Periodic endpoints must agree within 1e-6 of the sampled bounding-box diagonal, independent of translation or world units; orientation must be uv or vu."
- ],
- "topology": [
- "A sampled surface, not automatically a closed solid; periodic seams retain separate UV vertices.",
- "Each grid cell becomes two triangles. Collapsed parameter rows or columns are not converted into pole fans; they can create degenerate triangles and zero normals."
- ],
- "preservation": [
- "Generates UVs and normals, aligns normals across validated periodic seams, computes bounds."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "(uSegments + 1) × (vSegments + 1) samples, capped at 262,144 before callbacks/allocation; 2 × uSegments × vSegments triangles. The evaluator still owns callback timeouts.",
- "example": "const canopy = parametricSurface((u,v) => [u, 0.3*Math.sin(u*3)*Math.cos(v*2), v], { u: [-2,2], v: [-1,1] });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:geometryDiagnostics",
- "name": "geometryDiagnostics",
- "summary": "Counts topology issues after position-grid matching. Default tolerance is 1e-6 times the finite-position diagonal; an explicit positive value is absolute. Reports effective tolerance and scale. Open boundaries are valid for sheets; closed edges do not certify a self-intersection-free solid.",
- "family": "utility",
- "tags": [
- "utility",
- "diagnostics",
- "topology"
- ],
- "aliases": [
- "mesh diagnostics",
- "watertightness inspection"
- ],
- "intents": [
- "inspect open edges and malformed mesh data",
- "boundary nonmanifold edges",
- "welded seam topology",
- "degenerate triangle orientation"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/geometry.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "geometryDiagnostics(geometry: BufferGeometry, tolerance?: number)",
- "returns": "{ tolerance, toleranceMode, positionScale, vertices, triangles, boundaryEdges, nonManifoldEdges, orientationConflicts, degenerateTriangles, invalidIndices, nonFiniteVertices }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. tolerance uses position units.",
- "axes": "Reads source XYZ without changing it.",
- "origin": "Does not reposition geometry.",
- "execution": "sync",
- "ownership": "Read-only inspection; returns counts, not repaired geometry.",
- "coordinates": "Geometry-local positions; position-based seam matching uses tolerance.",
- "parameters": [
- "A BufferGeometry; omitted tolerance is 1e-6 times its finite-position bounding-box diagonal. A supplied positive finite tolerance is an absolute distance and must resolve the extent within safe integer quantization.",
- "Returns effective tolerance, toleranceMode (relative or absolute) and positionScale with the counts; a collapsed extent uses zero default tolerance."
- ],
- "topology": [
- "Counts boundary/nonmanifold/orientation/degenerate/index/finite issues; does not detect arbitrary triangle self-intersections.",
- "An open sheet can be valid for its intended use.",
- "Position matching quantizes a grid relative to the bounds minimum, not an exact distance weld. Invalid-position triangles are excluded from edge/area counts and nonfinite vertices remain reported.",
- "collapsedByToleranceTriangles counts faces whose corners merge in that grid; they are excluded from edge counts, not removed from geometry. Nonzero means topology detail was lost at this tolerance; inspect at a finer tolerance before interpreting edge counts. This is separate from area-based degenerateTriangles."
- ],
- "preservation": [
- "Input buffers and topology are unchanged."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Visits vertices and triangle edges; memory grows with unique welded positions/edges.",
- "example": "const topology = geometryDiagnostics(shell);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:creaseNormals",
- "name": "creaseNormals",
- "summary": "Returns owned geometry with angle-limited smooth normals, preserving UV corners. Angle is degrees. Default position tolerance is 1e-8 times the diagonal, with no world-unit floor; explicit tolerance is absolute. Invalidates tangents; use after shaping for sharp rims and smooth walls.",
- "family": "mesh-ops",
- "tags": [
- "mesh-ops",
- "shading",
- "normals"
- ],
- "aliases": [
- "hard edges",
- "smooth normals"
- ],
- "intents": [
- "keep sharp rims while smoothing curved faces",
- "smooth normals",
- "preserve sharp edges",
- "hard surface shading"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/geometry.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "creaseNormals(geometry: BufferGeometry, opts?: { angle?: 60, tolerance?: number })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. angle is degrees; tolerance is a distance.",
- "axes": "Preserves source coordinate axes.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Finite crease angle; default 60 degrees. Omitted tolerance is 1e-8 times the finite-position bounding-box diagonal, without a world-unit floor; an explicit positive finite distance overrides it."
- ],
- "topology": [
- "Can split corners for shading; no topology repair or solid-validity guarantee."
- ],
- "preservation": [
- "Preserves UV corner seams; recomputes angle-limited normals and bounds; invalidates tangents."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Depends on faces and vertex adjacency; highly connected neighborhoods can increase work.",
- "example": "const shell = creaseNormals(cylinderGeo(1,1,2,32), { angle: 45 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:bend",
- "name": "bend",
- "summary": "Bends local +Y toward +X through angle degrees. Returns owned geometry and updated normals/bounds; preserves UVs, invalidates tangents. Frame rotation is Euler XYZ degrees.",
- "family": "mesh-ops",
- "tags": [
- "mesh-ops",
- "deformation",
- "owned geometry"
- ],
- "aliases": [
- "curve a mesh"
- ],
- "intents": [
- "bend an existing segmented shape"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:subdivide",
- "relation": "companion"
- },
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- }
- ],
- "references": [
- "src/deform.ts"
- ],
- "limitations": [
- "Enough longitudinal segments must exist before deforming; discontinuous interval boundaries remain possible."
- ],
- "kind": "operation",
- "contract": {
- "signature": "bend(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. frame rotations and angle parameters use Euler XYZ degrees; scale and falloff are dimensionless.",
- "axes": "Bends frame-local +Y toward +X; local Z is the bend axis.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Frame origin/rotation finite; interval finite and increasing; falloff returns a finite weight in [0,1].",
- "Outside positions stay unchanged with endpoint roundoff bounded to one millionth of interval length; nonzero intervals retain normalized progress at tiny scales.",
- "At most 2000000 vertices / 3000000 triangle corners; morph targets require deformation before morph creation.",
- "Deformation interval uses local Y distances; outside vertices stay unchanged. Add enough segments before bending. Falloff returns 0..1; use it to avoid a discontinuity at a selected interval boundary."
- ],
- "topology": [
- "Keeps connectivity but can create degenerate or self-intersecting shapes; no automatic subdivision."
- ],
- "preservation": [
- "Preserves UVs, groups and cloned attributes. Unchanged positions keep authored normals; changed geometry rebuilds area-weighted normals across authored smooth seam classes while retaining hard creases.",
- "Seam matching uses 1e-7 of geometry diagonal for position and 1e-6 normal components; tangents are removed with DEFORM_TANGENTS_DROPPED. No topology-validity guarantee."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in vertex count plus normal recomputation and callback cost; callback termination is a host responsibility.",
- "example": "const arch = bend(planeGeo(1,4,4,32), { angle: 90 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:twist",
- "name": "twist",
- "summary": "Rotates the cross-section progressively around local +Y, reaching angle degrees at the end. Returns owned geometry; frame rotation uses Euler XYZ degrees.",
- "family": "mesh-ops",
- "tags": [
- "mesh-ops",
- "deformation",
- "owned geometry"
- ],
- "aliases": [
- "torsion"
- ],
- "intents": [
- "twist a column or handle"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:subdivide",
- "relation": "companion"
- },
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- }
- ],
- "references": [
- "src/deform.ts"
- ],
- "limitations": [
- "Enough longitudinal segments must exist before deforming; discontinuous interval boundaries remain possible."
- ],
- "kind": "operation",
- "contract": {
- "signature": "twist(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. frame rotations and angle parameters use Euler XYZ degrees; scale and falloff are dimensionless.",
- "axes": "Rotates cross-sections around frame-local +Y along the interval.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Frame origin/rotation finite; interval finite and increasing; falloff returns a finite weight in [0,1].",
- "Outside positions stay unchanged with endpoint roundoff bounded to one millionth of interval length; nonzero intervals retain normalized progress at tiny scales.",
- "At most 2000000 vertices / 3000000 triangle corners; morph targets require deformation before morph creation."
- ],
- "topology": [
- "Keeps connectivity but can create degenerate or self-intersecting shapes; no automatic subdivision."
- ],
- "preservation": [
- "Preserves UVs, groups and cloned attributes. Unchanged positions keep authored normals; changed geometry rebuilds area-weighted normals across authored smooth seam classes while retaining hard creases.",
- "Seam matching uses 1e-7 of geometry diagonal for position and 1e-6 normal components; tangents are removed with DEFORM_TANGENTS_DROPPED. No topology-validity guarantee."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in vertex count plus normal recomputation and callback cost; callback termination is a host responsibility.",
- "example": "const spiral = twist(column, { angle: 120 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:taper",
- "name": "taper",
- "summary": "Scales local X/Z across the local Y interval using positive start/end scale pairs. Returns owned geometry; preserves UVs and invalidates tangents.",
- "family": "mesh-ops",
- "tags": [
- "mesh-ops",
- "deformation",
- "owned geometry"
- ],
- "aliases": [
- "narrow a mesh"
- ],
- "intents": [
- "vary the width of a segmented shape"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:subdivide",
- "relation": "companion"
- },
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- }
- ],
- "references": [
- "src/deform.ts"
- ],
- "limitations": [
- "Enough longitudinal segments must exist before deforming; discontinuous interval boundaries remain possible."
- ],
- "kind": "operation",
- "contract": {
- "signature": "taper(geometry, { startScale?: [1,1], endScale: [x,z], frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. frame rotations and angle parameters use Euler XYZ degrees; scale and falloff are dimensionless.",
- "axes": "Scales frame-local X/Z along local Y.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Frame origin/rotation finite; interval finite and increasing; falloff returns a finite weight in [0,1].",
- "Outside positions stay unchanged with endpoint roundoff bounded to one millionth of interval length; nonzero intervals retain normalized progress at tiny scales.",
- "At most 2000000 vertices / 3000000 triangle corners; morph targets require deformation before morph creation.",
- "startScale/endScale contain two finite positive scale factors."
- ],
- "topology": [
- "Keeps connectivity but can create degenerate or self-intersecting shapes; no automatic subdivision."
- ],
- "preservation": [
- "Preserves UVs, groups and cloned attributes. Unchanged positions keep authored normals; changed geometry rebuilds area-weighted normals across authored smooth seam classes while retaining hard creases.",
- "Seam matching uses 1e-7 of geometry diagonal for position and 1e-6 normal components; tangents are removed with DEFORM_TANGENTS_DROPPED. No topology-validity guarantee."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in vertex count plus normal recomputation and callback cost; callback termination is a host responsibility.",
- "example": "const narrowed = taper(column, { endScale: [0.4,0.7] });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:displace",
- "name": "displace",
- "summary": "Adds an authored displacement vector in the chosen local frame. Returns owned geometry; callback coordinates are local and t is normalized along the interval.",
- "family": "mesh-ops",
- "tags": [
- "mesh-ops",
- "deformation",
- "owned geometry"
- ],
- "aliases": [
- "vertex displacement"
- ],
- "intents": [
- "shape a mesh using an authored offset field"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:subdivide",
- "relation": "companion"
- },
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- }
- ],
- "references": [
- "src/deform.ts"
- ],
- "limitations": [
- "Enough longitudinal segments must exist before deforming; discontinuous interval boundaries remain possible."
- ],
- "kind": "operation",
- "contract": {
- "signature": "displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. frame rotations and angle parameters use Euler XYZ degrees; scale and falloff are dimensionless.",
- "axes": "Callback receives frame-local XYZ and normalized interval distance.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Frame origin/rotation finite; interval finite and increasing; falloff returns a finite weight in [0,1].",
- "Outside positions stay unchanged with endpoint roundoff bounded to one millionth of interval length; nonzero intervals retain normalized progress at tiny scales.",
- "At most 2000000 vertices / 3000000 triangle corners; morph targets require deformation before morph creation.",
- "Callback returns a finite XYZ displacement vector, not an absolute position."
- ],
- "topology": [
- "Keeps connectivity but can create degenerate or self-intersecting shapes; no automatic subdivision."
- ],
- "preservation": [
- "Preserves UVs, groups and cloned attributes. Unchanged positions keep authored normals; changed geometry rebuilds area-weighted normals across authored smooth seam classes while retaining hard creases.",
- "Seam matching uses 1e-7 of geometry diagonal for position and 1e-6 normal components; tangents are removed with DEFORM_TANGENTS_DROPPED. No topology-validity guarantee."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in vertex count plus normal recomputation and callback cost; callback termination is a host responsibility.",
- "example": "const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:sweepProfile",
- "name": "sweepProfile",
- "summary": "Sweeps a simple noncircular profile along polyline stations using transported frames. Supports total twist in degrees and per-station scales. Generates UVs and optional caps.",
- "family": "curves",
- "tags": [
- "curves",
- "sweep",
- "profile",
- "path"
- ],
- "aliases": [
- "extrude along path",
- "noncircular tube"
- ],
- "intents": [
- "carry a cross-section along a rail",
- "profile along a path",
- "extruded rail",
- "curved trim"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:loftProfiles",
- "relation": "alternative"
- },
- {
- "id": "operation:pipeAlongPath",
- "relation": "alternative"
- },
- {
- "id": "operation:extrudeProfile",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/sweep.ts"
- ],
- "limitations": [
- "Tight-turn warnings use the scaled profile radius at the turning station and adjacent segment lengths. This local heuristic does not test swept-volume intersections, rapid scale changes, or certify a solid."
- ],
- "kind": "operation",
- "contract": {
- "signature": "sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true | false | 'start' | 'end', creaseAngle?: 60, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. twist/frame rotations are degrees; scale is dimensionless.",
- "axes": "Profile coordinates are local XZ; local +Y is the longitudinal direction.",
- "origin": "Defined by supplied path stations or section frames.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Finite simple profile and distinct path stations: at least 2 open or 3 closed.",
- "Profile and path checks use their respective extents, not fixed world-unit cutoffs; up specifies a direction regardless of its nonzero magnitude. Output positions remain Float32.",
- "Closed paths omit the repeated endpoint and require twist to be a multiple of 360 degrees.",
- "Transported frames and per-station positive scales define the cross-section.",
- "cap is true (both ends, default), false, 'start' or 'end'; a one-ended cap needs an open path.",
- "creaseAngle is degrees in [0, 180], default 60. Side panels meeting at more than it, across a profile corner or a path station, get separate vertices and a hard shading edge; hexagons and finer profiles stay smooth at the default.",
- "First version supports one simple profile without holes. Closed paths omit the repeated endpoint and require twist to be a multiple of 360. up sets the initial profile +Z direction and cannot parallel the path. cap caps both ends by default; 'start' or 'end' caps only that end of an open path. creaseAngle (degrees) keeps side faces meeting at more than it hard-edged, at profile corners and sharp path corners: at the default 60, squares, triangles and pentagons stay faceted while hexagons and finer profiles shade smooth; 180 smooths every edge. Tight-turn warnings do not replace visual inspection for self-intersections."
- ],
- "topology": [
- "Simple profiles without holes; supplied holes fields fail explicitly. Optional caps do not prove freedom from self-intersection or create wall thickness.",
- "Warped side panels use four triangles around a bilinear midpoint to avoid diagonal bias; planar panels use two. This is piecewise-linear sampling, not a smooth surface.",
- "A corresponding edge that collapses between stations is rejected. Check matching starts/order or add intermediate stations for an intended twist. Bounded local analysis observes tight station curvature and intersecting consecutive rings; distant segments remain unchecked."
- ],
- "preservation": [
- "Generates UVs, normals and bounds; SWEEP_SELF_INTERSECTION observes station radius or intersecting consecutive rings. Incomplete analysis keeps an unchecked warning and partial finding."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Geometry grows with profile points × stations; each warped side panel adds one midpoint and two triangles. Local analysis is capped at 4096 stations, 512 points per ring and 65536 segment/triangle tests; no global surface-intersection certification or geometry allocation cap.",
- "example": "const rail = sweepProfile([[-.1,-.2],[.1,-.2],[.1,.2],[-.1,.2]], [[0,0,0],[0,1,0],[1,2,0]]);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:loftProfiles",
- "name": "loftProfiles",
- "summary": "Joins corresponding simple profiles in explicit local XZ planes. Frames use Euler XYZ degrees; initial section travel determines outward winding. Profiles need equal point counts and corresponding vertices.",
- "family": "curves",
- "tags": [
- "curves",
- "loft",
- "profile",
- "frames"
- ],
- "aliases": [
- "join cross-sections"
- ],
- "intents": [
- "transition between different cross-section shapes",
- "loft cross sections",
- "varying cross section",
- "join cross sections",
- "matching polygon outlines",
- "blend section shapes"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:sweepProfile",
- "relation": "alternative"
- },
- {
- "id": "operation:extrudeProfile",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/sweep.ts"
- ],
- "limitations": [
- "Closed boundaries do not certify a self-intersection-free solid."
- ],
- "kind": "operation",
- "contract": {
- "signature": "loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opts?: { cap?: true })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. twist/frame rotations are degrees; scale is dimensionless.",
- "axes": "Profiles lie in rigid local XZ planes. Initial section travel relative to the first plane determines face winding; sections may progress in either direction.",
- "origin": "Defined by supplied path stations or section frames.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "At least two simple profiles with equal point counts and corresponding vertex order.",
- "Profile validation is relative to its extent. Nonzero section travel has no fixed world-unit minimum; output positions remain Float32.",
- "Explicit rigid frames position local XZ profiles; no automatic profile correspondence or holes. Coplanar or crossed section arrangements are not certified solids.",
- "No holes or automatic profile correspondence. Opposite winding is normalized while preserving the first point. Caps close boundaries but do not prove the loft has no self-intersections."
- ],
- "topology": [
- "Simple profiles without holes; supplied holes fields fail explicitly. Optional caps do not prove freedom from self-intersection or create wall thickness.",
- "Warped side panels use four triangles around a bilinear midpoint to avoid diagonal bias; planar panels use two. This is piecewise-linear sampling, not a smooth surface.",
- "A corresponding edge that collapses between stations is rejected. Check matching starts/order or add intermediate stations for an intended twist. Bounded local analysis observes tight station curvature and intersecting consecutive rings; distant segments remain unchecked."
- ],
- "preservation": [
- "Generates UVs, normals and bounds; SWEEP_SELF_INTERSECTION observes station radius or intersecting consecutive rings. Incomplete analysis keeps an unchecked warning and partial finding."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Geometry grows with profile points × stations; each warped side panel adds one midpoint and two triangles. Local analysis is capped at 4096 stations, 512 points per ring and 65536 segment/triangle tests; no global surface-intersection certification or geometry allocation cap.",
- "example": "const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin: [0,2,0] } }]);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:implicitSurface",
- "name": "implicitSurface",
- "summary": "Experimental positive-inside implicit field sampled into a solid mesh. Requires explicit bounds and resolution; checks grid size and actual evaluation count. Output has no UVs.",
- "family": "geometry",
- "tags": [
- "geometry",
- "implicit surface",
- "field",
- "solid"
- ],
- "aliases": [
- "signed field",
- "isosurface"
- ],
- "intents": [
- "sample a blended volumetric shape"
- ],
- "stability": "experimental",
- "related": [],
- "references": [
- "src/implicit.ts"
- ],
- "limitations": [
- "No CAD accuracy or thin-feature preservation guarantee; requires host execution limits."
- ],
- "kind": "operation",
- "contract": {
- "signature": "await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max }, edgeLength, maxCells?: 1000000, maxEvaluations?: 8000000, level?: 0, tolerance?: -1, smooth?: true })",
- "returns": "Promise<THREE.BufferGeometry>",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Field receives XYZ; positive values describe the inside.",
- "origin": "Explicit sampling bounds min/max define the evaluated region.",
- "execution": "async",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Finite increasing bounds on all axes; finite positive edgeLength.",
- "Positive safe-integer maxCells/maxEvaluations; level finite, tolerance -1 or positive.",
- "Defaults: 1,000,000 estimated cells and 8,000,000 actual callback evaluations.",
- "Use async build and await. Smaller edgeLength increases cost sharply. This helper cannot stop a callback that never returns; the host evaluator process provides that boundary. Thin features and geometric accuracy require inspection."
- ],
- "topology": [
- "Manifold level-set extraction is resolution-dependent; thin features and boundary clipping require review."
- ],
- "preservation": [
- "Generates normals and bounds; no UVs; stamps experimental sampling settings and warnings."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Checks estimated grid and actual callback counts before/between samples; cannot interrupt a callback that never returns.",
- "example": "const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:createRoot",
- "name": "createRoot",
- "summary": "Creates the root Object3D for an asset. Call first in build().",
- "family": "structure",
- "tags": [
- "structure",
- "hierarchy",
- "root"
- ],
- "aliases": [
- "asset root"
- ],
- "intents": [
- "start an asset hierarchy"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "createRoot(name: string)",
- "returns": "THREE.Object3D",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Three.js local XYZ; +Y is the normal up convention.",
- "origin": "Identity transform at [0,0,0].",
- "execution": "sync",
- "ownership": "Creates a new root Object3D.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Names identify nodes; parent attachment changes the supplied parent hierarchy."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not clone a containing parent hierarchy."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "One node.",
- "example": "const root = createRoot('FuelDrum');"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:createPivot",
- "name": "createPivot",
- "summary": "Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.",
- "family": "structure",
- "tags": [
- "structure",
- "hierarchy",
- "pivot",
- "animation"
- ],
- "aliases": [
- "hinge",
- "joint pivot"
- ],
- "intents": [
- "rotate a part around an articulated origin"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "createPivot(name: string, position?: [x, y, z], parent?: Object3D)",
- "returns": "THREE.Object3D (prefixed `Joint_`)",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Three.js local XYZ; +Y is the normal up convention.",
- "origin": "Position is relative to the selected parent.",
- "execution": "sync",
- "ownership": "Creates new Object3D nodes; attaches them to the supplied parent when present.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Names identify nodes; parent attachment changes the supplied parent hierarchy."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not clone a containing parent hierarchy."
- ],
- "semantics": [
- "Prefixes the node name with Joint_; that name does not itself prove a skeletal role."
- ],
- "cost": "One pivot node.",
- "example": "const hip = createPivot('Hip', [0, 1, 0], root);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createJointChain",
- "name": "createJointChain",
- "summary": "Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly",
- "rig",
- "skeleton"
- ],
- "aliases": [
- "joint chain",
- "articulated chain"
- ],
- "intents": [
- "create a body-plan-neutral articulated chain"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/character.ts"
- ],
- "limitations": [],
- "kind": "assembly",
- "contract": {
- "signature": "createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })",
- "returns": "{ root, end, nodes, byRole, descriptors }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Per-joint forward/bend axes are explicit descriptors; +Y up is conventional, not a mandatory body plan.",
- "origin": "Each offset is local to the preceding joint, starting under the supplied parent.",
- "execution": "sync",
- "ownership": "Creates new Object3D nodes; attaches them to the supplied parent when present.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Ordered role descriptors with finite offsets and explicit semantic parent relationships.",
- "Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Creates rest frames, local axes, role lookup and parent edges; does not create skinning or a character mesh."
- ],
- "semantics": [
- "Stamps versioned joint/role metadata, contacts and end-effectors when declared."
- ],
- "cost": "Linear in number of joint descriptors.",
- "example": "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createVehicleFrame",
- "name": "createVehicleFrame",
- "summary": "Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly",
- "frame",
- "sockets",
- "vehicle"
- ],
- "aliases": [
- "chassis sockets",
- "vehicle scaffold"
- ],
- "intents": [
- "coordinate support and propulsion attachment locations"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/vehicle.ts"
- ],
- "limitations": [
- "Socket declarations alone do not prove ground support or working propulsion."
- ],
- "kind": "assembly",
- "contract": {
- "signature": "createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })",
- "returns": "{ root, chassis, axles, seats, contacts, steering, propulsion }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "+X forward, +Y up, +Z right.",
- "origin": "Socket positions are local to the new frame root.",
- "execution": "sync",
- "ownership": "Creates new Object3D nodes; attaches them to the supplied parent when present.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Typed chassis/axle/seat/contact/steering/propulsion descriptors; identifiers and coordinates are validated.",
- "Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Creates socket nodes and typed semantic relationships; geometry and wheels are separate."
- ],
- "semantics": [
- "Marks vehicle frame/socket roles; these labels do not activate category-specific policy."
- ],
- "cost": "Linear in declared sockets.",
- "example": "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:createWheelGeometrySet",
- "name": "createWheelGeometrySet",
- "summary": "Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.",
- "family": "instancing",
- "tags": [
- "instancing",
- "geometry",
- "wheel",
- "reuse"
- ],
- "aliases": [
- "shared wheel geometry"
- ],
- "intents": [
- "reuse matching tire and rim buffers"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "assembly:createWheelAssembly",
- "relation": "companion"
- }
- ],
- "references": [
- "src/vehicle.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "createWheelGeometrySet(radius: number, width: number)",
- "returns": "{ tire, rim, hub } shared THREE.BufferGeometry set",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "+Z axle; tire lies around XY.",
- "origin": "Axle center [0,0,0].",
- "execution": "sync",
- "ownership": "Allocates a tire/rim/hub geometry set intended to be shared by multiple assemblies.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Positive radius and width; width must be less than the diameter."
- ],
- "topology": [
- "Torus tire plus capped rim/hub cylinders; not a boolean union."
- ],
- "preservation": [
- "Generates standard geometry normals and UVs."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Fixed segment choices: torus 8 × 20 plus rim/hub cylinders.",
- "example": "const wheelGeo = createWheelGeometrySet(0.45, 0.22);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createWheelAssembly",
- "name": "createWheelAssembly",
- "summary": "Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly",
- "wheel",
- "pivot"
- ],
- "aliases": [
- "articulated wheel"
- ],
- "intents": [
- "build a wheel with steering and spin pivots"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:createWheelGeometrySet",
- "relation": "companion"
- },
- {
- "id": "assembly:createVehicleFrame",
- "relation": "companion"
- }
- ],
- "references": [
- "src/vehicle.ts"
- ],
- "limitations": [],
- "kind": "assembly",
- "contract": {
- "signature": "createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })",
- "returns": "{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis, geometryChecks }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "+Z spin axis, optional +Y steering axis.",
- "origin": "Concentric components at the axle pivot; position moves that pivot under the assembly root.",
- "execution": "sync",
- "ownership": "Creates new wheel hierarchy; supplied geometry set and material references are shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Positive dimensions; hubRadius < rimRadius < radius; rim/hub widths cannot exceed tire width.",
- "side is 'left', 'right' or 'center'; index identifies the axle. These label identity without inferring position, paired wheels or the number of fork arms.",
- "Supplied geometry is checked without mutation: geometryChecks reports radius/width/center differences at relative tolerance 1e-5. At most 2000000 position samples per component; empty/nonfinite geometry fails. A mismatch is advisory, never an automatic resize.",
- "side is 'left', 'right', or 'center': identity relative to the host, not fork design or automatic positioning. Centerline wheels need no partner. Keep tire, rim, and hub concentric at the axle pivot. Reuse geometry across matching wheels."
- ],
- "topology": [
- "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."
- ],
- "preservation": [
- "Preserves component hierarchy and semantic contacts/relationships. Supplied geometry stays shared; contacts retain declared radius. Review geometryChecks when customizing."
- ],
- "semantics": [
- "Typed wheel/tire/rim/hub/pivot/contact roles with load-bearing and steering metadata."
- ],
- "cost": "Three wheel meshes plus pivots/contact markers; sharing geometry is not one draw call.",
- "example": "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:createPart",
- "name": "createPart",
- "summary": "Creates a mesh using supplied geometry and material, with optional pivot and parent attachment. Rotation triples are degrees.",
- "family": "structure",
- "tags": [
- "structure",
- "mesh",
- "hierarchy",
- "placement"
- ],
- "aliases": [
- "place a mesh",
- "make a part"
- ],
- "intents": [
- "turn geometry into a placed part"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Attach once using parent; do not separately add the returned node to another parent."
- ],
- "kind": "operation",
- "contract": {
- "signature": "createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })",
- "returns": "THREE.Object3D (mesh or wrapping pivot)",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Three.js local XYZ; +Y is the normal up convention.",
- "origin": "Position is relative to the selected parent.",
- "execution": "sync",
- "ownership": "Creates a new mesh and optional pivot wrapper; input geometry and material are shared, not copied.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Names identify nodes; parent attachment changes the supplied parent hierarchy.",
- "AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead. rotation is DEGREES — writing radians (e.g. 0.785 or Math.PI/4) silently produces ~zero rotation."
- ],
- "topology": [
- "Uses input geometry unchanged; no repair or solid guarantee."
- ],
- "preservation": [
- "Keeps geometry/material references; does not import another subtree."
- ],
- "semantics": [
- "Names the mesh Mesh_<name>; optional pivot is a distinct parent node.",
- "With pivot:true, position moves the pivot while rotation/scale remain on the child mesh.",
- "Optional semantic input is stamped on the returned mesh or pivot."
- ],
- "cost": "One mesh plus optional pivot; geometry/material buffers are shared.",
- "example": "createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], rotation: [0, 0, 90], parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:defineLod",
- "name": "defineLod",
- "summary": "Declares LOD tiers (sibling nodes named Body_LOD0, Body_LOD1, ...) and their screen-coverage thresholds. Use only when the brief asks for LOD tiers.",
- "family": "structure",
- "tags": [
- "structure",
- "hierarchy",
- "lod",
- "export"
- ],
- "aliases": [
- "level of detail",
- "LOD tiers",
- "MSFT_lod",
- "screen coverage"
- ],
- "intents": [
- "export level-of-detail tiers as one chain"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/lod.ts",
- "src/lod-export.ts"
- ],
- "limitations": [
- "Tiers are authored, not generated: Kiln simplifies no geometry.",
- "Sets cannot nest inside another tier; material LOD chains are not created."
- ],
- "kind": "operation",
- "contract": {
- "signature": "defineLod(levels: Object3D[], opts: { screenCoverage: number[] })",
- "returns": "Object3D[] (levels, unchanged)",
- "units": "screenCoverage values are fractions of the screen area, 0..1; no lengths.",
- "axes": "Three.js local XYZ; +Y is the normal up convention.",
- "origin": "Each lower level keeps its own transform and replaces LOD0 under the same parent.",
- "execution": "sync",
- "ownership": "Records the thresholds on the LOD0 node; creates no nodes and moves nothing until export.",
- "coordinates": "Not a placement operation.",
- "parameters": [
- "levels: two or more sibling tier nodes named with one stem and tokens LOD0, LOD1, ... in order.",
- "screenCoverage: one value per level, each from 0 to 1, strictly decreasing, LOD0 first; the last may be 0, which never culls.",
- "Only when the brief asks for LOD tiers; otherwise build one tier. Tiers are sibling nodes named with one stem and consecutive LOD<n> tokens. screenCoverage has one value per level, strictly decreasing; below the last the asset is culled, and a last value of 0 never culls."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not clone a containing parent hierarchy."
- ],
- "semantics": [
- "Level i draws while the asset covers at least screenCoverage[i] of the screen; below the last value it is culled.",
- "Export writes the set as one MSFT_lod chain: LOD0 stays in the scene and lists the lower levels, which leave it; LOD0 extras.MSFT_screencoverage holds the thresholds.",
- "Reported triangles and bounds count LOD0; levelsOfDetail in render results lists each level with its triangles and path.",
- "A set of two or more tiers without this declaration, with a gap, or without LOD0 is an LOD_SET build error."
- ],
- "cost": "Metadata on one node; lower levels still cost file size.",
- "example": "const tiers = ['Body_LOD0', 'Body_LOD1', 'Body_LOD2'].map((name) => { const g = new THREE.Group(); g.name = name; root.add(g); return g; });\ndefineLod(tiers, { screenCoverage: [0.25, 0.06, 0.01] });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:markOpenShell",
- "name": "markOpenShell",
- "summary": "Marks a part that is open on purpose (a C-channel closed by end plates, a single-sided sheet) with the reason, so QA reports it as acknowledged rather than unmeasured.",
- "family": "structure",
- "tags": [
- "structure",
- "qa",
- "hierarchy",
- "export"
- ],
- "aliases": [
- "open shell",
- "intentionally open",
- "not manifold",
- "single-sided sheet",
- "acknowledge unmeasured part"
- ],
- "intents": [
- "mark a part that is open on purpose"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:createPart",
- "relation": "companion"
- },
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- }
- ],
- "references": [
- "src/open-shell.ts",
- "src/qa/self-intersection.ts"
- ],
- "limitations": [
- "A mark states intent and measures nothing: overlap with the part stays unmeasured and part-volume coverage stays partial.",
- "Close a part that is meant to be solid instead of marking it."
- ],
- "kind": "operation",
- "contract": {
- "signature": "markOpenShell(part: Object3D, reason: string)",
- "returns": "Object3D (part, unchanged)",
- "units": "No lengths; reason is text of 1 to 200 characters after trimming.",
- "axes": "Three.js local XYZ; +Y is the normal up convention.",
- "origin": "Not a placement operation.",
- "execution": "sync",
- "ownership": "Writes one validated mark to part.userData.kilnOpenShell; creates no nodes and changes no geometry.",
- "coordinates": "Not a placement operation.",
- "parameters": [
- "part: a scene node, such as the mesh createPart returned or a group; a mark on a group covers the meshes under it.",
- "reason: why the shell is open, 1 to 200 characters after trimming.",
- "Only for shells open by design; close a part meant to be solid instead. A mark on a group covers its meshes. Overlap with a marked part stays unmeasured, not clear."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not clone a containing parent hierarchy."
- ],
- "semantics": [
- "QA reports a marked part that cannot be built as a closed solid as GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED with the reason, instead of GEO_PART_SELF_INTERSECTION_UNMEASURED.",
- "Overlapping pairs with the marked part stay unmeasured and are counted; overlap there is not ruled out. Overlap between other parts is still measured and reported.",
- "A marked part that builds as a closed solid is measured like any other part. A part skipped for its size, draw range, instancing or invalid indices is still reported as unmeasured.",
- "Both exporters write the mark as the node extras kilnOpenShell: { schemaVersion: 1, reason }; import restores it to userData.",
- "Invalid arguments, or a kilnOpenShell value this helper did not write, are an OPEN_SHELL build error."
- ],
- "cost": "Metadata on one node: about 50 bytes of extras plus the reason.",
- "example": "const rail = createPart('Rail', new THREE.CylinderGeometry(0.2, 0.2, 2, 16, 1, true), steel, { parent: root });\nmarkOpenShell(rail, 'Tube closed by the end plates');"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:beamBetween",
- "name": "beamBetween",
- "summary": "Creates a cylindrical rail/strut exactly between two endpoints in its parent frame. Derive attachment endpoints from the neighboring geometry; the helper does not find joints or join surfaces. Use for braces, barrels, struts, cables, and scaffolding.",
- "family": "structure",
- "tags": [
- "structure",
- "beam",
- "path",
- "placement"
- ],
- "aliases": [
- "strut",
- "brace",
- "rail"
- ],
- "intents": [
- "connect two points with a straight circular beam",
- "beam between points",
- "bar connecting endpoints"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })",
- "returns": "THREE.Object3D (prefixed `Mesh_`)",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Cylinder +Y is oriented from start to end.",
- "origin": "Midpoint of supplied endpoints.",
- "execution": "sync",
- "ownership": "Creates a new cylinder geometry and mesh; material remains shared.",
- "coordinates": "Endpoints are in the selected parent local coordinates.",
- "parameters": [
- "Finite distinct endpoints and a usable radius/segment count are required by the intended shape; full validation remains unqualified."
- ],
- "topology": [
- "Capped circular beam for nondegenerate endpoints; not automatic connection to adjacent geometry."
- ],
- "preservation": [
- "Generated cylinder geometry has normals/UVs; no input geometry is transformed."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "One mesh; triangle count grows with radial segments.",
- "example": "beamBetween('SkidBraceA', [0.8, 0.3, 0.7], [0.8, 1.0, 0.45], 0.025, black, { parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:snapTo",
- "name": "snapTo",
- "summary": "Moves a part so its world bounding box contacts or overlaps the host bounding box. Useful for coarse alignment; it does not mate exact surfaces.",
- "family": "structure",
- "tags": [
- "structure",
- "alignment",
- "bounds",
- "placement"
- ],
- "aliases": [
- "bounding box contact",
- "align surfaces"
- ],
- "intents": [
- "close a visible bounding-box gap"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "AABBs can overlap even when the actual surfaces do not."
- ],
- "kind": "operation",
- "contract": {
- "signature": "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",
- "returns": "THREE.Object3D (the part, for chaining)",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Three.js local XYZ; +Y is the normal up convention.",
- "origin": "Changes the part translation; does not create a new pivot.",
- "execution": "sync",
- "ownership": "Mutates and returns the supplied part; leaves geometry/material buffers unchanged.",
- "coordinates": "Measures world AABBs after ancestor refresh, then converts displacement into part-parent coordinates.",
- "parameters": [
- "Closes AABB gaps on all axes. Optional axis selects only the overlap-bias direction; it does not constrain movement. overlap defaults to 0.02 scene units."
- ],
- "topology": [
- "Bounding-box overlap/contact is not exact surface contact or a boolean union."
- ],
- "preservation": [
- "Preserves rotation, scale, hierarchy and geometry; translation changes."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Traverses part/host bounds; cost depends on subtree geometry.",
- "example": "const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });\nsnapTo(scope, receiver);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createLadder",
- "name": "createLadder",
- "summary": "Builds a rooted ladder with perpendicular rails/rungs and bottom/top endpoint frames and sockets. Describe or replicate result.root as one assembly. Explicit widthDirection is projected perpendicular to the endpoints.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly"
- ],
- "aliases": [
- "ladder rungs"
- ],
- "intents": [
- "build rails and evenly spaced rungs"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "No structural-load or climbability guarantee. Rail/rung access remains available; they now belong to result.root."
- ],
- "kind": "assembly",
- "contract": {
- "signature": "createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, segments?, widthAxis?, widthDirection?, parent? })",
- "returns": "{ root: Object3D, leftRail: Object3D, rightRail: Object3D, rungs: Object3D[] }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Rails follow bottom-to-top. widthAxis is a preferred basis projected perpendicular to that line; a parallel basis uses the least-aligned canonical axis.",
- "origin": "Endpoints are supplied in parent coordinates; returned root is at bottom, children are root-local.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Finite endpoints; positive width and rail/rung radii; integer rungCount 0..10000 and segments 3..4096. Width axis is x or z; explicit finite nonzero widthDirection is projected and rejects parallel directions. Endpoint distance exceeds 1e-4."
- ],
- "topology": [
- "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."
- ],
- "preservation": [
- "Does not clone a containing parent hierarchy."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "Two rails plus rungCount meshes.",
- "example": "createLadder('TowerLadder', { bottom: [0,0,0], top: [0,2.2,0], width: 0.45, rungCount: 7, material: steel, parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createWingPair",
- "name": "createWingPair",
- "summary": "Creates mirrored trapezoid aircraft wings with roots attached at +/-rootZ. Use for aircraft wings and helicopter stub wings.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly"
- ],
- "aliases": [
- "paired wings",
- "aircraft wings"
- ],
- "intents": [
- "build a symmetric pair of swept panels"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Returns left/right nodes without a shared assembly root."
- ],
- "kind": "assembly",
- "contract": {
- "signature": "createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })",
- "returns": "{ right: Object3D, left: Object3D }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. dihedral is a tip height offset, not degrees.",
- "axes": "Two wings extend toward ±Z; positive sweep moves tips toward -X.",
- "origin": "Roots at ±rootZ with optional rootX/rootY offsets.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Uses wingGeo dimensions and explicit mirrored placement."
- ],
- "topology": [
- "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."
- ],
- "preservation": [
- "Creates separately owned mirrored geometry with corrected reflected triangle winding; material remains shared."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "Two fixed-complexity wing meshes.",
- "example": "createWingPair('MainWing', olive, { rootX: 0, rootY: 1.0, rootZ: 0.42, span: 2.4, rootChord: 0.9, tipChord: 0.35, sweep: 0.25, dihedral: 0.08, parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:room",
- "name": "room",
- "summary": "Creates four walls with rectangular openings and an optional floor. Front faces +X; compose, stack or adapt rooms without selecting an asset category.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly"
- ],
- "aliases": [
- "hollow room",
- "interior"
- ],
- "intents": [
- "build an enterable room",
- "hollow enclosure",
- "walls and floor",
- "room with doors and windows"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "assembly:wallWithOpening",
- "relation": "companion"
- },
- {
- "id": "assembly:createGableShell",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "assembly",
- "contract": {
- "signature": "room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",
- "returns": "{ root: Object3D, walls: { front, back, left, right }, floor: Object3D | null }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Width spans Z, depth spans X, height Y; front faces +X.",
- "origin": "Wall base and floor top are local Y=0; floor extends downward.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Default width/depth/height describe a small room; dimensions are not an overall building/storey limit.",
- "Per-wall rectangular openings are explicit; floor may be disabled.",
- "Use for any building the player enters. Do NOT model a building as a solid block — room() guarantees real interior space and a doorway gap. Pass openings to add windows / side doors."
- ],
- "topology": [
- "Four box-segment walls with real apertures; optional floor. No roof or automatic whole-building watertightness."
- ],
- "preservation": [
- "Does not clone a containing parent hierarchy."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "Mesh count grows with aperture segmentation, plus optional floor.",
- "example": "const { root: hut } = room('Hut', wood, { width: 5, depth: 4, height: 2.8, openings: [{ wall: 'front', kind: 'door' }, { wall: 'right', kind: 'window' }], parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:wallWithOpening",
- "name": "wallWithOpening",
- "summary": "A wall panel with real rectangular door/window gaps, composed from solid box segments. Supply opening or openings, never both. Multiple or vertically stacked apertures must not overlap or extend outside the wall. Base at local Y=0, centered on the run axis. Use to compose custom layouts and interior dividing walls.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly"
- ],
- "aliases": [
- "door opening",
- "window wall",
- "partition"
- ],
- "intents": [
- "build a wall with real doorway or window gaps",
- "wall aperture",
- "cut a window",
- "doorway opening",
- "door or window in a wall"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "assembly",
- "contract": {
- "signature": "wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, openings?: [{ kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",
- "returns": "THREE.Object3D (wall container)",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Wall run axis X or Z; vertical axis Y.",
- "origin": "Centered on run axis; base Y=0.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Positive finite length/height/thickness; opening or openings, never both.",
- "Rectangular apertures must not overlap or extend outside the wall; touching edges are allowed."
- ],
- "topology": [
- "Actual aperture gaps are composed from box segments; no solid boolean or wall-assembly union."
- ],
- "preservation": [
- "Does not clone a containing parent hierarchy."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "Segmentation grows with aperture boundary coordinates; no generic architectural complexity cap.",
- "example": "wallWithOpening('Partition', plaster, { length: 4, height: 2.8, thickness: 0.12, axis: 'x', opening: { kind: 'door', offset: 0.5 }, parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createRoofPlanes",
- "name": "createRoofPlanes",
- "summary": "A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite tilts — never mirrored the same way), footprint-matched with an eave overhang. Outer top eave at local Y=0, ridge at Y=height. Thickness extends inward. For a wall-bearing datum use createGableRoof. Returns a named group (e.g. `Roof`) the engine can lift to reveal the interior.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly"
- ],
- "aliases": [
- "pitched roof planes"
- ],
- "intents": [
- "place two roof slopes over walls"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "assembly:createGableRoof",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "assembly",
- "contract": {
- "signature": "createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
- "returns": "{ root: Object3D, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Pitched gable roof; ridgeAxis selects X or Z.",
- "origin": "Outer top eave at local Y=0; ridge reaches height. Roof thickness extends inward.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "width spans Z and depth spans X; createGableRoof exposes explicit spanX/spanZ instead.",
- "The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does this for you. Its outer top eave is the datum; createGableRoof instead anchors the wall bearing line."
- ],
- "topology": [
- "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."
- ],
- "preservation": [
- "One shared constructor across imports; returns root/slopes/face frames. Use describeAssembly(result.root) for common access and replication."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "Two slope meshes plus root.",
- "example": "const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height: 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root });\nroof.position.y = 2.8;"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createGableRoof",
- "name": "createGableRoof",
- "summary": "Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions, and a live local-to-world transform.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly",
- "architecture",
- "gable"
- ],
- "aliases": [
- "gable roof",
- "roof face frames"
- ],
- "intents": [
- "build a pitched roof with usable attachment frames"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "assembly:createRoofSurfaceLayout",
- "relation": "companion"
- }
- ],
- "references": [
- "src/architecture.ts"
- ],
- "limitations": [],
- "kind": "assembly",
- "contract": {
- "signature": "createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
- "returns": "{ root, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. pitchDegrees uses degrees.",
- "axes": "spanX/spanZ are explicit footprint axes; ridgeAxis X or Z.",
- "origin": "Wall-bearing line at Y=0; rise determines ridge elevation. Overhang descends below the bearing line.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Finite positive footprint spans; validated rise/pitch, overhang and thickness options.",
- "Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof panels run along each returned face downhill direction."
- ],
- "topology": [
- "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."
- ],
- "preservation": [
- "Returns live rigid roof-face frames with tangents, normals, dimensions and world conversion."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "Two roof slopes with frame metadata.",
- "example": "const roof = createGableRoof('Roof', shingles, { spanX: 8, spanZ: 5, pitchDegrees: 35, overhang: 0.35, ridgeAxis: 'x', parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createGableEndPanel",
- "name": "createGableEndPanel",
- "summary": "Exact thick triangular end closure for a gable roof, with optional rectangular openings cut from the geometry and semantic boundary metadata.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly",
- "architecture",
- "gable"
- ],
- "aliases": [
- "triangular end wall",
- "gable closure"
- ],
- "intents": [
- "close a pitched roof end"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/architecture.ts"
- ],
- "limitations": [],
- "kind": "assembly",
- "contract": {
- "signature": "createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })",
- "returns": "{ root, geometry, openings }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Vertical triangular panel perpendicular to ridgeAxis; side chooses the outward end.",
- "origin": "Panel base Y=0, centered across span.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Finite positive span/rise/thickness; explicit rectangular opening dimensions/offsets."
- ],
- "topology": [
- "Triangulated thick gable closure with clipped apertures; this is one panel, not a complete building."
- ],
- "preservation": [
- "Generated panel geometry and semantic boundary metadata; input material shared."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "Depends on aperture clipping and triangulation.",
- "example": "createGableEndPanel('FrontGable', siding, { span: 5, rise: 1.8, ridgeAxis: 'x', side: 'positive', parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createGableShell",
- "name": "createGableShell",
- "summary": "Composes a gable-roof building shell from walls, floor, slopes and end panels, with optional enterability and openings.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly",
- "architecture",
- "gable"
- ],
- "aliases": [
- "gable building shell"
- ],
- "intents": [
- "construct a small pitched-roof enclosure",
- "enclosed building shell",
- "gable house with openings"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/architecture.ts"
- ],
- "limitations": [
- "Gable-specific construction; not a universal building generator."
- ],
- "kind": "assembly",
- "contract": {
- "signature": "createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })",
- "returns": "{ root, walls, floor, roof, gables, openings }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "spanX/spanZ, +Y wall height and X/Z ridge axis; front is +X.",
- "origin": "Floor top and wall base Y=0.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "Optional floor/gable materials use documented defaults; openings/enterability are explicit.",
- "One gable shell per call; arbitrary environments can compose multiple shells or other geometry.",
- "Use for complete gable buildings. It stamps wall, floor, slope, gable, opening, adjacency, coverage, and separability semantics for deterministic QA and roof-off views."
- ],
- "topology": [
- "Separate walls/floor/slopes/end panels; closed-by-default enclosure does not imply one manifold mesh."
- ],
- "preservation": [
- "Creates semantic wall, opening, roof and boundary descriptions."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "Depends on wall/opening segmentation and gable geometry.",
- "example": "const house = createGableShell('House', { wall: plaster, roof: shingles }, { spanX: 8, spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x', parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createRoofSurfaceLayout",
- "name": "createRoofSurfaceLayout",
- "summary": "Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame, so repeated elements run ridge-to-eave for either ridge axis without manual Euler rotations.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly",
- "architecture",
- "gable"
- ],
- "aliases": [
- "roof shingles",
- "standing seams",
- "corrugated roof"
- ],
- "intents": [
- "repeat details consistently over a roof face"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "assembly:createGableRoof",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/architecture.ts"
- ],
- "limitations": [
- "Box approximations, not interlocking or physically folded roofing. Material and visual quality still need review.",
- "Separate-parent placement is a construction-time snapshot. Reparenting that requires local shear is rejected; use face.roofRoot to preserve inherited affine transforms."
- ],
- "kind": "assembly",
- "contract": {
- "signature": "createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })",
- "returns": "{ root, items: Object3D[], cost: { meshes, triangles } }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Uses the supplied roof-face tangent/downhill/normal frame.",
- "origin": "Relative to the supplied roof face.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "kind selects panels/shingles/seams/corrugations; finite positive dimensions and at most 10000 generated boxes.",
- "Panels keep 2% width gaps; staggered shingles keep 4% gaps within clipped boundary cells, overlap rows by up to 8%, and clip at the eave.",
- "Seams/corrugations clip edge strips to the face; a face narrower than one strip receives one clipped strip.",
- "Always pass the face object returned by createGableRoof/createGableShell. Never infer the panel rotation from world axes."
- ],
- "topology": [
- "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."
- ],
- "preservation": [
- "Uses live face frames; creates individual mesh elements with shared material."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "Returns cost.meshes and cost.triangles (12 per box); one mesh per element, no hardware-instanced batching or draw-call promise.",
- "example": "for (const face of roof.faces) createRoofSurfaceLayout('Panels_' + face.side, metal, { face, kind: 'panels', parent: roof.root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "assembly:createStairs",
- "name": "createStairs",
- "summary": "A straight flight of stairs: box treads (with optional risers) climbing totalRise over totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in a multi-storey building.",
- "family": "structure",
- "tags": [
- "structure",
- "assembly"
- ],
- "aliases": [
- "stair flight",
- "steps"
- ],
- "intents": [
- "connect elevations with straight stairs",
- "stair flight",
- "steps",
- "tiered seating",
- "rise and run"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "No curved staircase, landing sockets or navigability certificate."
- ],
- "kind": "assembly",
- "contract": {
- "signature": "createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })",
- "returns": "{ root: Object3D, steps: Object3D[] }",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Signed totalRise changes Y; signed totalRun advances along selected X or Z.",
- "origin": "Starts from the local origin; totalRise/totalRun define the flight.",
- "execution": "sync",
- "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",
- "coordinates": "Parent-local transform inputs, not automatic world-space placement.",
- "parameters": [
- "steps must be an integer from 1 to 10000; finite rise/run magnitudes below 1e-4 are rejected.",
- "Width and treadThickness are positive finite. Negative rise/run preserve descending/reversed placement with positive solid dimensions."
- ],
- "topology": [
- "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."
- ],
- "preservation": [
- "Does not clone a containing parent hierarchy."
- ],
- "semantics": [
- "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."
- ],
- "cost": "steps treads plus optional steps risers.",
- "example": "createStairs('Porch', stone, { steps: 4, totalRise: 0.6, totalRun: 1.0, width: 1.4, axis: 'x', parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:boxGeo",
- "name": "boxGeo",
- "summary": "6-face box. 12 tris regardless of size. Cheapest geometry.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "cuboid",
- "rectangular prism"
- ],
- "intents": [
- "make a rectangular block"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "boxGeo(width: number, height: number, depth: number)",
- "returns": "THREE.BoxGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Width X, height Y, depth Z.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "12 triangles; dimensions do not increase tessellation.",
- "example": "const geo = boxGeo(1, 0.5, 2);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:sphereGeo",
- "name": "sphereGeo",
- "summary": "UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "ball",
- "orb"
- ],
- "intents": [
- "make a rounded ball"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Raw computeVertexNormals replaces analytic normals and can leave unused pole vertices with zero normals, which fail GLTF validation. Preserve the existing normals for affine transforms."
- ],
- "kind": "operation",
- "contract": {
- "signature": "sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)",
- "returns": "THREE.SphereGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Latitude axis Y; circular cross-sections in XZ.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Supplies analytic normals and UVs. Geometry scale/rotation transforms the existing normals; no extra computeVertexNormals is needed for those transforms."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Grows with widthSegments × heightSegments; default 8 × 6.",
- "example": "const geo = sphereGeo(0.5, 12, 8);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:cylinderGeo",
- "name": "cylinderGeo",
- "summary": "Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "y axis cylinder",
- "frustum"
- ],
- "intents": [
- "make an axle or tapered circular body"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
- "returns": "THREE.CylinderGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Cylinder axis Y; radiusTop is toward +Y, radiusBottom toward -Y.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "Each radius is nonnegative; at least one must be positive. Height/length is positive."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments, default 8; 3 to 4096 radial segments.",
- "example": "const geo = cylinderGeo(0.25, 0.25, 1, 12);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:cylinderYGeo",
- "name": "cylinderYGeo",
- "summary": "Alias for cylinderGeo — a Y-axis cylinder. Provided because the sandbox exposes cylinderXGeo / cylinderZGeo and the symmetric Y form is commonly reached for.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "y axis cylinder",
- "frustum"
- ],
- "intents": [
- "make an axle or tapered circular body"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "cylinderYGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
- "returns": "THREE.CylinderGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Cylinder axis Y; radiusTop is toward +Y, radiusBottom toward -Y.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "Each radius is nonnegative; at least one must be positive. Height/length is positive."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments, default 8; 3 to 4096 radial segments.",
- "example": "const geo = cylinderYGeo(0.25, 0.25, 1, 12);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:cylinderXGeo",
- "name": "cylinderXGeo",
- "summary": "Cylinder pre-rotated to run along +X/-X. Use for fuselages, cannons, barrels, axles, and forward-facing tubes.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "x axis cylinder",
- "frustum"
- ],
- "intents": [
- "make an axle or tapered circular body"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "cylinderXGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
- "returns": "THREE.CylinderGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Cylinder axis X; radiusTop is toward +X, radiusBottom toward -X.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "Each radius is nonnegative; at least one must be positive. Height/length is positive."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments, default 8; 3 to 4096 radial segments.",
- "example": "const geo = cylinderXGeo(0.1, 0.1, 1.2, 12);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:cylinderZGeo",
- "name": "cylinderZGeo",
- "summary": "Cylinder pre-rotated to run along +Z/-Z. Use for side-mounted weapons, rails, crossbars, and pipes.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "z axis cylinder",
- "frustum"
- ],
- "intents": [
- "make an axle or tapered circular body"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "cylinderZGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
- "returns": "THREE.CylinderGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Cylinder axis Z; radiusTop is toward +Z, radiusBottom toward -Z.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "Each radius is nonnegative; at least one must be positive. Height/length is positive."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments, default 8; 3 to 4096 radial segments.",
- "example": "const geo = cylinderZGeo(0.08, 0.08, 0.9, 10);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:cylinderOnAxis",
- "name": "cylinderOnAxis",
- "summary": "Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when the cylinder needs to point along a non-cardinal direction (struts inside CSG operands, antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo / cylinderYGeo / cylinderZGeo helpers.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "oriented cylinder"
- ],
- "intents": [
- "align a cylinder to a non-cardinal direction"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom: number, height: number, opts?: { radiusTop?, segments? })",
- "returns": "THREE.CylinderGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Local +Y is rotated onto the supplied normal; top cap follows normal.",
- "origin": "Vertices are translated to the supplied center.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "center and normal are finite triples. Normal length must be at least 1e-6; normalization handles large finite components. Cylinder radii are nonnegative with at least one positive; height is positive."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments plus a vertex transform.",
- "example": "const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:capsuleGeo",
- "name": "capsuleGeo",
- "summary": "Stadium shape (cylinder with hemispherical caps). Good for limbs.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "pill",
- "rounded capsule"
- ],
- "intents": [
- "make a rounded limb or pod"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "capsuleGeo(radius: number, height: number, segments?: 6)",
- "returns": "THREE.CapsuleGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Longitudinal axis Y.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "height/length is the nonnegative straight middle section; zero is supported. Radius is positive; total outer length is height/length + 2 × radius.",
- "Cap subdivision is fixed at 2; radial segments default to 6."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments with fixed cap subdivision.",
- "example": "const geo = capsuleGeo(0.1, 0.5, 6);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:capsuleYGeo",
- "name": "capsuleYGeo",
- "summary": "Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo / capsuleZGeo.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "pill",
- "rounded capsule"
- ],
- "intents": [
- "make a rounded limb or pod"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "capsuleYGeo(radius: number, height: number, segments?: 6)",
- "returns": "THREE.CapsuleGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Longitudinal axis Y.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "height/length is the nonnegative straight middle section; zero is supported. Radius is positive; total outer length is height/length + 2 × radius.",
- "Cap subdivision is fixed at 2; radial segments default to 6."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments with fixed cap subdivision.",
- "example": "const geo = capsuleYGeo(0.1, 0.5, 6);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:capsuleXGeo",
- "name": "capsuleXGeo",
- "summary": "Capsule pre-rotated to run along +X/-X. Use for aircraft bodies, rounded vehicle hulls, and missiles.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "pill",
- "rounded capsule"
- ],
- "intents": [
- "make a rounded limb or pod"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "capsuleXGeo(radius: number, length: number, segments?: 6)",
- "returns": "THREE.CapsuleGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Longitudinal axis X.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "height/length is the nonnegative straight middle section; zero is supported. Radius is positive; total outer length is height/length + 2 × radius.",
- "Cap subdivision is fixed at 2; radial segments default to 6."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments with fixed cap subdivision.",
- "example": "const geo = capsuleXGeo(0.35, 2.4, 10);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:capsuleZGeo",
- "name": "capsuleZGeo",
- "summary": "Capsule pre-rotated to run along +Z/-Z. Use for lateral pods, floats, and side tanks.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "pill",
- "rounded capsule"
- ],
- "intents": [
- "make a rounded limb or pod"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "capsuleZGeo(radius: number, length: number, segments?: 6)",
- "returns": "THREE.CapsuleGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Longitudinal axis Z.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "height/length is the nonnegative straight middle section; zero is supported. Radius is positive; total outer length is height/length + 2 × radius.",
- "Cap subdivision is fixed at 2; radial segments default to 6."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments with fixed cap subdivision.",
- "example": "const geo = capsuleZGeo(0.18, 1.1, 8);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:coneGeo",
- "name": "coneGeo",
- "summary": "Y-axis cone (pointed up). Use for spikes, roofs, projectiles.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "pointed cone",
- "spike"
- ],
- "intents": [
- "make a tapered point"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "coneGeo(radius: number, height: number, segments?: 8)",
- "returns": "THREE.ConeGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Apex points toward +Y; height/length spans the Y axis.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments, default 8.",
- "example": "const geo = coneGeo(0.3, 0.8, 8);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:coneYGeo",
- "name": "coneYGeo",
- "summary": "Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo / coneZGeo.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "pointed cone",
- "spike"
- ],
- "intents": [
- "make a tapered point"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "coneYGeo(radius: number, height: number, segments?: 8)",
- "returns": "THREE.ConeGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Apex points toward +Y; height/length spans the Y axis.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments, default 8.",
- "example": "const geo = coneYGeo(0.3, 0.8, 8);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:coneXGeo",
- "name": "coneXGeo",
- "summary": "Cone pre-rotated so its point faces +X. Use for noses, rockets, shells, and forward-facing tips.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "pointed cone",
- "spike"
- ],
- "intents": [
- "make a tapered point"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "coneXGeo(radius: number, length: number, segments?: 8)",
- "returns": "THREE.ConeGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Apex points toward +X; height/length spans the X axis.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments, default 8.",
- "example": "const geo = coneXGeo(0.18, 0.45, 12);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:coneZGeo",
- "name": "coneZGeo",
- "summary": "Cone pre-rotated so its point faces +Z. Use for side-facing projectiles and tips.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "pointed cone",
- "spike"
- ],
- "intents": [
- "make a tapered point"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "coneZGeo(radius: number, length: number, segments?: 8)",
- "returns": "THREE.ConeGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Apex points toward +Z; height/length spans the Z axis.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments, default 8.",
- "example": "const geo = coneZGeo(0.12, 0.35, 10);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:taperConeGeo",
- "name": "taperConeGeo",
- "summary": "Truncated cone (frustum) — exposes both bottom and top radius. radiusTop=0 matches coneGeo, radiusTop=radiusBottom matches cylinderGeo. Use for pylon caps, soda cans, lampshades, anything tapered that does not come to a point. axis selects orientation (default Y).",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "truncated cone",
- "frustum"
- ],
- "intents": [
- "make a circular taper with two end radii"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "taperConeGeo(radiusBottom: number, radiusTop: number, height: number, axis?: 'x'|'y'|'z', segments?: 8)",
- "returns": "THREE.CylinderGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "axis must be x/y/z, default y; smaller radius is not inferred from the parameter name.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "Radii are nonnegative, with at least one positive. Height is positive."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in radial segments, default 8.",
- "example": "const cap = taperConeGeo(0.3, 0.18, 0.4); // frustum"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:torusGeo",
- "name": "torusGeo",
- "summary": "Donut shape. For rings, tyres, barrel ribs.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "donut",
- "ring"
- ],
- "intents": [
- "make a circular ring with a round tube"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)",
- "returns": "THREE.TorusGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Ring lies in XY; hole axis Z.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Grows with radialSegments × tubularSegments (defaults 8 × 12).",
- "example": "const geo = torusGeo(0.4, 0.04, 8, 16);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:planeGeo",
- "name": "planeGeo",
- "summary": "Creates a subdividable XY rectangular sheet with UVs. Place and orient it explicitly; use a solid primitive when thickness matters.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "quad",
- "sheet"
- ],
- "intents": [
- "make a flat textured surface"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)",
- "returns": "THREE.PlaneGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Width X, height Y; front normal +Z.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."
- ],
- "topology": [
- "Open rectangular sheet; no thickness or watertightness."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "2 × widthSegments × heightSegments triangles.",
- "example": "const geo = planeGeo(4, 4);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:decalBox",
- "name": "decalBox",
- "summary": "Thin box for solid-color surface decals: red stars, hull numbers, stamps, no-texture windows. Unlike planeGeo, has real depth so it visibly attaches to its host surface. Must be placed on a surface with position + rotation.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "thin plaque",
- "solid decal"
- ],
- "intents": [
- "attach a colored plate to a surface"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Does not place itself on another surface or prevent z-fighting."
- ],
- "kind": "operation",
- "contract": {
- "signature": "decalBox(width: number, height: number, depth?: 0.01)",
- "returns": "THREE.BoxGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Width X, height Y, depth Z.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",
- "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",
- "Width/height positive; depth nonnegative, default 0.01 and clamped to a documented minimum of 0.002.",
- "Offset at least 0.01 outside the host surface to avoid z-fighting (a 0.8-wide hull has faces at z=±0.4, so place the decal at z=±0.41)."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "12 triangles; default depth 0.01 scene units.",
- "example": "const star = decalBox(0.18, 0.18, 0.01);\ncreatePart('Mesh_StarPort', star, gameMaterial(0xc61f2a), { position: [0.4, 0.6, 0.41], parent: fuselage });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:foliageCardGeo",
- "name": "foliageCardGeo",
- "summary": "Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the ground. Pair with an alpha-tested material and a leaf/plant sprite.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "leaf card",
- "billboard"
- ],
- "intents": [
- "make a plant sprite card",
- "thin leaf cutout",
- "foliage card"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "foliageCardGeo(opts?: { width?, height?, yPivot?: 0..1 })",
- "returns": "THREE.PlaneGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Card lies in XY, front normal +Z.",
- "origin": "yPivot is a fraction of height; 0 puts the bottom edge at Y=0, 0.5 centers it.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Positive finite width/height; yPivot may lie outside 0..1, but resulting coordinates must fit finite Float32.",
- "The example uses an approved 4x4 teaching placeholder, not production foliage detail."
- ],
- "topology": [
- "One open quad; alpha masking is material behavior, not geometric trimming."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Stamps kilnGeometryRole=foliageCard."
- ],
- "cost": "Two triangles.",
- "example": "const albedo = await loadApprovedTexture('kiln.texture.leaf-mask-albedo.v1');\nconst leaves = foliageMaterial(albedo);\nconst quad = foliageCardGeo({ width: 0.6, height: 1, yPivot: 0 });\ncreatePart('LeafCard', quad, leaves, { parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:crossedQuadsGeo",
- "name": "crossedQuadsGeo",
- "summary": "Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a dense plant from any angle, cheaper than real geometry.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "cross billboard",
- "bush cards"
- ],
- "intents": [
- "make inexpensive vegetation with multiple silhouettes"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "crossedQuadsGeo(opts?: { width?, height?, planes?: 2 | 3, yPivot? })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Intersecting vertical sheets rotate around Y.",
- "origin": "yPivot controls the Y datum as a fraction of height.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Positive finite width/height; finite Float32 coordinates after pivot; planes must be exactly 2 or 3."
- ],
- "topology": [
- "Intersecting open quads; not a closed solid."
- ],
- "preservation": [
- "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",
- "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."
- ],
- "semantics": [
- "Stamps billboard geometry role metadata."
- ],
- "cost": "Two triangles per plane; intended plane count is 2 or 3.",
- "example": "const leaves = await materialRecipe('kiln.material.leaf.v1');\nconst bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });\ncreatePart('Mesh_Bush', bush, leaves, { parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:octaGridPlane",
- "name": "octaGridPlane",
- "summary": "Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas; the consumer shader adds per-instance tile offsets at draw time.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "atlas billboard",
- "impostor card"
- ],
- "intents": [
- "make a card for an atlas-aware runtime"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "The GLB material alone does not implement per-instance tile selection."
- ],
- "kind": "operation",
- "contract": {
- "signature": "octaGridPlane({ tilesX, tilesY, width?, height?, yPivot? })",
- "returns": "THREE.PlaneGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Atlas card lies in XY, front normal +Z.",
- "origin": "yPivot controls the Y datum as a fraction of height.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "tilesX/tilesY must be positive safe integers; width/height positive finite and pivoted coordinates finite Float32."
- ],
- "topology": [
- "Open quad; atlas tile selection requires consumer shader support."
- ],
- "preservation": [
- "Generates UVs covering the top-left atlas tile; no tile-selection shader is generated."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Two triangles independent of atlas tile count.",
- "example": "const card = octaGridPlane({ tilesX: 4, tilesY: 4, width: 6, height: 6 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:wingGeo",
- "name": "wingGeo",
- "summary": "Trapezoid wing panel. Local root edge is at Z=0, span extends toward +Z, positive sweep moves the tip aft along -X.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "trapezoid wing",
- "tapered panel"
- ],
- "intents": [
- "make a swept wing panel"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. dihedral is tip Y displacement, not an angle.",
- "axes": "Root at Z=0, span toward +Z; positive sweep shifts the tip leading edge toward -X relative to the root leading edge, not the chord midpoint.",
- "origin": "Root chord midpoint at [0,0,0].",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Positive finite span/rootChord/thickness; tipChord may be zero for a pointed wing. Signed sweep and dihedral are finite length displacements; generated coordinates must fit Float32."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Creates positions and normals; no UV attribute is generated."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Fixed trapezoid or triangular prism tessellation.",
- "example": "const geo = wingGeo({ span: 2.2, rootChord: 0.8, tipChord: 0.3, sweep: 0.25, dihedral: 0.08 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:gearGeo",
- "name": "gearGeo",
- "summary": "Stylized gear with flat edges and an optional center bore; no CSG. Use boreRadius < rootRadius < tipRadius. Radii are absolute: an omitted rootRadius stays 0.8 when tipRadius changes. Set all three radii for small gears.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "cog",
- "sprocket"
- ],
- "intents": [
- "make a stylized toothed wheel"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/gears.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "gearGeo(opts?: { teeth?: 12, rootRadius?: 0.8, tipRadius?: 1.0, boreRadius?: 0.2, height?: 0.3, toothWidthFrac?: 0.5 })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Gear lies in XZ, thickness on Y.",
- "origin": "Centered at local [0,0,0] unless this helper states another datum.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Absolute bore/root/tip radii; do not assume an omitted root radius scales with tipRadius.",
- "teeth is an integer from 3 to 4096; finite radii obey 0 <= bore < root < tip, height is positive, and toothWidthFrac is strictly between 0 and 1.",
- "Stylized teeth, not an involute engineering profile."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Creates positions and normals; UV preservation is not applicable and UVs are not generated."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Linear in tooth count; inspect tooth and radius validity.",
- "example": "const g = gearGeo({ teeth: 28, rootRadius: 0.063, tipRadius: 0.075, boreRadius: 0.012, height: 0.024 });\ncreatePart('Gear', g, gameMaterial(0x909090, { metalness: 0.8 }), { parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:bladeGeo",
- "name": "bladeGeo",
- "summary": "Parametric sword blade: rectangular base tapering to a point over tipLength. edgeBevel > 0 pinches the cross-section toward a diamond ridge.",
- "family": "geometry",
- "tags": [
- "geometry",
- "primitive",
- "shared geometry"
- ],
- "aliases": [
- "sword blade",
- "tapered blade"
- ],
- "intents": [
- "make a pointed blade"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyGeometry",
- "relation": "companion"
- },
- {
- "id": "operation:createPart",
- "relation": "companion"
- }
- ],
- "references": [
- "src/gears.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?: 0.25, edgeBevel?: 0 })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Length +Y, width X, thickness Z.",
- "origin": "Blade base at Y=0; centered across width and thickness.",
- "execution": "sync",
- "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",
- "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",
- "parameters": [
- "Positive finite length/baseWidth/thickness; 0 <= tipLength < length; edgeBevel is finite in 0..1. Zero tip length is a square end.",
- "edgeBevel controls a closed cross-section: flat rectangle at 0, partial bevels, diamond at 1. This is not a generic mesh bevel."
- ],
- "topology": [
- "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."
- ],
- "preservation": [
- "Creates positions and normals; UVs are not generated."
- ],
- "semantics": [
- "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."
- ],
- "cost": "Fixed tessellation with a bounded choice of cross-section; beveled tips taper to one point.",
- "example": "const b = bladeGeo({ length: 1.6, baseWidth: 0.09, tipLength: 0.3, edgeBevel: 0.5 });\ncreatePart('Blade', b, steel, { position: [0, 0, 0], parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:gameMaterial",
- "name": "gameMaterial",
- "summary": "Creates a configurable MeshStandardMaterial with flat shading enabled by default.",
- "family": "material",
- "tags": [
- "material"
- ],
- "aliases": [
- "flat shaded PBR"
- ],
- "intents": [
- "make a simple solid-color PBR material"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyMaterial",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",
- "returns": "THREE.MeshStandardMaterial",
- "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",
- "axes": "Not applicable to material construction.",
- "origin": "Not applicable to material construction.",
- "execution": "sync",
- "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",
- "coordinates": "Does not place geometry or generate UV coordinates.",
- "parameters": [
- "MeshStandardMaterial; defaults to flat shading with configurable roughness/metalness/emissive."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Material portability depends on supported glTF properties and the selected exporter; renderer appearance is not a portability guarantee."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",
- "example": "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:materialRecipe",
- "name": "materialRecipe",
- "summary": "Resolves a versioned portable bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF PBR.",
- "family": "material",
- "tags": [
- "material"
- ],
- "aliases": [
- "material preset"
- ],
- "intents": [
- "start from a named reusable material recipe"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyMaterial",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts",
- "src/material-recipes.ts"
- ],
- "limitations": [
- "A recipe name does not imply surface relief, geometry, or visual qualification."
- ],
- "kind": "operation",
- "contract": {
- "signature": "await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })",
- "returns": "Promise<THREE.MeshStandardMaterial>",
- "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",
- "axes": "Not applicable to material construction.",
- "origin": "Not applicable to material construction.",
- "execution": "async",
- "ownership": "Resolves a new portable material through the host-injected recipe/texture boundary; resource caching is host-specific.",
- "coordinates": "Does not place geometry or generate UV coordinates.",
- "parameters": [
- "A versioned approved recipe ID and its permitted overrides; availability depends on host resources.",
- "textureResources maps baseColor, normal, metallicRoughness, emissive or occlusion to approved resource ID strings. Use baseColor here, not the pbrMaterial field albedo. Check each resource allowedSlots and recipeIds.",
- "Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. textureResources uses portable slots baseColor, normal, metallicRoughness, emissive and occlusion with ID string values; albedo is a pbrMaterial field, not a recipe slot. Check resource allowedSlots and recipeIds. All numeric overrides (including emissiveIntensity) are finite 0..1. Recipe emission is baked into the core glTF emissive factor. Leaf is MASK, glass is BLEND, and host file paths are forbidden. Overrides differ by recipe; any other key is rejected: bark, wood, stone, rubber, painted-metal, cloth: baseColor, roughness, metalness, doubleSided, textureResources; leaf: baseColor, roughness, alphaCutoff, doubleSided, textureResources; skin: baseColor, roughness, doubleSided; glass: baseColor, roughness, opacity, doubleSided; emissive: baseColor, roughness, doubleSided, emissiveColor, emissiveIntensity, textureResources."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Compiles portable material settings; texture delivery/quality is explicit resource metadata."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",
- "example": "const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:compilePortableMaterialSpecV2",
- "name": "compilePortableMaterialSpecV2",
- "summary": "Compiles the strict portable material contract. Texture refs are typed procedural V2 specs or typed approved-resource references; bare IDs, paths, URLs, raw textures, callbacks, and shader source are rejected.",
- "family": "material",
- "tags": [
- "material"
- ],
- "aliases": [
- "portable material specification",
- "project material library"
- ],
- "intents": [
- "compile a strict portable material definition"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyMaterial",
- "relation": "companion"
- }
- ],
- "references": [
- "src/portable-material-runtime.ts",
- "docs/material-library.md",
- "docs/projects-and-live-review.md"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })",
- "returns": "Promise<THREE.MeshStandardMaterial>",
- "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",
- "axes": "Not applicable to material construction.",
- "origin": "Not applicable to material construction.",
- "execution": "async",
- "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",
- "coordinates": "Does not place geometry or generate UV coordinates.",
- "parameters": [
- "Strict schemaVersion 2 pbrMetallicRoughness specification.",
- "For workspace library materials, use the exact portableSpec returned by kiln_material and pin its material revision through per-call materialDependencies (CLI --materials) or an optional project lock. The host supplies verified map bytes; generated source cannot read library paths or fetch missing resources.",
- "baseColor and emissive are numeric color integers from 0x000000 to 0xffffff, for example baseColor: 0x8a867c. CSS strings and materialRecipe hex-string overrides are not accepted here.",
- "Texture references use typed procedural specs or approved resource IDs; arbitrary URLs, paths, callbacks and shaders are rejected.",
- "Each texture value is { kind: \"resource\", resourceId: \"kiln.texture...\" } or { kind: \"procedural\", spec: { schemaVersion: 2, ... } }. Bare ID strings are invalid; unlike materialRecipe.textureResources, this API requires the tagged object.",
- "Use textures: { baseColor: { kind: \"resource\", resourceId: \"kiln.texture.rough-concrete-albedo.v1\" } } for an approved resource, or { kind: \"procedural\", spec: { schemaVersion: 2, ... } }; bare ID strings are invalid. Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref usage must match its slot; resource refs must be approved for that exact slot. baseColor and emissive are numeric color integers from 0x000000 to 0xffffff, not CSS or materialRecipe hex strings. roughness, metalness and alphaCutoff are finite 0..1; emissiveIntensity is finite 0..64 (unlike materialRecipe, whose intensity is 0..1)."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Enforces supported portable material representation; does not certify visual similarity in every consumer."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",
- "example": "const steel = await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', roughness: 0.45, metalness: 0.85, textures: { metallicRoughness: { kind: 'procedural', spec: { schemaVersion: 2, usage: 'metallicRoughness', size: 64, layers: [{ op: 'solid', color: 0x0080cc }] } } } });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:basicMaterial",
- "name": "basicMaterial",
- "summary": "Unlit flat material. For UI / effects where lighting is baked in.",
- "family": "material",
- "tags": [
- "material"
- ],
- "aliases": [
- "unlit material"
- ],
- "intents": [
- "make an unlit surface"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyMaterial",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Does not provide physical lighting response."
- ],
- "kind": "operation",
- "contract": {
- "signature": "basicMaterial(color, opts?: { transparent, opacity })",
- "returns": "THREE.MeshBasicMaterial",
- "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",
- "axes": "Not applicable to material construction.",
- "origin": "Not applicable to material construction.",
- "execution": "sync",
- "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",
- "coordinates": "Does not place geometry or generate UV coordinates.",
- "parameters": [
- "Inspect alpha, roughness, metalness and color inputs against the exact signature."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Creates MeshBasicMaterial; unlit behavior depends on exporter and destination support."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",
- "example": "const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:glassMaterial",
- "name": "glassMaterial",
- "summary": "Creates a transparent double-sided standard material using alpha blending.",
- "family": "material",
- "tags": [
- "material"
- ],
- "aliases": [
- "transparent panel"
- ],
- "intents": [
- "make a transparent-looking panel"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyMaterial",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Approximate transparency, not physical transmission or refraction; sorting and overlapping surfaces require review."
- ],
- "kind": "operation",
- "contract": {
- "signature": "glassMaterial(color, opts?: { opacity, roughness, metalness })",
- "returns": "THREE.MeshStandardMaterial",
- "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",
- "axes": "Not applicable to material construction.",
- "origin": "Not applicable to material construction.",
- "execution": "sync",
- "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",
- "coordinates": "Does not place geometry or generate UV coordinates.",
- "parameters": [
- "Creates alpha-blended, double-sided MeshStandardMaterial; opacity is configurable."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Material portability depends on supported glTF properties and the selected exporter; renderer appearance is not a portability guarantee."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",
- "example": "const mat = glassMaterial(0x66ccff, { opacity: 0.3 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:lambertMaterial",
- "name": "lambertMaterial",
- "summary": "Creates a diffuse MeshLambertMaterial with optional flat shading and emission.",
- "family": "material",
- "tags": [
- "material"
- ],
- "aliases": [
- "diffuse material"
- ],
- "intents": [
- "make a simple diffuse surface"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyMaterial",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Portable export may approximate the original shading model."
- ],
- "kind": "operation",
- "contract": {
- "signature": "lambertMaterial(color, opts?: { flatShading, emissive })",
- "returns": "THREE.MeshLambertMaterial",
- "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",
- "axes": "Not applicable to material construction.",
- "origin": "Not applicable to material construction.",
- "execution": "sync",
- "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",
- "coordinates": "Does not place geometry or generate UV coordinates.",
- "parameters": [
- "Creates MeshLambertMaterial; no PBR metalness/roughness inputs."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Material portability depends on supported glTF properties and the selected exporter; renderer appearance is not a portability guarantee."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",
- "example": "const mat = lambertMaterial(0x2a4d14, { flatShading: true });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:rotationTrack",
- "name": "rotationTrack",
- "summary": "Absolute local XYZ Euler degrees converted to quaternion keys. Use an exact node name; Joint_ is a convention. LINEAR follows shortest quaternion arcs; STEP holds until the next key. CUBICSPLINE is one smooth curve through the keys; EASE_IN, EASE_OUT and EASE_IN_OUT ease every segment, so one key pair is a smooth swing. The last four export as glTF CUBICSPLINE and need two or more keys.",
- "family": "animation",
- "tags": [
- "animation",
- "keyframes"
- ],
- "aliases": [
- "rotate joint",
- "quaternion keyframes"
- ],
- "intents": [
- "animate a pivot rotation"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts",
- "src/animation-spline.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP' | 'CUBICSPLINE' | 'EASE_IN' | 'EASE_OUT' | 'EASE_IN_OUT')",
- "returns": "THREE.QuaternionKeyframeTrack",
- "units": "Times in seconds; Euler XYZ input rotations in degrees, converted to quaternion keyframes.",
- "axes": "Target-local XYZ axes.",
- "origin": "Does not infer the target rest pose.",
- "execution": "sync",
- "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",
- "coordinates": "Absolute parent-local TRS values replace target components during playback.",
- "parameters": [
- "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",
- "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",
- "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",
- "rotation contains XYZ degree triples. LINEAR, the cubic modes and the eases follow shortest quaternion arcs between keys, not Euler turns; use quarter-turn samples for a full revolution."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not automatically preserve target rest transforms; author their values explicitly."
- ],
- "semantics": [
- "Animation target strings bind to node names; names alone do not certify rig semantics.",
- "CUBICSPLINE passes one smooth curve through every key with PCHIP slopes: monotone between keys, never overshooting a key, at rest where the value holds or turns; two keys give a straight line.",
- "EASE_IN (s^2), EASE_OUT (2s - s^2) and EASE_IN_OUT (3s^2 - 2s^3) shape each segment between consecutive keys, s being the fraction of that segment; one key pair makes a smooth swing without sub-keys."
- ],
- "cost": "Linear in keyframe/track count.",
- "example": "rotationTrack('Joint_Lid', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [90, 0, 0] }], 'EASE_IN_OUT');"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:positionTrack",
- "name": "positionTrack",
- "summary": "Creates a translation track from absolute parent-local position keyframes and times in seconds.",
- "family": "animation",
- "tags": [
- "animation",
- "keyframes"
- ],
- "aliases": [
- "translation keyframes"
- ],
- "intents": [
- "animate a part position"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts",
- "src/animation-spline.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>, interp?: 'LINEAR' | 'STEP' | 'CUBICSPLINE' | 'EASE_IN' | 'EASE_OUT' | 'EASE_IN_OUT')",
- "returns": "THREE.VectorKeyframeTrack",
- "units": "Times in seconds; translation uses authored length units.",
- "axes": "Target-local XYZ axes.",
- "origin": "Does not infer the target rest pose.",
- "execution": "sync",
- "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",
- "coordinates": "Absolute parent-local TRS values replace target components during playback.",
- "parameters": [
- "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",
- "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",
- "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",
- "position contains absolute parent-local XYZ values, not value:."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not automatically preserve target rest transforms; author their values explicitly."
- ],
- "semantics": [
- "Animation target strings bind to node names; names alone do not certify rig semantics.",
- "CUBICSPLINE passes one smooth curve through every key with PCHIP slopes: monotone between keys, never overshooting a key, at rest where the value holds or turns; two keys give a straight line.",
- "EASE_IN (s^2), EASE_OUT (2s - s^2) and EASE_IN_OUT (3s^2 - 2s^3) shape each segment between consecutive keys, s being the fraction of that segment; one key pair makes a smooth swing without sub-keys."
- ],
- "cost": "Linear in keyframe/track count.",
- "example": "positionTrack('Joint_Body', [{ time: 0, position: [0, 0, 0] }, { time: 1, position: [0, 0.1, 0] }]);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:scaleTrack",
- "name": "scaleTrack",
- "summary": "Uniform or per-axis scale track.",
- "family": "animation",
- "tags": [
- "animation",
- "keyframes"
- ],
- "aliases": [
- "scaling keyframes"
- ],
- "intents": [
- "animate uniform or per-axis scale"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts",
- "src/animation-spline.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>, interp?: 'LINEAR' | 'STEP' | 'CUBICSPLINE' | 'EASE_IN' | 'EASE_OUT' | 'EASE_IN_OUT')",
- "returns": "THREE.VectorKeyframeTrack",
- "units": "Times in seconds; XYZ scale factors are dimensionless.",
- "axes": "Target-local XYZ axes.",
- "origin": "Does not infer the target rest pose.",
- "execution": "sync",
- "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",
- "coordinates": "Absolute parent-local TRS values replace target components during playback.",
- "parameters": [
- "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",
- "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",
- "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not automatically preserve target rest transforms; author their values explicitly."
- ],
- "semantics": [
- "Animation target strings bind to node names; names alone do not certify rig semantics.",
- "CUBICSPLINE passes one smooth curve through every key with PCHIP slopes: monotone between keys, never overshooting a key, at rest where the value holds or turns; two keys give a straight line.",
- "EASE_IN (s^2), EASE_OUT (2s - s^2) and EASE_IN_OUT (3s^2 - 2s^3) shape each segment between consecutive keys, s being the fraction of that segment; one key pair makes a smooth swing without sub-keys."
- ],
- "cost": "Linear in keyframe/track count.",
- "example": "scaleTrack('Joint_Chest', [{ time: 0, scale: [1, 1, 1] }, { time: 1, scale: [1.1, 1.1, 1.1] }]);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:createClip",
- "name": "createClip",
- "summary": "Validates supported position/quaternion/scale tracks and collects them into a named clip. Duration is seconds (-1 derives from keys); explicit duration must include every key. loop: true declares a cycle, false a one-shot; exported as the glTF animation extra kilnLoopIntent and reported by animation review. Returned from animate().",
- "family": "animation",
- "tags": [
- "animation",
- "keyframes"
- ],
- "aliases": [
- "animation clip"
- ],
- "intents": [
- "collect tracks into a named motion"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts",
- "src/animation-spline.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "createClip(name: string, duration: number, tracks: KeyframeTrack[], options?: { loop?: boolean })",
- "returns": "THREE.AnimationClip",
- "units": "Keyframe times and durations are seconds; transform values are absolute, not additive offsets.",
- "axes": "Defined by the supplied tracks.",
- "origin": "Does not infer the target rest pose.",
- "execution": "sync",
- "ownership": "Creates an AnimationClip sharing supplied track objects. Later caller mutation still needs validation. Export adds trailing holds on copied tracks only.",
- "coordinates": "Absolute parent-local TRS values replace target components during playback.",
- "parameters": [
- "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",
- "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",
- "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",
- "Only position/scale vector and quaternion tracks, unique target/channel pairs, valid strides and unit quaternion samples (squared-length tolerance 1e-4). No silent repairs.",
- "A cubic-spline track holds [in-tangent, value, out-tangent] per key, as a glTF CUBICSPLINE sampler does, and needs at least two keys; only its key values must be unit quaternions.",
- "Duration -1 derives from keys; explicit nonnegative seconds must include every key. Zero-duration time-zero static clips are valid. Longer duration is preserved by a held final native sample.",
- "options.loop: true declares a cycle and false a one-shot; omitted is unspecified. Exported as animations[].extras.kilnLoopIntent (loop | once); three.js GLTFLoader exposes it as clip.userData.kilnLoopIntent. Animation review reports it in loopClosure.loopIntent and warns when a declared loop does not close."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not automatically preserve target rest transforms; author their values explicitly."
- ],
- "semantics": [
- "Animation target strings bind to node names; names alone do not certify rig semantics."
- ],
- "cost": "Linear in keyframe/track count.",
- "example": "return [createClip('Open', 1, [rotationTrack('Joint_Lid', [...])], { loop: false })];"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:idleBreathing",
- "name": "idleBreathing",
- "summary": "Gentle parent-local Y bob around options.basePosition, default [0,0,0]. Give the authored base explicitly or animate a separate zero-origin pivot.",
- "family": "animation",
- "tags": [
- "animation",
- "keyframes"
- ],
- "aliases": [
- "bob",
- "idle motion"
- ],
- "intents": [
- "make a simple vertical motion loop"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts",
- "src/animation-spline.ts"
- ],
- "limitations": [
- "Target name cannot infer its rest pose. Supply basePosition explicitly or use a separate zero-origin animation pivot."
- ],
- "kind": "operation",
- "contract": {
- "signature": "idleBreathing(bodyJoint: string, duration?: 2, amount?: 0.02, options?: { basePosition?: [x, y, z] })",
- "returns": "THREE.AnimationClip",
- "units": "Keyframe times and durations are seconds; transform values are absolute, not additive offsets.",
- "axes": "Translation along parent-local Y.",
- "origin": "Does not infer the target rest pose.",
- "execution": "sync",
- "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",
- "coordinates": "Absolute parent-local TRS values replace target components during playback.",
- "parameters": [
- "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",
- "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",
- "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",
- "Positive duration in seconds; finite amount/height in authored length units. options.basePosition is a finite XYZ triple, default [0,0,0]."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Writes absolute positions around the supplied basePosition while leaving rotation/scale untouched. Snapshot numeric base components without mutating the caller array."
- ],
- "semantics": [
- "Animation target strings bind to node names; names alone do not certify rig semantics."
- ],
- "cost": "One three-keyframe position track.",
- "example": "return [idleBreathing('Joint_Body', 2, 0.02, { basePosition: [0, 1.2, 0] })];"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:bobbingAnimation",
- "name": "bobbingAnimation",
- "summary": "Parent-local Y motion loop around options.basePosition, default [0,0,0]. A target name alone cannot infer its rest translation.",
- "family": "animation",
- "tags": [
- "animation",
- "keyframes"
- ],
- "aliases": [
- "bob",
- "idle motion"
- ],
- "intents": [
- "make a simple vertical motion loop"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts",
- "src/animation-spline.ts"
- ],
- "limitations": [
- "Target name cannot infer its rest pose. Supply basePosition explicitly or use a separate zero-origin animation pivot."
- ],
- "kind": "operation",
- "contract": {
- "signature": "bobbingAnimation(rootName: string, duration?: 2, height?: 0.1, options?: { basePosition?: [x, y, z] })",
- "returns": "THREE.AnimationClip",
- "units": "Keyframe times and durations are seconds; transform values are absolute, not additive offsets.",
- "axes": "Translation along parent-local Y.",
- "origin": "Does not infer the target rest pose.",
- "execution": "sync",
- "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",
- "coordinates": "Absolute parent-local TRS values replace target components during playback.",
- "parameters": [
- "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",
- "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",
- "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",
- "Positive duration in seconds; finite amount/height in authored length units. options.basePosition is a finite XYZ triple, default [0,0,0]."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Writes absolute positions around the supplied basePosition while leaving rotation/scale untouched. Snapshot numeric base components without mutating the caller array."
- ],
- "semantics": [
- "Animation target strings bind to node names; names alone do not certify rig semantics."
- ],
- "cost": "One three-keyframe position track.",
- "example": "return [bobbingAnimation('Joint_Root', 1.5, 0.08, { basePosition: [0, 0.5, 0] })];"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:spinAnimation",
- "name": "spinAnimation",
- "summary": "360° rotation over `duration` around `axis`.",
- "family": "animation",
- "tags": [
- "animation",
- "keyframes"
- ],
- "aliases": [
- "continuous rotation",
- "spin loop"
- ],
- "intents": [
- "rotate a named pivot through a complete turn"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts",
- "src/animation-spline.ts"
- ],
- "limitations": [
- "Place authored orientation on a parent pivot when using this identity-based preset."
- ],
- "kind": "operation",
- "contract": {
- "signature": "spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')",
- "returns": "THREE.AnimationClip",
- "units": "Keyframe times and durations are seconds; transform values are absolute, not additive offsets.",
- "axes": "Selected local X/Y/Z rotation axis, default Y.",
- "origin": "Does not infer the target rest pose.",
- "execution": "sync",
- "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",
- "coordinates": "Absolute parent-local TRS values replace target components during playback.",
- "parameters": [
- "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",
- "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",
- "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Writes absolute rotations from identity; does not compose an authored rest rotation."
- ],
- "semantics": [
- "Animation target strings bind to node names; names alone do not certify rig semantics."
- ],
- "cost": "One five-keyframe quaternion track using quarter turns.",
- "example": "return [spinAnimation('Joint_Rotor', 0.5, 'y')];"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:createInstance",
- "name": "createInstance",
- "summary": "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",
- "family": "instancing",
- "tags": [
- "instancing",
- "reuse",
- "mesh instances"
- ],
- "aliases": [
- "reuse mesh",
- "duplicate mesh node"
- ],
- "intents": [
- "place another copy of a single mesh"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/ops.ts",
- "src/primitives.ts"
- ],
- "limitations": [
- "Mesh reuse is not hierarchy-preserving assembly replication or hardware instancing."
- ],
- "kind": "operation",
- "contract": {
- "signature": "createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })",
- "returns": "THREE.Object3D",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Three.js local XYZ; +Y is the normal up convention.",
- "origin": "Position is relative to the selected parent.",
- "execution": "sync",
- "ownership": "Creates new mesh nodes sharing source geometry/material; not deep copies.",
- "coordinates": "Source local transform values and array offsets are interpreted without converting between different parent frames.",
- "parameters": [
- "source is a Mesh or has a direct Mesh child; absence throws.",
- "Position/rotation/scale are explicit new transforms; rotation is degrees."
- ],
- "topology": [
- "Source mesh geometry is shared unchanged."
- ],
- "preservation": [
- "Only the source mesh or first direct Mesh child is used; nested assemblies, child transforms and semantic hierarchy are not reproduced."
- ],
- "semantics": [
- "New mesh names do not preserve full source semantic identity."
- ],
- "cost": "One new mesh; shared geometry/material buffers.",
- "example": "const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });\ncreateInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });\ncreateInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });\ncreateInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:boolUnion",
- "name": "boolUnion",
- "summary": "Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.",
- "family": "csg",
- "tags": [
- "csg",
- "boolean",
- "solid",
- "async"
- ],
- "aliases": [
- "union",
- "fuse solids"
- ],
- "intents": [
- "combine overlapping volumes",
- "join overlapping solids",
- "boolean union"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- },
- {
- "id": "operation:autoUnwrap",
- "relation": "companion"
- }
- ],
- "references": [
- "src/solids.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
- "returns": "Promise<THREE.Mesh>",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Uses one translated and uniformly normalized computation frame for all operands; output axes remain world-aligned.",
- "origin": "The unparented result mesh.position is the first contributing mesh world origin; geometry positions are local to that origin. Preserve the returned mesh transform.",
- "execution": "async",
- "ownership": "Creates output mesh/geometry; does not mutate operand geometry. Material sharing and generated groups depend on preservation options.",
- "coordinates": "World operand relationships are preserved, not their hierarchy. Read world bounds or apply the returned matrix when inspecting positions; geometry alone no longer contains the world translation.",
- "parameters": [
- "Use closed, valid solid operands; Manifold WASM is loaded lazily.",
- "Use static triangle meshes. Bake instances, skin poses and active morphs before CSG; these operands are rejected rather than read as base geometry.",
- "smooth affects normals; preserveAttributes requests UV/material provenance where supported.",
- "Keep shape detail in local coordinates; a common frame cannot recover precision already lost in input buffers/transforms or resolve arbitrarily tiny features across a vast combined extent.",
- "Requires at least two operands."
- ],
- "topology": [
- "Uses Manifold solid operations; malformed/degenerate operands can fail. Empty boolean results are rejected with diagnostics."
- ],
- "preservation": [
- "Default path does not promise UV retention; preservation mode carries supported UV/material groups and reports losses.",
- "Cut-face UV0/materials come from the cutter. Colors, secondary UVs, tangents, skin/custom attributes and inactive morph targets are dropped with diagnostics; normals are regenerated.",
- "Source attribute/geometry diagnostics are retained without sharing mutable records. Arbitrary user metadata and animation are not carried onto the new topology."
- ],
- "semantics": [
- "Output is a new mesh, not the source articulated assembly; provenance is operation-specific."
- ],
- "cost": "WASM work depends on operand topology/intersections; no universal input-size or time bound is claimed.",
- "example": "const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);\nconst turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);\nturret.position.y = 0.5;\nconst hull = await boolUnion('Hull', body, turret);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:boolDiff",
- "name": "boolDiff",
- "summary": "Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.",
- "family": "csg",
- "tags": [
- "csg",
- "boolean",
- "solid",
- "async"
- ],
- "aliases": [
- "subtract",
- "carve",
- "cut holes"
- ],
- "intents": [
- "remove cutter volume from a solid",
- "subtract solids",
- "cut out a shape",
- "boolean difference"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- },
- {
- "id": "operation:autoUnwrap",
- "relation": "companion"
- }
- ],
- "references": [
- "src/solids.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
- "returns": "Promise<THREE.Mesh>",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Uses one translated and uniformly normalized computation frame for all operands; output axes remain world-aligned.",
- "origin": "The unparented result mesh.position is the first contributing mesh world origin; geometry positions are local to that origin. Preserve the returned mesh transform.",
- "execution": "async",
- "ownership": "Creates output mesh/geometry; does not mutate operand geometry. Material sharing and generated groups depend on preservation options.",
- "coordinates": "World operand relationships are preserved, not their hierarchy. Read world bounds or apply the returned matrix when inspecting positions; geometry alone no longer contains the world translation.",
- "parameters": [
- "Use closed, valid solid operands; Manifold WASM is loaded lazily.",
- "Use static triangle meshes. Bake instances, skin poses and active morphs before CSG; these operands are rejected rather than read as base geometry.",
- "smooth affects normals; preserveAttributes requests UV/material provenance where supported.",
- "Keep shape detail in local coordinates; a common frame cannot recover precision already lost in input buffers/transforms or resolve arbitrarily tiny features across a vast combined extent.",
- "Requires body and at least one cutter."
- ],
- "topology": [
- "Uses Manifold solid operations; malformed/degenerate operands can fail. Empty boolean results are rejected with diagnostics."
- ],
- "preservation": [
- "Default path does not promise UV retention; preservation mode carries supported UV/material groups and reports losses.",
- "Cut-face UV0/materials come from the cutter. Colors, secondary UVs, tangents, skin/custom attributes and inactive morph targets are dropped with diagnostics; normals are regenerated.",
- "Source attribute/geometry diagnostics are retained without sharing mutable records. Arbitrary user metadata and animation are not carried onto the new topology."
- ],
- "semantics": [
- "Output is a new mesh, not the source articulated assembly; provenance is operation-specific."
- ],
- "cost": "WASM work depends on operand topology/intersections; no universal input-size or time bound is claimed.",
- "example": "const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);\nconst teeth = [...]; // 8 radially-arrayed box meshes\nconst gear = await boolDiff('Gear', body, ...teeth); // hard-edged"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:roundedBoxGeo",
- "name": "roundedBoxGeo",
- "summary": "A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.",
- "family": "csg",
- "tags": [
- "csg",
- "profile",
- "solid",
- "async"
- ],
- "aliases": [
- "rounded box",
- "chamfered block"
- ],
- "intents": [
- "make a block with softened edges"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/profile.ts"
- ],
- "limitations": [
- "This is a specific primitive, not a generic selected-edge bevel operation."
- ],
- "kind": "operation",
- "contract": {
- "signature": "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",
- "returns": "Promise<THREE.BufferGeometry>",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. angle/twist and pitch parameters use degrees.",
- "axes": "Width X, height Y, depth Z.",
- "origin": "Centered at local origin; requested outer extents are maintained.",
- "execution": "async",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Finite positive dimensions and radius; radius must be less than half the smallest dimension.",
- "style round or chamfer; segments affect rounded construction.",
- "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await."
- ],
- "topology": [
- "Manifold-backed solid generation from valid profiles; not a guarantee that any arbitrary input describes the intended solid."
- ],
- "preservation": [
- "New geometry/normals/bounds; does not carry authored UVs from an input mesh."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "WASM complexity depends on profile vertices, segments and divisions; no general allocation bound is claimed.",
- "example": "const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);\ncreatePart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:extrudeProfile",
- "name": "extrudeProfile",
- "summary": "Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.",
- "family": "csg",
- "tags": [
- "csg",
- "profile",
- "solid",
- "async"
- ],
- "aliases": [
- "extrude outline",
- "profile extrusion"
- ],
- "intents": [
- "make a solid from a planar cross-section with optional holes"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:circleProfile",
- "relation": "companion"
- },
- {
- "id": "operation:sweepProfile",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/profile.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: 0, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",
- "returns": "Promise<THREE.BufferGeometry>",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. angle/twist and pitch parameters use degrees.",
- "axes": "For profile (u,v) and extrusion depth coordinate d, output XYZ is axis x: (d, v, -u); axis y: (u, d, -v); axis z: (u, v, d). Default axis is y. For a desired XZ footprint on axis y, pass profile [X,-Z].",
- "origin": "center defaults true; center false starts depth at the selected-axis origin.",
- "execution": "async",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Finite closed outline, optional finite hole outlines, positive depth.",
- "Twist is degrees; taper is dimensionless; divisions is a whole number >= 0 of intermediate rings, default 0 (16 when twisting).",
- "Bevel uses profile units. If its inward offset empties the section, execution rejects with repair advice: reduce bevel below half the narrowest width, disable it, or widen the section.",
- "Profile (u,v) maps to XYZ as axis x: (d,v,-u), axis y: (u,d,-v), axis z: (u,v,d), where d is extrusion depth. For a desired XZ footprint on axis y, pass [X,-Z]; positive profile v projects toward -Z. The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. divisions is the whole number (>= 0) of intermediate rings between the caps: default 0, or 16 when twisting; a straight or tapered sweep needs none. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build()."
- ],
- "topology": [
- "Manifold-backed solid generation from valid profiles; not a guarantee that any arbitrary input describes the intended solid."
- ],
- "preservation": [
- "New geometry/normals/bounds; does not carry authored UVs from an input mesh."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "WASM complexity depends on profile vertices, segments and divisions; no general allocation bound is claimed.",
- "example": "// L-bracket, inner AND outer corners filleted\nconst outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];\nconst geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });\ncreatePart('Bracket', geo, steel, { parent: root });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:revolveProfile",
- "name": "revolveProfile",
- "summary": "Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.",
- "family": "csg",
- "tags": [
- "csg",
- "profile",
- "solid",
- "async"
- ],
- "aliases": [
- "solid revolution",
- "turned solid"
- ],
- "intents": [
- "turn a closed section into a solid vessel or knob"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:revolveGeo",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/profile.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",
- "returns": "Promise<THREE.BufferGeometry>",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. angle/twist and pitch parameters use degrees.",
- "axes": "Profile x is radial distance, y is distance along selected X/Y/Z axis (default Y). Around Y, the sweep starts at +X and proceeds toward -Z.",
- "origin": "Rotation axis passes through local origin.",
- "execution": "async",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Closed finite profile; only nonnegative radial side is used.",
- "angle in (0,360] degrees; segments and bevel options control tessellation.",
- "Bevel uses profile units. If its inward offset empties the section, execution rejects with repair advice: reduce bevel below half the narrowest width, disable it, or widen the section.",
- "Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build()."
- ],
- "topology": [
- "Manifold-backed solid generation from valid profiles; not a guarantee that any arbitrary input describes the intended solid."
- ],
- "preservation": [
- "New geometry/normals/bounds; does not carry authored UVs from an input mesh."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "WASM complexity depends on profile vertices, segments and divisions; no general allocation bound is claimed.",
- "example": "// capsule tank with a rounded rim, then carve a port into it\nconst profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];\nconst body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });\nconst tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:circleProfile",
- "name": "circleProfile",
- "summary": "Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.",
- "family": "csg",
- "tags": [
- "csg",
- "profile",
- "circle"
- ],
- "aliases": [
- "circular outline"
- ],
- "intents": [
- "create a reusable circular profile"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/profile.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "circleProfile(radius: number, segments?: 24, center?: [number, number])",
- "returns": "[number, number][]",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "2D points in caller-selected profile plane.",
- "origin": "Optional 2D center; default origin.",
- "execution": "sync",
- "ownership": "Returns a new point array.",
- "coordinates": "Profile-local 2D coordinates.",
- "parameters": [
- "Finite positive radius; segment count must be an integer at least 3."
- ],
- "topology": [
- "Closed outline represented without repeating the endpoint; no 3D mesh."
- ],
- "preservation": [
- "Generates profile points only."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in segments, default 24.",
- "example": "const washer = await extrudeProfile(circleProfile(1), {\n depth: 0.1,\n holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],\n});"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:boolIntersect",
- "name": "boolIntersect",
- "summary": "Keeps only the volume where both operands overlap. Default flat shading.",
- "family": "csg",
- "tags": [
- "csg",
- "boolean",
- "solid",
- "async"
- ],
- "aliases": [
- "intersection",
- "overlap volume"
- ],
- "intents": [
- "retain only the shared volume",
- "intersection of solids",
- "overlapping volume"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- },
- {
- "id": "operation:autoUnwrap",
- "relation": "companion"
- }
- ],
- "references": [
- "src/solids.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false, preserveAttributes?: boolean })",
- "returns": "Promise<THREE.Mesh>",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Uses one translated and uniformly normalized computation frame for all operands; output axes remain world-aligned.",
- "origin": "The unparented result mesh.position is the first contributing mesh world origin; geometry positions are local to that origin. Preserve the returned mesh transform.",
- "execution": "async",
- "ownership": "Creates output mesh/geometry; does not mutate operand geometry. Material sharing and generated groups depend on preservation options.",
- "coordinates": "World operand relationships are preserved, not their hierarchy. Read world bounds or apply the returned matrix when inspecting positions; geometry alone no longer contains the world translation.",
- "parameters": [
- "Use closed, valid solid operands; Manifold WASM is loaded lazily.",
- "Use static triangle meshes. Bake instances, skin poses and active morphs before CSG; these operands are rejected rather than read as base geometry.",
- "smooth affects normals; preserveAttributes requests UV/material provenance where supported.",
- "Keep shape detail in local coordinates; a common frame cannot recover precision already lost in input buffers/transforms or resolve arbitrarily tiny features across a vast combined extent.",
- "Two operands."
- ],
- "topology": [
- "Uses Manifold solid operations; malformed/degenerate operands can fail. Empty boolean results are rejected with diagnostics."
- ],
- "preservation": [
- "Default path does not promise UV retention; preservation mode carries supported UV/material groups and reports losses.",
- "Cut-face UV0/materials come from the cutter. Colors, secondary UVs, tangents, skin/custom attributes and inactive morph targets are dropped with diagnostics; normals are regenerated.",
- "Source attribute/geometry diagnostics are retained without sharing mutable records. Arbitrary user metadata and animation are not carried onto the new topology."
- ],
- "semantics": [
- "Output is a new mesh, not the source articulated assembly; provenance is operation-specific."
- ],
- "cost": "WASM work depends on operand topology/intersections; no universal input-size or time bound is claimed.",
- "example": "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:hull",
- "name": "hull",
- "summary": "Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.",
- "family": "csg",
- "tags": [
- "csg",
- "boolean",
- "solid",
- "async"
- ],
- "aliases": [
- "convex hull",
- "convex envelope"
- ],
- "intents": [
- "enclose geometry with a convex shape"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:geometryDiagnostics",
- "relation": "companion"
- },
- {
- "id": "operation:autoUnwrap",
- "relation": "companion"
- }
- ],
- "references": [
- "src/solids.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true, preserveAttributes?: boolean })",
- "returns": "Promise<THREE.Mesh>",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Uses one translated and uniformly normalized computation frame for all operands; output axes remain world-aligned.",
- "origin": "The unparented result mesh.position is the first contributing mesh world origin; geometry positions are local to that origin. Preserve the returned mesh transform.",
- "execution": "async",
- "ownership": "Creates output mesh/geometry; does not mutate operand geometry. Material sharing and generated groups depend on preservation options.",
- "coordinates": "World operand relationships are preserved, not their hierarchy. Read world bounds or apply the returned matrix when inspecting positions; geometry alone no longer contains the world translation.",
- "parameters": [
- "At least one part; convex enclosure uses its input points."
- ],
- "topology": [
- "Convex solid envelope; removes concavities and does not preserve internal cavities."
- ],
- "preservation": [
- "Generated hull faces have unknown source UV/material provenance; do not infer original texture mapping."
- ],
- "semantics": [
- "Output is a new mesh, not the source articulated assembly; provenance is operation-specific."
- ],
- "cost": "WASM work depends on operand topology/intersections; no universal input-size or time bound is claimed.",
- "example": "const rockChunks = [...]; // scattered box meshes\nconst rock = await hull('Rock', ...rockChunks);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:arrayLinear",
- "name": "arrayLinear",
- "summary": "`count` is the TOTAL, source included: the source stays where it is as copy 0 and the call returns count-1 new instances, so count 10 gives 10 posts, not 11. Copies share geometry + material via createInstance, and carry the source rotation and scale.",
- "family": "arrays",
- "tags": [
- "arrays",
- "reuse",
- "mesh instances"
- ],
- "aliases": [
- "linear repeat",
- "row of parts"
- ],
- "intents": [
- "repeat a mesh at regular offsets",
- "linear repetition",
- "repeat along a line",
- "straight row",
- "regular spacing",
- "bench or fence slats"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/ops.ts",
- "src/primitives.ts"
- ],
- "limitations": [
- "Mesh reuse is not hierarchy-preserving assembly replication or hardware instancing."
- ],
- "kind": "operation",
- "contract": {
- "signature": "arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)",
- "returns": "THREE.Object3D[]",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Three.js local XYZ; +Y is the normal up convention.",
- "origin": "Position is relative to the selected parent.",
- "execution": "sync",
- "ownership": "Creates new mesh nodes sharing source geometry/material; not deep copies.",
- "coordinates": "Source local transform values and array offsets are interpreted without converting between different parent frames.",
- "parameters": [
- "count is a safe integer from 1 to 10,000 including the original source; returns count-1 new meshes.",
- "offset and source transforms must be finite; resulting positions are checked before any attachment. Coordinates are source-parent local."
- ],
- "topology": [
- "Source mesh geometry is shared unchanged."
- ],
- "preservation": [
- "Only the source mesh or first direct Mesh child is used; nested assemblies, child transforms and semantic hierarchy are not reproduced.",
- "Copies preserve source rotation and scale."
- ],
- "semantics": [
- "New mesh names do not preserve full source semantic identity."
- ],
- "cost": "count-1 new mesh nodes; draw calls are not automatically batched.",
- "example": "const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });\narrayLinear('Post', post, 10, [0.5, 0, 0], root);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:arrayRadial",
- "name": "arrayRadial",
- "summary": "`count` is the TOTAL, source included: the source stays at its angle as copy 0 and the call returns count-1 new mesh instances. Copies preserve source scale. Default outward rotation follows the orbit; relative orientation composes the orbit with the source rotation. Copies orbit the parent's origin unless you pass center. This is mesh reuse, not hierarchy-preserving assembly replication.",
- "family": "arrays",
- "tags": [
- "arrays",
- "reuse",
- "mesh instances"
- ],
- "aliases": [
- "circular repeat",
- "radial pattern"
- ],
- "intents": [
- "repeat a mesh around a center",
- "radial repetition",
- "repeat around a circle",
- "circular pattern",
- "ring of supports",
- "arena seating"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/ops.ts",
- "src/primitives.ts"
- ],
- "limitations": [
- "Mesh reuse is not hierarchy-preserving assembly replication or hardware instancing."
- ],
- "kind": "operation",
- "contract": {
- "signature": "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?, center?: [x,y,z], opts?: { orientation?: 'outward'|'relative' })",
- "returns": "THREE.Object3D[]",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Orbit around selected local X/Y/Z axis, default Y.",
- "origin": "Position is relative to the selected parent.",
- "execution": "sync",
- "ownership": "Creates new mesh nodes sharing source geometry/material; not deep copies.",
- "coordinates": "Source local transform values and array offsets are interpreted without converting between different parent frames.",
- "parameters": [
- "count is a safe integer from 1 to 10,000 including source; finite center defaults to parent origin.",
- "axis must be x/y/z; orientation outward follows orbit and relative composes with source rotation. Source transforms and all resulting positions must be finite."
- ],
- "topology": [
- "Source mesh geometry is shared unchanged."
- ],
- "preservation": [
- "Only the source mesh or first direct Mesh child is used; nested assemblies, child transforms and semantic hierarchy are not reproduced.",
- "Preserves source scale; rotation follows the explicit orientation mode."
- ],
- "semantics": [
- "New mesh names do not preserve full source semantic identity."
- ],
- "cost": "count-1 mesh nodes; no automatic draw-call batching.",
- "example": "const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });\narrayRadial('Bolt', bolt, 8, 'y', root);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:mirror",
- "name": "mirror",
- "summary": "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
- "family": "arrays",
- "tags": [
- "arrays",
- "reuse",
- "mesh instances"
- ],
- "aliases": [
- "reflect part"
- ],
- "intents": [
- "place a reflected counterpart",
- "reflection across a plane",
- "opposite side",
- "symmetric counterpart"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/ops.ts",
- "src/primitives.ts"
- ],
- "limitations": [
- "Mesh reuse is not hierarchy-preserving assembly replication or hardware instancing."
- ],
- "kind": "operation",
- "contract": {
- "signature": "mirror(name, source, axis: 'x'|'y'|'z', parent?)",
- "returns": "THREE.Object3D",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",
- "axes": "Reflects across the origin plane normal to X/Y/Z.",
- "origin": "Position is relative to the selected parent.",
- "execution": "sync",
- "ownership": "Creates new mesh nodes sharing source geometry/material; not deep copies.",
- "coordinates": "Source local transform values and array offsets are interpreted without converting between different parent frames.",
- "parameters": [
- "A source mesh/direct mesh child and explicit reflection axis.",
- "Requires a finite nonsingular local transform representable as TRS; local shear is rejected."
- ],
- "topology": [
- "Source mesh geometry is shared unchanged."
- ],
- "preservation": [
- "Only the source mesh or first direct Mesh child is used; nested assemblies, child transforms and semantic hierarchy are not reproduced.",
- "Reflection is represented by transforms; viewers/exporters must respect negative determinant winding."
- ],
- "semantics": [
- "New mesh names do not preserve full source semantic identity."
- ],
- "cost": "One new mesh sharing geometry/material.",
- "example": "mirror('WingR', wingL, 'x', root);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:subdivide",
- "name": "subdivide",
- "summary": "Loop subdivision returns new geometry; each iteration roughly quadruples triangles and smooths the surface. Use preserveUV:true for textured meshes. Legacy position-only welding discards UVs and reports that loss. This smooths shapes, not selected-edge beveling.",
- "family": "mesh-ops",
- "tags": [
- "mesh-ops",
- "mesh processing",
- "subdivision"
- ],
- "aliases": [
- "smooth subdivision"
- ],
- "intents": [
- "add segments and smooth a coarse mesh"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/ops.ts"
- ],
- "limitations": [
- "Conservative per-operation budgets include presplit growth. They are not a peak-memory guarantee; host evaluation limits still apply."
- ],
- "kind": "operation",
- "contract": {
- "signature": "subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { preserveUV?: boolean, split?: boolean, uvSmooth?: boolean, preserveEdges?: boolean, flatOnly?: boolean, weld?: boolean })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Preserves source axes; smoothing moves vertices.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "iterations is an integer 0..10, default 1; options determine welding, UV preservation and edge behavior.",
- "preserveUV must be explicit for the textured preservation path; subdivide before skin binding because joint indices cannot be interpolated safely.",
- "Continuous vertex attributes have 1..4 components; normalized storage is decoded to owned Float32 and all four RGBA channels are interpolated. Morph attributes currently require three components."
- ],
- "topology": [
- "Loop subdivision changes topology and shape; not selected-edge beveling or general remeshing."
- ],
- "preservation": [
- "preserveUV path retains corner UVs, material groups and supported morph attributes. Position-only welding reports removed UVs, other attributes, groups and morphs; tangents are invalidated.",
- "All paths normalize working coordinates before position welding and upstream adjacency hashing, then restore original units; features near the relative weld/grid resolution need review.",
- "Normals/bounds are updated and unsupported provenance is invalidated."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Preflight upper bound is input triangles × 4^iterations × 4 when split is enabled (default). Rejects above 1,000,000 triangles or 128 MiB of output attributes, including morph channels, before cloning/welding. No silent truncation.",
- "example": "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:mergeVertices",
- "name": "mergeVertices",
- "summary": "Returns indexed geometry. Default welding preserves attribute seams, so a textured cube retains separate face corners. positionOnly:true welds coincident positions and discards other attributes; use it explicitly when changing topology and regenerate shading/UVs afterward.",
- "family": "mesh-ops",
- "tags": [
- "mesh-ops",
- "mesh processing",
- "weld"
- ],
- "aliases": [
- "weld vertices"
- ],
- "intents": [
- "merge duplicate vertices deliberately"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/ops.ts"
- ],
- "limitations": [
- "Do not use position-only welding as an invisible textured-mesh optimization."
- ],
- "kind": "operation",
- "contract": {
- "signature": "mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?: boolean } | number)",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Preserves source axes.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "sync",
- "ownership": "Normally returns new indexed geometry; positionOnly mode with no position attribute currently returns the input unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "tolerance defaults 1e-4; default attribute-aware weld preserves seams.",
- "positionOnly explicitly discards non-position attributes."
- ],
- "topology": [
- "Merges matching vertices; does not prove manifoldness or repair self-intersections."
- ],
- "preservation": [
- "Default weld retains differing attribute seams; positionOnly loses UVs/normals/other attributes and requires regeneration."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Depends on vertex count and hashed attribute width.",
- "example": "const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });\nconst rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:curveToMesh",
- "name": "curveToMesh",
- "summary": "Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a circle profile. Use for pipes, cables, tubular frames.",
- "family": "curves",
- "tags": [
- "curves",
- "curve",
- "surface",
- "path"
- ],
- "aliases": [
- "tube along spline",
- "cable"
- ],
- "intents": [
- "make a round tube along a curved path",
- "curved tube",
- "tube following a curve",
- "hose conduit cable"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/ops.ts"
- ],
- "limitations": [
- "Open path ends are uncapped; input stations can overshoot under spline interpolation."
- ],
- "kind": "operation",
- "contract": {
- "signature": "curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Path points use XYZ; frames are chosen by the curve implementation.",
- "origin": "Defined by path/profile coordinates.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Circular tube follows Catmull-Rom interpolation of points; closed controls the path.",
- "radius is required: positive, finite and representable in Float32, in asset units. Undefined dimensions fail instead of selecting a default radius.",
- "Default tubularSegments 32, radialSegments 8."
- ],
- "topology": [
- "Generates a surface; endpoint caps and a watertight solid are not implicit."
- ],
- "preservation": [
- "Generates normals and UVs; eager bounding volumes are not guaranteed."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Tessellation grows with longitudinal × radial segments; no broad resource cap is claimed.",
- "example": "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:pipeAlongPath",
- "name": "pipeAlongPath",
- "summary": "Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.",
- "family": "curves",
- "tags": [
- "curves",
- "curve",
- "surface",
- "path"
- ],
- "aliases": [
- "pipe",
- "rounded path"
- ],
- "intents": [
- "make a tube with softened path corners",
- "tube along a path",
- "curved pipe",
- "hose conduit cable"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:sweepProfile",
- "relation": "alternative"
- },
- {
- "id": "operation:curveToMesh",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/ops.ts"
- ],
- "limitations": [
- "Tube ends remain open; this does not construct a hollow pipe wall."
- ],
- "kind": "operation",
- "contract": {
- "signature": "pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Path points use XYZ; frames are chosen by the curve implementation.",
- "origin": "Defined by path/profile coordinates.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "bendRadius inserts interpolated corner waypoints; it is not an exact circular fillet radius.",
- "radius is required: positive, finite and representable in Float32, in asset units. Undefined dimensions fail instead of selecting a default radius.",
- "Other tube options follow the signature."
- ],
- "topology": [
- "Generates a surface; endpoint caps and a watertight solid are not implicit."
- ],
- "preservation": [
- "Generates normals and UVs; eager bounding volumes are not guaranteed."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Tessellation grows with longitudinal × radial segments; no broad resource cap is claimed.",
- "example": "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:lathe",
- "name": "lathe",
- "summary": "Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.",
- "family": "curves",
- "tags": [
- "curves",
- "curve",
- "surface",
- "path"
- ],
- "aliases": [
- "lathe surface"
- ],
- "intents": [
- "turn a radial profile into a surface"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:revolveProfile",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/ops.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "lathe(profile: [x,y][], segments?: 12)",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "Profile x is radius, y is height; spins around Y.",
- "origin": "Defined by path/profile coordinates.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Open or closed profile point list; segments default 12."
- ],
- "topology": [
- "Generates a surface; endpoint caps and a watertight solid are not implicit."
- ],
- "preservation": [
- "Generates normals and UVs; eager bounding volumes are not guaranteed."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in profile points × revolution segments.",
- "example": "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:revolveGeo",
- "name": "revolveGeo",
- "summary": "Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.",
- "family": "curves",
- "tags": [
- "curves",
- "curve",
- "surface",
- "path"
- ],
- "aliases": [
- "surface revolution",
- "partial lathe"
- ],
- "intents": [
- "revolve a surface about an arbitrary axis"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:revolveProfile",
- "relation": "alternative"
- }
- ],
- "references": [
- "src/ops.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })",
- "returns": "THREE.BufferGeometry",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. sweep angle is radians (default 2π), unlike revolveProfile degrees.",
- "axes": "Profile x is radius, y is axial distance; arbitrary nonzero axis vector. Before axis reorientation, the Y sweep starts at +Z and proceeds toward +X.",
- "origin": "Defined by path/profile coordinates.",
- "execution": "sync",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Profile points and revolution segments; explicit angular sweep in radians."
- ],
- "topology": [
- "Generates a surface; endpoint caps and a watertight solid are not implicit."
- ],
- "preservation": [
- "Generates normals and UVs; eager bounding volumes are not guaranteed."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in profile points × revolution segments.",
- "example": "// Half-dome (180° sweep around +Y):\nconst quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });\nconst dome = revolveGeo(quarter, { angle: Math.PI });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:bezierCurve",
- "name": "bezierCurve",
- "summary": "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",
- "family": "curves",
- "tags": [
- "curves",
- "curve",
- "surface",
- "path"
- ],
- "aliases": [
- "bezier samples",
- "quadratic curve",
- "cubic curve"
- ],
- "intents": [
- "sample a controlled curved path",
- "quadratic cubic bezier control points",
- "sample curved path"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/ops.ts"
- ],
- "limitations": [
- "Passing samples to curveToMesh applies Catmull-Rom interpolation again."
- ],
- "kind": "operation",
- "contract": {
- "signature": "bezierCurve(controlPoints: [x,y,z][], samples?: 32)",
- "returns": "[x,y,z][]",
- "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",
- "axes": "XYZ control points.",
- "origin": "Defined by supplied control points.",
- "execution": "sync",
- "ownership": "Returns a new array of sampled points.",
- "coordinates": "Control-point coordinate space; no parent transforms.",
- "parameters": [
- "Exactly 3 quadratic or 4 cubic control points; sample count controls point density."
- ],
- "topology": [
- "Point sequence only; no geometry or caps."
- ],
- "preservation": [
- "Retains sampled curve positions, not a reusable parametric curve object."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in sample count.",
- "example": "const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);\nconst geo = curveToMesh(path, 0.1);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:autoUnwrap",
- "name": "autoUnwrap",
- "summary": "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",
- "family": "uv",
- "tags": [
- "uv",
- "atlas",
- "async"
- ],
- "aliases": [
- "UV atlas",
- "unwrap charts"
- ],
- "intents": [
- "create packed UVs for baked textures",
- "unwrap texture coordinates",
- "UV atlas",
- "unfold mesh"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/uv.ts"
- ],
- "limitations": [
- "Arbitrary chart rotation is unsuitable when directional tileable textures should retain analytic mapping."
- ],
- "kind": "operation",
- "contract": {
- "signature": "await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })",
- "returns": "Promise<THREE.BufferGeometry>",
- "units": "UVs are dimensionless; source positions retain authored units.",
- "axes": "Chart orientation is selected by xatlas, not a directional material frame.",
- "origin": "Preserves the authored origin unless stated otherwise.",
- "execution": "async",
- "ownership": "Returns independent geometry buffers; the input remains unchanged.",
- "coordinates": "Geometry-local coordinates; parent transforms are not applied.",
- "parameters": [
- "Nonempty complete triangle geometry; resolution is a packing limit, not guaranteed final dimensions.",
- "padding defaults 2; useNormals defaults false."
- ],
- "topology": [
- "Reindexes/splits vertices for charts; does not repair malformed source topology."
- ],
- "preservation": [
- "Returns new positions/index/UVs and atlas metadata; normals depend on input/options.",
- "Arbitrary custom attributes, groups, materials and original UV orientation are not preserved by this reconstruction."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "WASM charting/packing depends on mesh complexity and resolution; no general time bound.",
- "example": "const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });\nconst mesh = new THREE.Mesh(unwrapped, bakedPbr);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:loadApprovedTexture",
- "name": "loadApprovedTexture",
- "summary": "Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.",
- "family": "textures",
- "tags": [
- "textures",
- "texture",
- "approved resources",
- "async"
- ],
- "aliases": [
- "approved texture"
- ],
- "intents": [
- "load a permitted material resource"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts",
- "src/material-resources.ts"
- ],
- "limitations": [
- "Missing resource capability fails; arbitrary file/network loading is not exposed."
- ],
- "kind": "operation",
- "contract": {
- "signature": "await loadApprovedTexture(resourceId)",
- "returns": "Promise<THREE.DataTexture>",
- "units": "Texture sizes in pixels; color/data usage is explicit.",
- "axes": "Image U/V coordinates, not scene axes.",
- "origin": "Image-local coordinates.",
- "execution": "async",
- "ownership": "Returns the host-resolved texture; cache sharing is host-specific and not an independent-copy guarantee.",
- "coordinates": "Texture space; does not generate mesh UVs.",
- "parameters": [
- "One approved kiln.texture.* resource ID; paths, URLs, arbitrary bytes and loader options are rejected.",
- "Host resolver fixes dimensions, bytes/hash, MIME, usage and deadlines.",
- "Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export)."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Portable texture bytes and usage metadata matter independently of material appearance."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Host-bounded approved resource loading; network availability is host-specific.",
- "example": "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:proceduralTexture",
- "name": "proceduralTexture",
- "summary": "Builds a repeat-wrapped texture from a bounded layer stack, with no image file needed. Layers composite bottom-first; the same spec produces the same bytes. Seeded noise is tileable, while other patterns can have visible repeat seams. Baked to PNG and embedded in the GLB automatically.",
- "family": "textures",
- "tags": [
- "textures",
- "texture",
- "procedural",
- "deterministic"
- ],
- "aliases": [
- "generated texture",
- "noise texture",
- "layered pattern"
- ],
- "intents": [
- "generate a repeatable texture without external image files"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/procedural-texture.ts"
- ],
- "limitations": [
- "Repeat wrapping does not guarantee matching edge colors. Odd stripe counts, angled patterns and nonconstant gradients can show seams; inspect the chosen pattern at its repeat boundaries."
- ],
- "kind": "operation",
- "contract": {
- "signature": "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: ProceduralLayer[] })",
- "returns": "THREE.DataTexture (tiling, sRGB or linear per usage)",
- "units": "Texture sizes in pixels; color/data usage is explicit.",
- "axes": "Image U/V coordinates, not scene axes.",
- "origin": "Image-local coordinates.",
- "execution": "sync",
- "ownership": "Creates a new DataTexture with generated bytes and portable metadata.",
- "coordinates": "Texture space; does not generate mesh UVs.",
- "parameters": [
- "Strict schemaVersion 2; size power-of-two 4..1024; at most 8 layers.",
- "Pattern counts 1..256 and noise octaves 1..6; seeded patterns are deterministic.",
- "For stripes and gradient, angleDeg rotates the direction of color variation in UV space about the image center. At 0 degrees colors vary across U: stripe bands run along V. At 90 degrees colors vary across V: bands run along U. This does not rotate the mesh UVs.",
- "Stripes count is the number of alternating bands across one unit of the projected coordinate, not the number of colorA/colorB pairs. Gradient runs from its from color to its to color along that coordinate and clamps outside 0..1.",
- "Unknown keys, callbacks, paths, URLs and shader source are rejected.",
- "Layer fields by op — solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }. Every layer also accepts blend?: 'normal'|'multiply'|'screen'|'overlay' and opacity?: 0..1. Pattern counts are integers 1..256; noise octaves are 1..6. Sync — no await. Unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Max 8 layers."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Produces repeat-wrapped encoded texture content; color space follows usage."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Bounded pixel/layer budgets; generation scales with pixels × layers × pattern work.",
- "example": "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:normalMapFromHeight",
- "name": "normalMapFromHeight",
- "summary": "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
- "family": "textures",
- "tags": [
- "textures",
- "texture",
- "normal map"
- ],
- "aliases": [
- "height to normal",
- "bump relief"
- ],
- "intents": [
- "derive surface normals from a height image"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/procedural-texture.ts"
- ],
- "limitations": [
- "Does not displace actual geometry or certify the supplied albedo is a meaningful height field."
- ],
- "kind": "operation",
- "contract": {
- "signature": "normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })",
- "returns": "THREE.DataTexture (linear normal map)",
- "units": "Texture sizes in pixels; color/data usage is explicit.",
- "axes": "Image U/V coordinates, not scene axes.",
- "origin": "Image-local coordinates.",
- "execution": "sync",
- "ownership": "Creates a new linear-data normal texture; source pixels are read, not changed.",
- "coordinates": "Texture space; does not generate mesh UVs.",
- "parameters": [
- "Source must expose supported pixel data; strength controls height-gradient magnitude.",
- "strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Uses brightness as height and wraps image edges; output is tangent-space normal data, not albedo."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Linear in source pixel count with neighboring pixel samples.",
- "example": "const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });\nconst mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:pbrMaterial",
- "name": "pbrMaterial",
- "summary": "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. alphaMode takes lowercase opaque/mask/blend and exports uppercase glTF modes. Supports double-sided output.",
- "family": "material",
- "tags": [
- "material"
- ],
- "aliases": [
- "textured PBR",
- "metallic roughness material"
- ],
- "intents": [
- "bind portable material textures and scalar factors"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyMaterial",
- "relation": "companion"
- }
- ],
- "references": [
- "src/textures.ts"
- ],
- "limitations": [
- "CPU views do not prove texture/metalness appearance."
- ],
- "kind": "operation",
- "contract": {
- "signature": "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided? })",
- "returns": "THREE.MeshStandardMaterial",
- "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",
- "axes": "Not applicable to material construction.",
- "origin": "Not applicable to material construction.",
- "execution": "sync",
- "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",
- "coordinates": "Does not place geometry or generate UV coordinates.",
- "parameters": [
- "alphaMode input is lowercase: opaque (default), mask or blend. Exported glTF uses uppercase OPAQUE/MASK/BLEND; do not pass those as authoring values.",
- "Use packed metallicRoughness data (G roughness, B metalness); unsupported separate data maps are rejected."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Binds texture slots with usage-appropriate color spaces; geometry must provide suitable UVs."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",
- "example": "const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });\nconst crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:foliageMaterial",
- "name": "foliageMaterial",
- "summary": "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",
- "family": "material",
- "tags": [
- "material"
- ],
- "aliases": [
- "alpha cutout",
- "leaf material"
- ],
- "intents": [
- "render cutout cards with portable alpha masking",
- "leaf transparency",
- "foliage cutout",
- "alpha mask"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:copyMaterial",
- "relation": "companion"
- }
- ],
- "references": [
- "src/textures.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",
- "returns": "THREE.MeshStandardMaterial",
- "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",
- "axes": "Not applicable to material construction.",
- "origin": "Not applicable to material construction.",
- "execution": "sync",
- "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",
- "coordinates": "Does not place geometry or generate UV coordinates.",
- "parameters": [
- "Defaults to MASK, alphaCutoff 0.5, rough nonmetal and double-sided; requires useful alpha-bearing albedo.",
- "The example uses an approved 4x4 teaching placeholder. Check GPU and destination alpha filtering; a geometry-flat CPU view cannot establish the cutout silhouette."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Material portability depends on supported glTF properties and the selected exporter; renderer appearance is not a portability guarantee."
- ],
- "semantics": [
- "No asset category or whole-asset acceptance is inferred from this operation."
- ],
- "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",
- "example": "const albedo = await loadApprovedTexture('kiln.texture.leaf-mask-albedo.v1');\nconst mat = foliageMaterial(albedo, { alphaCutoff: 0.5, doubleSided: true });"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:countTriangles",
- "name": "countTriangles",
- "summary": "Sums placed mesh triangles across the subtree, including active InstancedMesh copies and two triangles per sprite. Not draw calls or visible-frame cost.",
- "family": "utility",
- "tags": [
- "utility",
- "metrics",
- "triangles"
- ],
- "aliases": [
- "triangle count"
- ],
- "intents": [
- "measure geometry complexity"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [],
- "kind": "operation",
- "contract": {
- "signature": "countTriangles(root: Object3D)",
- "returns": "number",
- "units": "Counts, not physical units.",
- "axes": "No axis convention required.",
- "origin": "Does not reposition the input.",
- "execution": "sync",
- "ownership": "Read-only traversal; returns counts or names.",
- "coordinates": "Inspects the supplied subtree.",
- "parameters": [
- "An Object3D root; results describe that subtree, not a renderer frame."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not mutate geometry, materials or hierarchy."
- ],
- "semantics": [
- "Counts placed mesh triangles, multiplying active InstancedMesh count, and each sprite as two triangles. Ignores visibility/culling, drawRange and material groups; finalized GLB metrics describe exported primitives separately.",
- "Not an acceptance threshold, visible-frame count, draw-call count or GPU timing."
- ],
- "cost": "Linear traversal over the scene subtree and relevant mesh/material records.",
- "example": "meta.tris = countTriangles(root);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:countMaterials",
- "name": "countMaterials",
- "summary": "Unique material count (by reference) across the subtree.",
- "family": "utility",
- "tags": [
- "utility",
- "metrics",
- "materials"
- ],
- "aliases": [
- "material count"
- ],
- "intents": [
- "measure material reference diversity"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Several meshes sharing one material can still require several draw calls."
- ],
- "kind": "operation",
- "contract": {
- "signature": "countMaterials(root: Object3D)",
- "returns": "number",
- "units": "Counts, not physical units.",
- "axes": "No axis convention required.",
- "origin": "Does not reposition the input.",
- "execution": "sync",
- "ownership": "Read-only traversal; returns counts or names.",
- "coordinates": "Inspects the supplied subtree.",
- "parameters": [
- "An Object3D root; results describe that subtree, not a renderer frame."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not mutate geometry, materials or hierarchy."
- ],
- "semantics": [
- "Counts unique material object references; not draw calls, texture memory or material equivalence."
- ],
- "cost": "Linear traversal over the scene subtree and relevant mesh/material records.",
- "example": "const mats = countMaterials(root);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "operation:getJointNames",
- "name": "getJointNames",
- "summary": "All node names beginning with `Joint_`. Use to sanity-check animation targets.",
- "family": "utility",
- "tags": [
- "utility",
- "inspection",
- "rig",
- "names"
- ],
- "aliases": [
- "joint names"
- ],
- "intents": [
- "list named animation pivots"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:describeAssembly",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts"
- ],
- "limitations": [
- "Prefix lookup is not body-plan or skeleton validation. Use describeAssembly(root).joints for semantic joint-chain, wheel-spin and steering nodes, independent of names."
- ],
- "kind": "operation",
- "contract": {
- "signature": "getJointNames(root: Object3D)",
- "returns": "string[]",
- "units": "Counts, not physical units.",
- "axes": "No axis convention required.",
- "origin": "Does not reposition the input.",
- "execution": "sync",
- "ownership": "Read-only traversal; returns counts or names.",
- "coordinates": "Inspects the supplied subtree.",
- "parameters": [
- "An Object3D root; results describe that subtree, not a renderer frame."
- ],
- "topology": [
- "Not a mesh-producing operation; no manifold or watertightness claim."
- ],
- "preservation": [
- "Does not mutate geometry, materials or hierarchy."
- ],
- "semantics": [
- "Returns names beginning Joint_; does not discover every semantic pivot or validate a rig graph."
- ],
- "cost": "Linear traversal over the scene subtree and relevant mesh/material records.",
- "example": "const joints = getJointNames(root);"
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-bark-v1",
- "name": "Bark material baseline",
- "summary": "Rough, nonmetal tree bark with optional approved albedo and normal resources. Call await materialRecipe(\"kiln.material.bark.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "bark"
- ],
- "aliases": [
- "tree trunk",
- "woody stem"
- ],
- "intents": [
- "apply bark appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.bark.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"BarkSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.bark.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.14702726649759498,0.05780543019106723,0.019382360956935723,1],\"metallicFactor\":0,\"roughnessFactor\":0.93,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-leaf-v1",
- "name": "Leaf material baseline",
- "summary": "Alpha-tested, double-sided foliage using glTF MASK rather than blending. Call await materialRecipe(\"kiln.material.leaf.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "leaf"
- ],
- "aliases": [
- "foliage",
- "leaves",
- "alpha cutout"
- ],
- "intents": [
- "apply leaf appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer.",
- "MASK mode alone does not create a cutout. Supply alpha data and UVs for shaped leaf cards."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.leaf.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"LeafSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.leaf.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, alphaCutoff, doubleSided, textureResources. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.04970656598412723,0.21223075741405523,0.042311410620809675,1],\"metallicFactor\":0,\"roughnessFactor\":0.86,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"MASK\",\"doubleSided\":true,\"textureResources\":{},\"alphaCutoff\":0.5}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-wood-v1",
- "name": "Wood material baseline",
- "summary": "Portable nonmetal wood with a warm authored base color. Call await materialRecipe(\"kiln.material.wood.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "wood"
- ],
- "aliases": [
- "wooden",
- "timber",
- "grain",
- "plank"
- ],
- "intents": [
- "apply wood appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.wood.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"WoodSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.wood.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.32314320911295075,0.14412847085805777,0.042311410620809675,1],\"metallicFactor\":0,\"roughnessFactor\":0.78,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-stone-v1",
- "name": "Stone material baseline",
- "summary": "Dry rough stone with no runtime shader dependency. Call await materialRecipe(\"kiln.material.stone.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "stone"
- ],
- "aliases": [
- "rock",
- "masonry",
- "mineral"
- ],
- "intents": [
- "apply stone appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.stone.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"StoneSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.stone.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.20507873639031693,0.19461783044157582,0.17464740365558504,1],\"metallicFactor\":0,\"roughnessFactor\":0.95,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-rubber-v1",
- "name": "Rubber material baseline",
- "summary": "Dark, high-roughness rubber for tires, grips, and seals. Call await materialRecipe(\"kiln.material.rubber.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "rubber"
- ],
- "aliases": [
- "tire",
- "tyre",
- "grip",
- "seal"
- ],
- "intents": [
- "apply rubber appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.rubber.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"RubberSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.rubber.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.014443843596092545,0.01520851442291271,0.017641954488384078,1],\"metallicFactor\":0,\"roughnessFactor\":0.88,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-painted-metal-v1",
- "name": "Painted metal material baseline",
- "summary": "Coated metal with restrained metallic response and a durable painted finish. Call await materialRecipe(\"kiln.material.painted-metal.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "painted-metal"
- ],
- "aliases": [
- "paint",
- "coating",
- "vehicle panel",
- "cast iron",
- "steel"
- ],
- "intents": [
- "apply painted metal appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.painted-metal.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"Painted metalSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.painted-metal.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.45078578283822346,0.042311410620809675,0.03189603307301153,1],\"metallicFactor\":0.18,\"roughnessFactor\":0.38,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-cloth-v1",
- "name": "Cloth material baseline",
- "summary": "Very rough, nonmetal woven cloth represented with core glTF PBR. Call await materialRecipe(\"kiln.material.cloth.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "cloth"
- ],
- "aliases": [
- "fabric",
- "woven",
- "textile"
- ],
- "intents": [
- "apply cloth appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.cloth.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"ClothSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.cloth.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.1589608350608804,0.17788841598362914,0.22696587351009836,1],\"metallicFactor\":0,\"roughnessFactor\":1,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-skin-v1",
- "name": "Skin material baseline",
- "summary": "Portable skin baseline without nonstandard subsurface extensions. Call await materialRecipe(\"kiln.material.skin.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "skin"
- ],
- "aliases": [
- "flesh",
- "organic surface"
- ],
- "intents": [
- "apply skin appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer.",
- "This baseline has no subsurface scattering."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.skin.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"SkinSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.skin.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, doubleSided. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.4793201831008268,0.1912016827407914,0.12213877222960187,1],\"metallicFactor\":0,\"roughnessFactor\":0.62,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-glass-v1",
- "name": "Glass material baseline",
- "summary": "Portable alpha-blended glass fallback using core glTF fields only. Call await materialRecipe(\"kiln.material.glass.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "glass"
- ],
- "aliases": [
- "transparent",
- "window",
- "translucent"
- ],
- "intents": [
- "apply glass appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer.",
- "Core glTF BLEND approximates transparency; this is not refraction or physical transmission. Sorting depends on the destination renderer."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.glass.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"GlassSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.glass.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, opacity, doubleSided. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.39675523072562685,0.6866853124353134,0.8069522576692516,0.32],\"metallicFactor\":0,\"roughnessFactor\":0.12,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"BLEND\",\"doubleSided\":true,\"textureResources\":{}}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:material-emissive-v1",
- "name": "Emissive material baseline",
- "summary": "Core glTF emissive material with intensity baked into emissiveFactor. Call await materialRecipe(\"kiln.material.emissive.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",
- "family": "materials",
- "tags": [
- "material",
- "pbr",
- "surface",
- "emissive"
- ],
- "aliases": [
- "glowing",
- "lamp",
- "light source"
- ],
- "intents": [
- "apply emissive appearance to any asset"
- ],
- "stability": "stable",
- "related": [
- {
- "id": "operation:materialRecipe",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",
- "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer.",
- "Emissive color does not create a scene light or guarantee bloom in the destination renderer."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:materialRecipe",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Await materialRecipe(\"kiln.material.emissive.v1\") in async build().",
- "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",
- "Render the exported asset and inspect material fidelity before finishing."
- ],
- "example": "const meta = { name: \"EmissiveSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.emissive.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",
- "adaptations": [
- "Allowed overrides: baseColor, roughness, doubleSided, emissiveColor, emissiveIntensity, textureResources. Pass them as the second materialRecipe argument.",
- "Baseline portable fields: {\"baseColorFactor\":[0.042311410620809675,0.017641954488384078,0.005181516702338386,1],\"metallicFactor\":0,\"roughnessFactor\":0.5,\"emissiveFactor\":[1,0.25415209433082675,0.01599629336550963],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",
- "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."
- ],
- "checks": [
- "Inspect glTF material fields and texture bindings in the exported artifact.",
- "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",
- "Check silhouette and dimensions separately from surface appearance."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:rig-biped-v1",
- "name": "biped rig guidance",
- "summary": "Optional biped semantic rig preset graph. The supplied graph has hips, spine, head, paired arm chains and paired leg chains. Adapt the rest offsets and contact roles to the intended proportions.",
- "family": "rigs",
- "tags": [
- "rig",
- "skeleton",
- "joint",
- "biped"
- ],
- "aliases": [
- "two legged",
- "humanoid",
- "person",
- "robot"
- ],
- "intents": [
- "articulate a biped asset",
- "attach geometry to semantic joint pivots"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:createJointChain",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/character.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "The preset supplies semantic joints only, not anatomy, skinning or finished asset geometry.",
- "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",
- "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:createJointChain",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "The supplied graph has hips, spine, head, paired arm chains and paired leg chains. Adapt the rest offsets and contact roles to the intended proportions.",
- "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",
- "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",
- "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."
- ],
- "example": "const meta = { name: \"bipedRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"hips\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"pelvis\"],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"spine\",\"parentRole\":\"hips\",\"offset\":[0,0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"torso\"],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"head\",\"parentRole\":\"spine\",\"offset\":[0,0.55,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"shoulder.left\",\"parentRole\":\"spine\",\"offset\":[0,0.3,-0.25],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"elbow.left\",\"parentRole\":\"shoulder.left\",\"offset\":[0,-0.35,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"wrist.left\",\"parentRole\":\"elbow.left\",\"offset\":[0,-0.35,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"hand.left\",\"grip.left\"],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false},{\"role\":\"shoulder.right\",\"parentRole\":\"spine\",\"offset\":[0,0.3,0.25],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"elbow.right\",\"parentRole\":\"shoulder.right\",\"offset\":[0,-0.35,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"wrist.right\",\"parentRole\":\"elbow.right\",\"offset\":[0,-0.35,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"hand.right\",\"grip.right\"],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false},{\"role\":\"hip.left\",\"parentRole\":\"hips\",\"offset\":[0,-0.1,-0.14],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"knee.left\",\"parentRole\":\"hip.left\",\"offset\":[0,-0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"ankle.left\",\"parentRole\":\"knee.left\",\"offset\":[0,-0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"foot.left\"],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true},{\"role\":\"hip.right\",\"parentRole\":\"hips\",\"offset\":[0,-0.1,0.14],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"knee.right\",\"parentRole\":\"hip.right\",\"offset\":[0,-0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"ankle.right\",\"parentRole\":\"knee.right\",\"offset\":[0,-0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"foot.right\"],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"biped\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",
- "adaptations": [
- "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",
- "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",
- "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."
- ],
- "checks": [
- "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",
- "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",
- "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:rig-quadruped-v1",
- "name": "quadruped rig guidance",
- "summary": "Optional quadruped semantic rig preset graph. The supplied graph has an axial hips/spine/neck/head chain and four leg chains. Adapt limb lengths and paw contacts to the creature.",
- "family": "rigs",
- "tags": [
- "rig",
- "skeleton",
- "joint",
- "quadruped"
- ],
- "aliases": [
- "four legged creature",
- "animal",
- "dog",
- "horse"
- ],
- "intents": [
- "articulate a quadruped asset",
- "attach geometry to semantic joint pivots"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:createJointChain",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/character.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "The preset supplies semantic joints only, not anatomy, skinning or finished asset geometry.",
- "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",
- "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:createJointChain",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "The supplied graph has an axial hips/spine/neck/head chain and four leg chains. Adapt limb lengths and paw contacts to the creature.",
- "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",
- "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",
- "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."
- ],
- "example": "const meta = { name: \"quadrupedRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"hips\",\"offset\":[0,0.8,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"pelvis\"],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"spine\",\"parentRole\":\"hips\",\"offset\":[0.7,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"neck\",\"parentRole\":\"spine\",\"offset\":[0.45,0.1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"head\",\"parentRole\":\"neck\",\"offset\":[0.3,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"shoulder.fore.left\",\"parentRole\":\"spine\",\"offset\":[0.2,-0.1,-0.28],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"elbow.fore.left\",\"parentRole\":\"shoulder.fore.left\",\"offset\":[0,-0.4,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"paw.fore.left\",\"parentRole\":\"elbow.fore.left\",\"offset\":[0,-0.3,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true},{\"role\":\"shoulder.fore.right\",\"parentRole\":\"spine\",\"offset\":[0.2,-0.1,0.28],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"elbow.fore.right\",\"parentRole\":\"shoulder.fore.right\",\"offset\":[0,-0.4,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"paw.fore.right\",\"parentRole\":\"elbow.fore.right\",\"offset\":[0,-0.3,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true},{\"role\":\"hip.hind.left\",\"parentRole\":\"hips\",\"offset\":[0,-0.1,-0.28],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"knee.hind.left\",\"parentRole\":\"hip.hind.left\",\"offset\":[0,-0.4,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"paw.hind.left\",\"parentRole\":\"knee.hind.left\",\"offset\":[0,-0.3,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true},{\"role\":\"hip.hind.right\",\"parentRole\":\"hips\",\"offset\":[0,-0.1,0.28],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"knee.hind.right\",\"parentRole\":\"hip.hind.right\",\"offset\":[0,-0.4,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"paw.hind.right\",\"parentRole\":\"knee.hind.right\",\"offset\":[0,-0.3,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"quadruped\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",
- "adaptations": [
- "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",
- "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",
- "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."
- ],
- "checks": [
- "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",
- "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",
- "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:rig-avian-v1",
- "name": "avian rig guidance",
- "summary": "Optional avian semantic rig guidance with a partial scaffold. Extend the example torso/wing branch with an axial neck/head graph, paired wing chains and any requested leg/contact chains.",
- "family": "rigs",
- "tags": [
- "rig",
- "skeleton",
- "joint",
- "avian"
- ],
- "aliases": [
- "bird",
- "wings",
- "winged creature"
- ],
- "intents": [
- "articulate a avian asset",
- "attach geometry to semantic joint pivots"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:createJointChain",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/character.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",
- "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",
- "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:createJointChain",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Extend the example torso/wing branch with an axial neck/head graph, paired wing chains and any requested leg/contact chains.",
- "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",
- "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",
- "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."
- ],
- "example": "const meta = { name: \"avianRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"wing.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"avian\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",
- "adaptations": [
- "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",
- "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",
- "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."
- ],
- "checks": [
- "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",
- "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",
- "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:rig-serpentine-v1",
- "name": "serpentine rig guidance",
- "summary": "Optional serpentine semantic rig guidance with a partial scaffold. Extend the continuous axial chain with explicit bend axes and requested contact nodes; no limb graph is implied.",
- "family": "rigs",
- "tags": [
- "rig",
- "skeleton",
- "joint",
- "serpentine"
- ],
- "aliases": [
- "snake",
- "tail",
- "worm",
- "axial chain"
- ],
- "intents": [
- "articulate a serpentine asset",
- "attach geometry to semantic joint pivots"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:createJointChain",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/character.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",
- "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",
- "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:createJointChain",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Extend the continuous axial chain with explicit bend axes and requested contact nodes; no limb graph is implied.",
- "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",
- "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",
- "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."
- ],
- "example": "const meta = { name: \"serpentineRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"tail.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"serpentine\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",
- "adaptations": [
- "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",
- "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",
- "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."
- ],
- "checks": [
- "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",
- "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",
- "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:rig-multi-limb-v1",
- "name": "multi-limb rig guidance",
- "summary": "Optional multi-limb semantic rig guidance with a partial scaffold. Expand each requested branch with distinct semantic roles, explicit parent edges and contact/end-effector labels.",
- "family": "rigs",
- "tags": [
- "rig",
- "skeleton",
- "joint",
- "multi-limb"
- ],
- "aliases": [
- "many legs",
- "spider",
- "branched tentacles"
- ],
- "intents": [
- "articulate a multi-limb asset",
- "attach geometry to semantic joint pivots"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:createJointChain",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/character.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",
- "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",
- "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:createJointChain",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Expand each requested branch with distinct semantic roles, explicit parent edges and contact/end-effector labels.",
- "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",
- "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",
- "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."
- ],
- "example": "const meta = { name: \"multi-limbRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"appendage.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"multi-limb\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",
- "adaptations": [
- "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",
- "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",
- "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."
- ],
- "checks": [
- "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",
- "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",
- "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:rig-wheeled-v1",
- "name": "wheeled rig guidance",
- "summary": "Optional wheeled semantic rig guidance with a partial scaffold. Build the character core and articulated appendages as distinct roles; discover wheel assemblies separately for wheel geometry and locomotion.",
- "family": "rigs",
- "tags": [
- "rig",
- "skeleton",
- "joint",
- "wheeled"
- ],
- "aliases": [
- "wheeled robot",
- "mobile character"
- ],
- "intents": [
- "articulate a wheeled asset",
- "attach geometry to semantic joint pivots"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:createJointChain",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/character.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",
- "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",
- "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:createJointChain",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Build the character core and articulated appendages as distinct roles; discover wheel assemblies separately for wheel geometry and locomotion.",
- "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",
- "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",
- "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."
- ],
- "example": "const meta = { name: \"wheeledRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"appendage.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"wheeled\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",
- "adaptations": [
- "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",
- "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",
- "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."
- ],
- "checks": [
- "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",
- "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",
- "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:rig-custom-v1",
- "name": "custom rig guidance",
- "summary": "Optional custom semantic rig guidance with a partial scaffold. Design the graph for the brief, preserving explicit parent edges and local frames without inheriting a different body plan.",
- "family": "rigs",
- "tags": [
- "rig",
- "skeleton",
- "joint",
- "custom"
- ],
- "aliases": [
- "custom skeleton",
- "unusual creature",
- "articulated mechanism"
- ],
- "intents": [
- "articulate a custom asset",
- "attach geometry to semantic joint pivots"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:createJointChain",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/character.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",
- "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",
- "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:createJointChain",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Design the graph for the brief, preserving explicit parent edges and local frames without inheriting a different body plan.",
- "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",
- "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",
- "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."
- ],
- "example": "const meta = { name: \"customRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"appendage.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"custom\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",
- "adaptations": [
- "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",
- "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",
- "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."
- ],
- "checks": [
- "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",
- "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",
- "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:joined-frame-v1",
- "name": "Braced frame from shared attachment points",
- "summary": "Keep both ends of braces attached after resizing a frame by deriving them from the same post endpoints. Separate intended joints from surfaces that must remain apart; adapt to supports, furniture, chassis or scaffolding.",
- "family": "structure",
- "tags": [
- "brace",
- "frame",
- "attachment",
- "junction",
- "clearance",
- "resize"
- ],
- "aliases": [
- "floating support bars",
- "disconnected struts",
- "joined beams",
- "bench frame",
- "table legs and rails",
- "chair or stool frame"
- ],
- "intents": [
- "connect both ends of a support",
- "resize a frame without detached braces"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "operation:beamBetween",
- "relation": "prerequisite"
- },
- {
- "id": "recipe:editable-assembly-v1",
- "relation": "companion"
- }
- ],
- "references": [
- "skills/kiln-refine-asset/references/revision-and-views.md"
- ],
- "limitations": [
- "Centerline joints intentionally overlap. This is neither a Boolean union nor a welded, load-bearing or manufacturing certificate.",
- "The interpolation below describes straight posts in one local frame. Curved or transformed neighbors need attachment points derived from their actual geometry and frames.",
- "A connected-component report can pass when only one end touches. Inspect each intended pair separately; zero unsigned surface distance can mean intersection."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:createRoot",
- "operation:createPart",
- "operation:beamBetween"
- ],
- "steps": [
- "Choose the assembly frame and derive support endpoints from shared dimensions. Identify which interfaces must meet and which must have clearance.",
- "Derive brace endpoints along those same supports instead of entering unrelated coordinates. Rebuild dependent members when dimensions change.",
- "Inspect each brace against each intended post. Then check its clearance from the deck; contact at a required joint must not substitute for clearance elsewhere."
- ],
- "example": "const meta = { name: 'BracedFrame' };\nconst span = 1.2;\nconst height = 0.8;\nconst depth = 0.45;\nconst radius = 0.025;\nfunction build() {\n const root = createRoot(meta.name);\n const steel = gameMaterial('#637987');\n const along = (a, b, t) => a.map((v, i) => v + (b[i] - v) * t);\n for (const [side, z] of [['Near', -depth / 2], ['Far', depth / 2]]) {\n const a0 = [-span / 2, 0, z], a1 = [-span / 2, height, z];\n const b0 = [span / 2, 0, z], b1 = [span / 2, height, z];\n beamBetween(side + 'PostA', a0, a1, radius, steel, { parent: root });\n beamBetween(side + 'PostB', b0, b1, radius, steel, { parent: root });\n beamBetween(side + 'Rail', a1, b1, radius, steel, { parent: root });\n beamBetween(side + 'Brace', along(a0, a1, 0.25), along(b0, b1, 0.75),\n radius, steel, { parent: root });\n }\n const thickness = 0.06;\n createPart('Deck', boxGeo(span + 0.1, thickness, depth + 0.1), gameMaterial('#947653'),\n { parent: root, position: [0, height + radius + thickness / 2, 0] });\n return root;\n}",
- "adaptations": [
- "Change span or height and rebuild. Keep tube thickness independent; scaling the assembly would also scale thickness and clearances.",
- "For a removable connector, give it a local root at the attachment point. For a gap or bearing, derive the separation explicitly instead of overlapping parts."
- ],
- "checks": [
- "Measure each Near/FarBrace against both corresponding PostA and PostB surfaces with kiln_inspect measure.mode=surface. Inspect those joints in context.",
- "Check each rail against the deck underside and each brace against the deck separately. The latter should have positive separation; a whole-frame minimum can hide the wrong connection.",
- "After edits, compare exported bounds and protected components. A rendered image or connected graph alone does not establish all required joints."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:editable-assembly-v1",
- "name": "Editable multipart assembly",
- "summary": "Group a replaceable support under a real root, repeat its full hierarchy, then replace one bracket in its local frame while retaining the post and base. Adapt the same pattern to bays, wheels or mechanisms.",
- "family": "structure",
- "tags": [
- "assembly",
- "replacement",
- "hierarchy",
- "reuse",
- "local frame"
- ],
- "aliases": [
- "replaceable multipart support",
- "coherent parts",
- "group components",
- "swap bracket"
- ],
- "intents": [
- "move or replace an assembly together",
- "edit one repeated component independently"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "operation:describeAssembly",
- "relation": "prerequisite"
- },
- {
- "id": "operation:replicateAssembly",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/assembly.ts",
- "skills/kiln-author-asset/references/geometry-recipes.md"
- ],
- "limitations": [
- "A common name prefix does not create a shared transform or replacement root. The actual parent-child hierarchy must carry the assembly.",
- "Replication does not solve attachment, clearances or load-bearing contact. Check the new component against its neighbors.",
- "This static example has no animation or external references. Animated replacements must preserve or explicitly retarget tracks, joint roles and rest frames."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:createRoot",
- "operation:createPart",
- "operation:describeAssembly",
- "operation:replicateAssembly"
- ],
- "steps": [
- "Create a static root at the support placement datum. Parent every support component beneath it and author child dimensions in that local frame.",
- "Give the replaceable bracket its own root at the connection datum. Retain that root when changing bracket geometry.",
- "Replicate describeAssembly(support.root) with an explicit unique namespace; use nodeMap for the copied bracket instead of guessing a renamed path.",
- "Move or rotate the support root. Replace only the bracket children, then inspect exported parents, unchanged parts and contact views."
- ],
- "example": "const meta = { name: 'EditableSupports' };\nconst replaceSecond = false;\nfunction build() {\n const root = createRoot(meta.name);\n const metal = gameMaterial('#637987');\n function bracketParts(bracket, style, prefix) {\n if (style === 'fork') {\n for (const side of [-1, 1]) createPart(prefix + 'Arm' + side,\n boxGeo(0.04, 0.18, 0.10), metal,\n { parent: bracket, position: [side * 0.055, 0.07, 0], rotation: [0, 0, -side * 35] });\n } else createPart(prefix + 'Saddle', boxGeo(0.30, 0.04, 0.18), metal, { parent: bracket });\n }\n function makeSupport(name, height) {\n const support = createRoot(name);\n root.add(support);\n createPart('Base', boxGeo(0.30, 0.04, 0.30), metal,\n { parent: support, position: [0, 0.02, 0] });\n createPart('Post', boxGeo(0.06, height, 0.06), metal,\n { parent: support, position: [0, height / 2, 0] });\n const bracket = createRoot('Bracket');\n bracket.position.y = height;\n support.add(bracket);\n bracketParts(bracket, 'saddle', '');\n return { root: support, bracket };\n }\n const support = makeSupport('Support', 0.8);\n support.root.position.x = -0.6;\n const second = replicateAssembly(describeAssembly(support.root),\n { namespace: 'second', parent: root });\n second.root.position.x = 0.6;\n second.root.rotation.y = Math.PI / 6; // Object3D rotations use radians.\n if (replaceSecond) {\n const bracket = second.nodeMap.get(support.bracket);\n bracket.clear(); // Retain the attachment root and its local transform.\n bracketParts(bracket, 'fork', 'second__');\n }\n return root;\n}",
- "adaptations": [
- "Set replaceSecond=true for the local bracket replacement. A different bracket height may require moving the connection datum or its neighbor; do not silently stretch the post.",
- "Use ordinary factories for parametric variants and replicateAssembly for a repeated hierarchy. Geometry/materials default to shared; request copy or clone before independently mutating resources.",
- "Flat hierarchies remain valid for independent parts. Add assembly roots when shared placement, articulation or replacement is requested."
- ],
- "checks": [
- "Verify each exported assembly root contains its intended components and each replacement has the intended local transform.",
- "Compare retained geometry, world transforms, materials and animation targets across the edit; test rotated placements as well as the original.",
- "Inspect the connection in context. Names and axis-aligned bounds alone do not prove physical contact."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:surface-detail-v1",
- "name": "Attached raised surface detail",
- "summary": "Create a raised strip whose boundary reuses the actual sampled carrier vertices. Optional starting point for a vein, rib, seam or embossed panel, with shared coordinates and independent materials.",
- "family": "geometry",
- "tags": [
- "surface",
- "attachment",
- "vein",
- "rib",
- "seam",
- "custom geometry"
- ],
- "aliases": [
- "attached raised vein seam",
- "detail follows curved surface",
- "organic surface rib"
- ],
- "intents": [
- "keep detail attached after a shape edit",
- "avoid floating surface decoration"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "operation:parametricSurface",
- "relation": "prerequisite"
- },
- {
- "id": "operation:meshGeo",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/geometry.ts",
- "skills/kiln-author-asset/references/geometry-recipes.md"
- ],
- "limitations": [
- "This is an open carrier sheet and an attached raised strip, not a watertight solid, Boolean union or general attachment solver.",
- "The strip follows a grid-aligned UV band. Arbitrary branches require splitting carrier faces at their boundaries or another explicitly checked attachment construction.",
- "Offsets follow sampled vertex normals; extreme curvature, coarse tessellation or excessive height can produce intersections. Coincident boundaries are intentional; inspect shading and the actual destination."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:parametricSurface",
- "operation:meshGeo",
- "operation:createPart"
- ],
- "steps": [
- "Build the carrier once. Derive the detail from its position, normal, UV and index buffers in the same local frame.",
- "Select complete carrier triangles in a narrow UV band; reuse their topology and boundary positions.",
- "Raise interior vertices along carrier normals, tapering to zero at the entire boundary. Rebuild both meshes from shared dimensions after a shape edit.",
- "Inspect exported boundary contact and overall dimensions, then review the detail in context from the side and underside."
- ],
- "example": "const meta = { name: 'AttachedSurfaceDetail' };\nconst width = 0.8;\nfunction build() {\n const root = createRoot(meta.name);\n const carrier = parametricSurface((u, v) => [\n width * (u - 0.5) * (0.5 + 0.5 * Math.sin(Math.PI * v)),\n 1.2 * v,\n 0.12 * Math.sin(Math.PI * v) + 0.04 * Math.sin(Math.PI * u)\n ], { uSegments: 32, vSegments: 32 });\n createPart('Carrier', carrier, gameMaterial('#47785a'), { parent: root });\n const p = carrier.getAttribute('position'), n = carrier.getAttribute('normal');\n const uv = carrier.getAttribute('uv'), index = carrier.getIndex();\n const lo = 15 / 32, hi = 17 / 32;\n const positions = [], uvs = [], indices = [], remap = new Map();\n function vertex(original) {\n if (remap.has(original)) return remap.get(original);\n const u = uv.getX(original), v = uv.getY(original);\n const boundary = u === lo || u === hi || v === 0 || v === 1;\n const lift = boundary ? 0 : 0.015 * Math.sin(Math.PI * (u - lo) / (hi - lo)) * Math.sin(Math.PI * v);\n const result = positions.length / 3;\n positions.push(p.getX(original) + n.getX(original) * lift,\n p.getY(original) + n.getY(original) * lift,\n p.getZ(original) + n.getZ(original) * lift);\n uvs.push(u, v);\n remap.set(original, result);\n return result;\n }\n for (let t = 0; t < index.count; t += 3) {\n const face = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];\n if (face.every(i => uv.getX(i) >= lo && uv.getX(i) <= hi)) indices.push(...face.map(vertex));\n }\n createPart('RaisedDetail', meshGeo({ positions, indices, uvs }), gameMaterial('#a5bd79'), { parent: root });\n return root;\n}",
- "adaptations": [
- "Change width or the carrier equation to reshape both surfaces together. Keep band limits on sampled UV columns, or split triangles where the new boundary crosses them.",
- "For fine detail without geometric relief, use an authored texture or normal map with matching UVs. For rounded tubes, check their swept cross-sections against the actual surface instead of assuming shared control points prove contact.",
- "Choose tessellation and detail height for the intended scale. Local normal offsets can change any dimension; measure the final asset when a brief requires a fixed envelope."
- ],
- "checks": [
- "Verify the exported strip boundary coincides with the carrier and the strip rises on the intended side; matching equations alone are insufficient.",
- "After edits, compare unchanged regions, dimensions and boundary contact separately from silhouette and shading.",
- "A close view with neighboring surfaces retained should expose gaps, clipping or z-fighting. Structural QA alone does not establish continuous attachment."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:foliage-cutout-v1",
- "name": "Alpha-bearing foliage card",
- "summary": "Bind an approved alpha-bearing albedo to a UV-mapped card with foliageMaterial. An executable cutout teaching fixture; adapt the card shape, placement and approved resource to the asset.",
- "family": "materials",
- "tags": [
- "foliage",
- "alpha",
- "cutout",
- "card",
- "UV",
- "double sided"
- ],
- "aliases": [
- "leaf mask",
- "transparent leaf silhouette",
- "plant billboard"
- ],
- "intents": [
- "make a leaf card with a cutout silhouette",
- "bind alpha to foliage"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "operation:foliageCardGeo",
- "relation": "prerequisite"
- },
- {
- "id": "operation:foliageMaterial",
- "relation": "prerequisite"
- },
- {
- "id": "operation:loadApprovedTexture",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/material-recipes.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "The bundled leaf-mask resource is a 4 by 4 placeholder. It demonstrates alpha delivery, not production foliage detail or a photorealistic leaf.",
- "MASK alone does not cut out an opaque texture. The albedo must contain alpha and the mesh must provide matching UVs.",
- "A card has no physical thickness. Double-sided rendering does not make a solid; destination filtering, mipmaps, shadows and alpha cutoff can change the silhouette.",
- "Raw THREE.DataTexture construction is not an authoring-sandbox route. Use an approved resource available in the current host; do not mutate resource pixels or provenance."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:loadApprovedTexture",
- "operation:foliageCardGeo",
- "operation:foliageMaterial"
- ],
- "steps": [
- "Check material capabilities for an approved alpha-bearing albedo, its availability, license and quality. The example uses the embedded teaching resource.",
- "Await loadApprovedTexture in async build, pass it to foliageMaterial, and bind the material to a card with UVs.",
- "Place cards with ordinary local roots and transforms. Add stems or geometric leaves only when the brief needs them; a billboard construction is optional.",
- "Inspect GPU views from both sides and at the intended distance. Check the exported alphaMode, cutoff, doubleSided, UVs and embedded texture in the destination."
- ],
- "example": "const meta = { name: 'FoliageCutoutTeachingCard' };\nasync function build() {\n const root = createRoot(meta.name);\n // Embedded 4x4 placeholder: replace with a suitable approved resource for delivery.\n const albedo = await loadApprovedTexture('kiln.texture.leaf-mask-albedo.v1');\n const leaf = foliageMaterial(albedo, { alphaCutoff: 0.5, roughness: 0.85, doubleSided: true });\n createPart('LeafCard', foliageCardGeo({ width: 0.6, height: 1, yPivot: 0 }), leaf, { parent: root });\n return root;\n}",
- "adaptations": [
- "Change width, height and yPivot to match placement. For bent cards, preserve UVs when deforming the geometry and inspect the back face.",
- "A custom solid leaf or sampled surface is equally valid. Discover surface geometry and attached detail when a card is inappropriate.",
- "Replace the resource ID only with a host-approved resource that actually has alpha. Change cutoff deliberately and compare the final silhouette, not just the rectangular card bounds."
- ],
- "checks": [
- "A geometry-flat CPU view can confirm placement, but cannot establish the alpha-cut silhouette or material fidelity. Inspect viewFidelity and a GPU image.",
- "Reimport the GLB and verify both transparent and opaque texture samples survive. A nonempty texture binding alone is insufficient.",
- "Review the actual destination at near and far distances for edge loss, halos, backfaces and shadow behavior. Do not present the placeholder as final foliage."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:directional-sweep-v1",
- "name": "Directional texture on a curved sweep",
- "summary": "Use the sweep UVs to keep lengthwise stripes aligned through a bend. A diagnostic pattern for rails, stems, hoses or beams; adapt the material without replacing meaningful UVs with an arbitrarily rotated atlas.",
- "family": "materials",
- "tags": [
- "UV",
- "directional",
- "sweep",
- "stripes",
- "grain",
- "curved rail"
- ],
- "aliases": [
- "texture follows curve",
- "lengthwise wood grain",
- "striped hose"
- ],
- "intents": [
- "keep texture direction along a curved part",
- "preserve UVs through a path edit"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "operation:sweepProfile",
- "relation": "prerequisite"
- },
- {
- "id": "operation:proceduralTexture",
- "relation": "prerequisite"
- },
- {
- "id": "operation:pbrMaterial",
- "relation": "prerequisite"
- }
- ],
- "references": [
- "src/sweep.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "The example uses a conspicuous diagnostic stripe pattern, not realistic wood grain. Material appearance needs GPU and destination review.",
- "Sweep side U follows the profile perimeter and V follows normalized path distance. End caps have separate planar UVs and need distinct treatment for convincing end grain.",
- "Normalized path UVs stretch with path length. Use an explicit repeat/UV scale tied to measured dimensions when physical texture scale must remain constant.",
- "Sweep frames and caps do not prove absence of self-intersection. Keep profile size appropriate to curvature and inspect tight bends and seams."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:sweepProfile",
- "operation:proceduralTexture",
- "operation:pbrMaterial"
- ],
- "steps": [
- "Sample the path at sufficient stations and sweep a simple profile using an explicit up reference.",
- "Keep the generated side UVs: U wraps around the profile; V progresses along path length. Choose a pattern varying across U for stripes that run along V.",
- "Bind the albedo using pbrMaterial. Rebuild from changed path parameters while retaining the intended UV convention.",
- "Inspect both bends, the UV seam and caps with GPU views; reimport and check texture direction in the intended destination."
- ],
- "example": "const meta = { name: 'DirectionalSweepTeachingPattern' };\nconst curveOffset = 0.2;\nfunction build() {\n const root = createRoot(meta.name);\n const profile = Array.from({ length: 16 }, (_, i) => {\n const angle = 2 * Math.PI * i / 16;\n return [0.07 * Math.cos(angle), 0.07 * Math.sin(angle)];\n });\n const path = Array.from({ length: 33 }, (_, i) => {\n const t = i / 32;\n return [1.2 * t, 0.25, curveOffset * Math.sin(2 * Math.PI * t)];\n });\n const albedo = proceduralTexture({ schemaVersion: 2, size: 128, usage: 'albedo',\n layers: [{ op: 'stripes', colorA: 0x8a4b24, colorB: 0xe4bc70, count: 16, angleDeg: 0 }] });\n createPart('CurvedRail', sweepProfile(profile, path, { up: [0, 1, 0] }),\n pbrMaterial({ albedo, roughness: 0.7, metalness: 0 }), { parent: root });\n return root;\n}",
- "adaptations": [
- "Change curveOffset to its negative to mirror the path while preserving length and UV scale; changing length requires a separate texture-density decision.",
- "Replace stripes with a suitable authored or approved directional texture. Match its direction to these UV axes rather than assuming all textures use the same convention.",
- "Use an atlas when you need independent baked surface detail. Its arbitrary chart rotations are a different contract from continuous directional tiling."
- ],
- "checks": [
- "Check the exported TEXCOORD_0 and texture binding, then inspect that stripes follow the path rather than running across it.",
- "Compare UVs, texture bytes and retained parts after a shape edit. GPU appearance and structural dimensions are separate evidence.",
- "Verify the destination preserves texture direction, seams and cap treatment at useful viewing distances; a CPU geometry sheet cannot establish these."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:structural-bays-v1",
- "name": "Editable structural bays and openings",
- "summary": "Compose any number of storeys from independently placed bays with real wall apertures and replaceable recessed glazing. Resize one bay without scaling its neighbors; the example leaves a clear ground-level entry.",
- "family": "structure",
- "tags": [
- "facade",
- "bay",
- "opening",
- "storey",
- "local frame",
- "replacement"
- ],
- "aliases": [
- "stack editable facade bays and openings",
- "multi-level wall",
- "recessed window",
- "modular architecture"
- ],
- "intents": [
- "resize one structural bay",
- "replace window infill independently",
- "build an open facade without a house preset"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:wallWithOpening",
- "relation": "prerequisite"
- },
- {
- "id": "recipe:editable-assembly-v1",
- "relation": "companion"
- }
- ],
- "references": [
- "src/primitives.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "A teaching facade, not a complete building, load-bearing design or navigation certificate. Add floors, access, returns and support only when requested.",
- "The clear entry is intentionally unfilled. Adding doors, plinths, trim or collision meshes can obstruct it; check the finished passage, not just the aperture parameters.",
- "Glazing is a core glTF transparency approximation. Review GPU appearance and the intended destination; this example has no textures or physical refraction."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:wallWithOpening",
- "operation:createRoot",
- "operation:createPart",
- "operation:boxGeo",
- "operation:glassMaterial"
- ],
- "steps": [
- "Choose storey heights and bay widths from the brief. Put placement on each bay root; author its wall and infill in bay-local coordinates.",
- "Use one front-plane datum: this example faces +Z at Z=0, with the wall in -thickness..0. Position glazing and trim relative to that plane once, avoiding a second parent offset.",
- "Create an actual opening, then give its replaceable infill its own root. Keep an entry free of full-width plinths and unrelated decorations.",
- "For a width edit, rebuild affected dimensions and reposition neighboring roots. For an infill swap, retain its root and replace only its children."
- ],
- "example": "const meta = { name: 'StructuralBays' };\nconst centerWidth = 3;\nconst storeys = 6;\nconst replaceCenterFourth = false;\nfunction build() {\n const root = createRoot(meta.name);\n const wallMaterial = gameMaterial('#a87a64');\n const frameMaterial = gameMaterial('#cad0ca');\n const glass = glassMaterial('#83b4c3', { opacity: 0.45 });\n const widths = [2.5, centerWidth, 2.5], height = 3, thickness = 0.3;\n const totalWidth = widths.reduce((sum, width) => sum + width, 0);\n function infill(group, name, width, tall, divided) {\n if (divided) {\n for (const side of [-1, 1]) createPart(name + '_Pane' + side,\n boxGeo((width - 0.12) / 2, tall - 0.08, 0.02), glass,\n { parent: group, position: [side * (width - 0.04) / 4, tall / 2, -0.18] });\n createPart(name + '_Divider', boxGeo(0.04, tall, 0.05), frameMaterial,\n { parent: group, position: [0, tall / 2, -0.16] });\n } else createPart(name + '_Pane', boxGeo(width - 0.08, tall - 0.08, 0.02), glass,\n { parent: group, position: [0, tall / 2, -0.18] });\n }\n for (let level = 1; level <= storeys; level++) {\n const floor = createRoot('Storey_' + level);\n floor.position.y = (level - 1) * height;\n root.add(floor);\n let left = -totalWidth / 2;\n for (let bayIndex = 0; bayIndex < widths.length; bayIndex++) {\n const width = widths[bayIndex], name = 'Bay_' + level + '_' + bayIndex;\n const bay = createRoot(name);\n bay.position.x = left + width / 2;\n floor.add(bay);\n left += width;\n const entry = level === 1 && bayIndex === 1;\n const apertureWidth = entry ? 1.4 : width * 0.5;\n const apertureHeight = entry ? 2.4 : 1.6, sill = entry ? 0 : 0.8;\n const wall = wallWithOpening(name + '_Wall', wallMaterial, {\n length: width, height, thickness, axis: 'x',\n opening: { kind: entry ? 'door' : 'window', width: apertureWidth, height: apertureHeight, sill },\n parent: bay\n });\n wall.position.z = -thickness / 2;\n // Surround is outside the aperture, so the declared entry remains clear.\n for (const side of [-1, 1]) createPart(name + '_Jamb' + side,\n boxGeo(0.08, apertureHeight, 0.12), frameMaterial,\n { parent: bay, position: [side * (apertureWidth / 2 + 0.04), sill + apertureHeight / 2, 0] });\n createPart(name + '_Lintel', boxGeo(apertureWidth + 0.16, 0.08, 0.12), frameMaterial,\n { parent: bay, position: [0, sill + apertureHeight + 0.04, 0] });\n if (!entry) {\n const glazing = createRoot('Glazing_' + level + '_' + bayIndex);\n glazing.position.y = sill;\n bay.add(glazing);\n infill(glazing, name, apertureWidth, apertureHeight, false);\n if (replaceCenterFourth && level === 4 && bayIndex === 1) {\n glazing.clear();\n infill(glazing, name, apertureWidth, apertureHeight, true);\n }\n }\n }\n }\n return root;\n}",
- "adaptations": [
- "Change centerWidth or storeys; there is no category or two-floor restriction. Preserve outer detailing by moving the outer roots rather than scaling the whole facade.",
- "Set replaceCenterFourth=true to swap one infill. For a balcony or roof, use a separate attachment root and an explicit physical interface; check neighbor contact after replacement.",
- "Remove bays or combine this open wall with other structures freely. For repeated identical hierarchies, discover replicateAssembly and its explicit resource/identity policies."
- ],
- "checks": [
- "Measure exported bay widths, storey heights and final passage clearance including trim. A wall opening alone does not prove usable access.",
- "Confirm recessed glazing lies inside the intended wall depth in world space; a parent offset applies to every child.",
- "Compare retained geometry, hierarchy and world transforms after a local swap, including with a rotated/scaled ancestor."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:open-tiered-seating-v1",
- "name": "Open tiered seating sectors",
- "summary": "Build an open arena or amphitheater from separately editable stepped sectors, reserving an entrance before placing geometry. Each sector has a local placement root; no enclosing roof, house layout or floor-count policy is implied.",
- "family": "structure",
- "tags": [
- "arena",
- "amphitheater",
- "seating",
- "tiers",
- "open structure",
- "entrance"
- ],
- "aliases": [
- "open arena tiered seating entrance",
- "coliseum seating",
- "stadium terraces"
- ],
- "intents": [
- "keep a path into an open structure",
- "replace one seating sector",
- "build tiered environment geometry"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "operation:extrudeProfile",
- "relation": "prerequisite"
- },
- {
- "id": "recipe:structural-bays-v1",
- "relation": "companion"
- }
- ],
- "references": [
- "src/profile.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Faceted solid tier blocks are a layout scaffold, not individual seats, a circulation plan, structural engineering or a collision/navigation certificate.",
- "The reserved entrance stays open only if later walls, trim, platforms and collision geometry also respect it. Evaluate the complete asset and requested approach route.",
- "Adjacent sectors meet on matching radial planes; coarse sectors approximate circular arcs with chords. The independent solids are not Boolean-unioned."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "operation:extrudeProfile",
- "operation:createRoot",
- "operation:createPart"
- ],
- "steps": [
- "Reserve an entrance sector before generating tiers. Define inner radius, row depth/rise and the open angular interval explicitly.",
- "Give each seating sector a root at its inner-edge midpoint. Use sector-local profiles so placement is carried by the root instead of baked world coordinates.",
- "Extrude individual tier footprints from ground to their requested top height. Keep sectors and rows separately addressable for edits.",
- "Inspect the exported entrance with all neighboring geometry present, then verify sector seams and unchanged neighbors after a replacement or omission."
- ],
- "example": "const meta = { name: 'OpenTieredSeating' };\nconst omittedSector = -1;\nasync function build() {\n const root = createRoot(meta.name);\n const stone = gameMaterial('#a6947c');\n const innerRadius = 6, rowDepth = 0.8, rowRise = 0.4, rows = 4;\n const sectors = 20, entranceDegrees = 60;\n const span = (360 - entranceDegrees) / sectors;\n const half = span * Math.PI / 360;\n // extrudeProfile(axis:'y') maps profile (u,v) to world-local (X,-Z).\n function point(radius, angle) {\n return [radius * Math.cos(angle) - innerRadius, -radius * Math.sin(angle)];\n }\n for (let sector = 0; sector < sectors; sector++) {\n if (sector === omittedSector) continue;\n const angle = (entranceDegrees / 2 + (sector + 0.5) * span) * Math.PI / 180;\n const group = createRoot('Sector_' + sector);\n group.position.set(innerRadius * Math.cos(angle), 0, innerRadius * Math.sin(angle));\n group.rotation.y = -angle; // Object3D rotation is radians.\n root.add(group);\n for (let row = 0; row < rows; row++) {\n const near = innerRadius + row * rowDepth, far = near + rowDepth;\n const footprint = [point(near, -half), point(far, -half), point(far, half), point(near, half)];\n const geometry = await extrudeProfile(footprint, { axis: 'y', depth: (row + 1) * rowRise, center: false });\n createPart('Sector_' + sector + '_Tier_' + row, geometry, stone, { parent: group });\n }\n }\n return root;\n}",
- "adaptations": [
- "Change rows, rise, radius or the open angle to fit the brief. For a larger arc budget use smaller sectors; do not add floors or a roof unless requested.",
- "Set omittedSector=6 to remove one complete sector while preserving its neighbors. Build replacement geometry beneath that same placement root to retain its interface.",
- "Use createStairs for a straight access flight where needed; seating rise is not automatically a walkable stair or accessibility ramp. Check approach clearance and destination collision separately."
- ],
- "checks": [
- "Trace the approach through the final exported asset near the ground and at the requested clearance height. Decorative or structural additions must not silently close it.",
- "Verify exported sector roots carry placement, tier top heights match requested rise and adjoining radial endpoints agree.",
- "Inspect the inside, outside and underside; independent solids and plausible silhouettes alone do not prove all navigation or material requirements."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:steerable-wheel-v1",
- "name": "Steerable wheel with a local fork",
- "summary": "Compose a wheel, fork and axle around separate steering and spin pivots. Resize from shared dimensions and inspect actual animated geometry; usable as a caster or mechanism without selecting a vehicle category.",
- "family": "articulation",
- "tags": [
- "wheel",
- "caster",
- "steering",
- "spin",
- "local frame",
- "animation"
- ],
- "aliases": [
- "swivel support",
- "steer and spin a caster wheel",
- "rotating wheel fork"
- ],
- "intents": [
- "add an editable rolling support",
- "separate steering from wheel rotation"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:createWheelAssembly",
- "relation": "prerequisite"
- },
- {
- "id": "recipe:editable-assembly-v1",
- "relation": "companion"
- }
- ],
- "references": [
- "src/vehicle.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "A teaching assembly, not a suspension, physics model or load certificate. Spin is in place; translation is not synchronized to rolling distance.",
- "The contact marker is a rest-pose reference under the spin pivot. Evaluate actual tire geometry over motion; nominal radius or marker position cannot certify rolling contact.",
- "The host mounting surface is not included. Bind external support relationships when integrating into the host, and check mounting contact and clearance independently."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:createWheelAssembly",
- "operation:createRoot",
- "operation:createPart",
- "operation:rotationTrack",
- "operation:createClip"
- ],
- "steps": [
- "Choose the axle datum and dimensions. This example uses +Y up, +Z spin and +Y steering; put the assembly placement on a parent root.",
- "Parent the fork and axle to the steering pivot and the tire, rim, hub and spin marker to the spin pivot. Keep the fork out of wheel rotation.",
- "Derive fork spacing, axle length, clearance and placement from radius and width. Rebuild after a dimension edit rather than scaling hardware thickness.",
- "Use intermediate quaternion keys for a full spin. Export and inspect both clips, sampled tread bounds and fork clearance before attaching a host."
- ],
- "example": "const meta = { name: 'SteerableCaster' };\nconst radius = 0.25;\nconst width = 0.12;\nfunction build() {\n const root = createRoot(meta.name);\n const steel = gameMaterial('#7894a3');\n const wheel = createWheelAssembly('Caster', {\n tire: gameMaterial('#252b30'), rim: steel\n }, { radius, width, side: 'center', index: 'caster', steering: true,\n position: [0, radius, 0], parent: root,\n geometries: { tire: torusGeo(radius - width / 2, width / 2, 12, 64) } });\n const fork = createRoot('Fork');\n wheel.steeringPivot.add(fork);\n const legZ = width / 2 + 0.04, top = radius + 0.10;\n for (const side of [-1, 1]) createPart('ForkLeg' + side,\n boxGeo(0.08, top, 0.04), steel,\n { parent: fork, position: [0, top / 2, side * legZ] });\n createPart('ForkCap', boxGeo(0.10, 0.05, 2 * legZ + 0.04), steel,\n { parent: fork, position: [0, top + 0.025, 0] });\n createPart('Axle', cylinderZGeo(0.025, 0.025, 2 * legZ + 0.06, 20), steel,\n { parent: fork, semantic: { roles: ['axle.caster'] } });\n createPart('SpinMarker', boxGeo(radius * 0.2, 0.015, 0.008), gameMaterial('#edbd54'),\n { parent: wheel.spinPivot, position: [radius * 0.43, 0, width * 0.4 + 0.002] });\n return root;\n}\nfunction animate(root) {\n const steering = root.getObjectByName('SteeringPivot_center_caster');\n const spin = root.getObjectByName('WheelPivot_center_caster');\n return [\n createClip('Steer', 1, [rotationTrack(steering.name, [\n { time: 0, rotation: [0, 0, 0] },\n { time: 0.5, rotation: [0, 40, 0] },\n { time: 1, rotation: [0, 0, 0] }\n ])]),\n createClip('Spin', 1, [rotationTrack(spin.name,\n [0, 90, 180, 270, 360].map((angle, i) => ({ time: i / 4, rotation: [0, 0, angle] })))])\n ];\n}",
- "adaptations": [
- "Use center identity for a wheel on the host centerline. A single-sided fork is an explicit design alternative: preserve the axle-to-hub connection and inspect it; the wheel helper does not choose the support arrangement.",
- "Change radius or width and rebuild. Preserve the declared axle frame when replacing tire geometry; check the helper geometryChecks advisory and actual exported bounds.",
- "Replicate describeAssembly(root, { clips }) with a unique namespace and an explicit external-reference decision; use the returned remapped clips and nodeMap.",
- "For a real rolling assembly, account for tread protrusions, wheel profile and sampled rotation when choosing center height. A smooth polygonal tire is still a contact approximation."
- ],
- "checks": [
- "Verify fork and spin are siblings beneath steering, and the entire assembly moves together under a transformed parent.",
- "Sample exported spin and steering independently. The tire must not rotate the fork; steering must carry both.",
- "Inspect the actual axle/fork/hub interface, ground clearance and host attachment. Semantic roles and matching bounding boxes do not prove physical mating."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "recipe:branched-articulation-v1",
- "name": "Branched articulation with preserved rest frames",
- "summary": "Build a two-branch mechanical gripper with local links, explicit parent roles and nonzero rest rotations. Animate bends without resetting joint offsets or assuming a humanoid skeleton.",
- "family": "articulation",
- "tags": [
- "rig",
- "branch",
- "gripper",
- "rest frame",
- "local rotation",
- "animation"
- ],
- "aliases": [
- "branching articulated gripper",
- "non humanoid mechanism",
- "jointed appendages"
- ],
- "intents": [
- "animate a branching mechanism",
- "retain rest offsets during a bend"
- ],
- "stability": "experimental",
- "related": [
- {
- "id": "assembly:createJointChain",
- "relation": "prerequisite"
- },
- {
- "id": "recipe:rig-custom-v1",
- "relation": "companion"
- }
- ],
- "references": [
- "src/character.ts",
- "docs/geometry.md"
- ],
- "limitations": [
- "Rigid articulated teaching geometry, without skinning, inverse kinematics, grasp constraints or collision avoidance. Inspect each intended pose and edited proportion.",
- "The animation demonstrates local bending only. A graph label does not establish locomotion, stable contact or a functional grasp."
- ],
- "kind": "recipe",
- "recipe": {
- "prerequisites": [
- "assembly:createJointChain",
- "operation:createRoot",
- "operation:createPart",
- "operation:rotationTrack",
- "operation:createClip"
- ],
- "steps": [
- "Place a shared core, then parent each branch explicitly with parentRole. Give every role a unique name and author links in each joint local frame.",
- "Set rest rotations as quaternions and derive geometry and downstream offsets from the same lengths. Record the returned descriptors on the root graph.",
- "Rotation tracks are absolute local rotations, not deltas. Start from the rest orientation; leave translations untouched unless intentionally changing them.",
- "Export the graph and clips; verify parent edges, rest frames and moving geometry. For replication, remap the full assembly and its clips together."
- ],
- "example": "const meta = { name: 'BranchedGripper' };\nconst upperLength = 0.4;\nconst lowerLength = 0.28;\nfunction build() {\n const root = createRoot(meta.name);\n const metal = gameMaterial('#748e9c'), jointMaterial = gameMaterial('#35464f');\n const core = createJointChain('Fork', [{ role: 'core', offset: [0, 0.3, 0] }], { parent: root });\n createPart('Core', boxGeo(0.32, 0.18, 0.18), metal, { parent: core.root });\n const descriptors = [...core.descriptors];\n function zRotation(degrees) {\n const half = degrees * Math.PI / 360;\n return [0, 0, Math.sin(half), Math.cos(half)];\n }\n for (const side of [-1, 1]) {\n const label = side < 0 ? 'left' : 'right';\n const branch = createJointChain('Fork', [\n { role: label + '.shoulder', offset: [side * 0.1, 0, 0],\n restRotation: zRotation(-side * 35), localBendAxis: [0, 0, 1] },\n { role: label + '.elbow', offset: [0, upperLength, 0],\n restRotation: zRotation(side * 15), localBendAxis: [0, 0, 1] },\n { role: label + '.tip', offset: [0, lowerLength, 0], endEffector: true }\n ], { parent: core.end, parentRole: 'core' });\n descriptors.push(...branch.descriptors);\n createPart(label + 'Upper', boxGeo(0.08, upperLength, 0.08), metal,\n { parent: branch.nodes[0], position: [0, upperLength / 2, 0] });\n createPart(label + 'Lower', boxGeo(0.07, lowerLength, 0.07), metal,\n { parent: branch.nodes[1], position: [0, lowerLength / 2, 0] });\n for (let i = 0; i < 2; i++) createPart(label + 'Hinge' + i,\n cylinderZGeo(0.055, 0.055, 0.1, 16), jointMaterial, { parent: branch.nodes[i] });\n createPart(label + 'Pad', boxGeo(0.11, 0.06, 0.12), jointMaterial, { parent: branch.end });\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: 'custom', joints: descriptors };\n return root;\n}\nfunction animate(root) {\n const tracks = [];\n root.traverse(node => {\n const descriptor = node.userData.kilnCharacterJoint;\n if (!descriptor || !descriptor.role.endsWith('.elbow')) return;\n const rest = descriptor.rest.rotation;\n const degrees = 2 * Math.atan2(rest[2], rest[3]) * 180 / Math.PI;\n const bend = descriptor.role.startsWith('left.') ? -45 : 45;\n tracks.push(rotationTrack(node.name, [\n { time: 0, rotation: [0, 0, degrees] },\n { time: 0.5, rotation: [0, 0, degrees + bend] },\n { time: 1, rotation: [0, 0, degrees] }\n ]));\n });\n return [createClip('Bend', 1, tracks)];\n}",
- "adaptations": [
- "Change upperLength or lowerLength, rebuilding links and child offsets together. The core and the opposite branch need not change for a one-branch edit.",
- "Add branches with distinct roles and explicit parent edges. No body-plan preset or asset category is required.",
- "This example bends about local Z only. For arbitrary rest frames, compose rest and delta quaternions in the intended order rather than adding Euler angles."
- ],
- "checks": [
- "Every graph role must resolve to one exported joint and parentRole must match the real hierarchy.",
- "At time zero, sampled animation must agree with the declared rest frame. Bending must retain translations and move the attached links and end effectors.",
- "Review open and bent views, hinge contact, self-intersection and the intended destination playback. Structural validity alone cannot certify useful motion."
- ]
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "shape:project-draft",
- "name": "project-draft",
- "summary": "The record kiln_project create takes: name, brief, design (style, scale, palette, materialRoles, conventions, exceptions), inventory, deliveryProfiles, materialDependencies, references and reviews, with an optional projectId.",
- "family": "tool-input",
- "tags": [
- "schema",
- "kiln_project",
- "draft"
- ],
- "aliases": [
- "project draft",
- "new project fields",
- "project record"
- ],
- "intents": [
- "create a project for a pack",
- "write a project brief and inventory"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "docs/projects-and-live-review.md"
- ],
- "limitations": [],
- "kind": "shape",
- "shape": {
- "tool": "kiln_project",
- "field": "draft",
- "schema": {
- "type": "object",
- "properties": {
- "projectId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "brief": {
- "default": "",
- "type": "string",
- "maxLength": 16000
- },
- "design": {
- "default": {
- "style": "",
- "scale": "",
- "palette": [],
- "materialRoles": [],
- "conventions": [],
- "exceptions": []
- },
- "type": "object",
- "properties": {
- "style": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "scale": {
- "default": "",
- "type": "string",
- "maxLength": 1000
- },
- "palette": {
- "default": [],
- "maxItems": 64,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "role": {
- "type": "string",
- "minLength": 1,
- "maxLength": 100
- },
- "color": {
- "type": "string",
- "pattern": "^#[a-fA-F0-9]{6}$"
- }
- },
- "required": [
- "role",
- "color"
- ],
- "additionalProperties": false
- }
- },
- "materialRoles": {
- "default": [],
- "maxItems": 128,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "role": {
- "type": "string",
- "minLength": 1,
- "maxLength": 100
- },
- "description": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- }
- },
- "required": [
- "role"
- ],
- "additionalProperties": false
- }
- },
- "conventions": {
- "default": [],
- "maxItems": 100,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 1000
- }
- },
- "exceptions": {
- "default": [],
- "maxItems": 100,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 1000
- }
- }
- },
- "additionalProperties": false
- },
- "inventory": {
- "default": [],
- "maxItems": 1000,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "kind": {
- "default": "asset",
- "type": "string",
- "enum": [
- "asset",
- "environment"
- ]
- },
- "brief": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "references": {
- "default": [],
- "maxItems": 64,
- "type": "array",
- "items": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- }
- },
- "asset": {
- "type": "object",
- "properties": {
- "collectionId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "assetId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "revisionId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- }
- },
- "required": [
- "collectionId",
- "assetId",
- "revisionId"
- ],
- "additionalProperties": false
- }
- },
- "required": [
- "id",
- "name"
- ],
- "additionalProperties": false
- }
- },
- "deliveryProfiles": {
- "default": [],
- "maxItems": 32,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "target": {
- "type": "string",
- "enum": [
- "three",
- "godot",
- "unity",
- "unreal",
- "roblox",
- "sbox",
- "usdz",
- "custom"
- ]
- },
- "description": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "performanceIntent": {
- "default": "",
- "type": "string",
- "maxLength": 1000
- },
- "constraints": {
- "default": [],
- "maxItems": 100,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 1000
- }
- }
- },
- "required": [
- "id",
- "target"
- ],
- "additionalProperties": false
- }
- },
- "materialDependencies": {
- "default": [],
- "maxItems": 512,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- },
- "revisionId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "role": {
- "type": "string",
- "maxLength": 100
- }
- },
- "required": [
- "resourceId",
- "revisionId",
- "sha256"
- ],
- "additionalProperties": false
- }
- },
- "references": {
- "default": [],
- "maxItems": 256,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "title": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "uri": {
- "type": "string",
- "minLength": 1,
- "maxLength": 2048
- },
- "description": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- }
- },
- "required": [
- "id",
- "title",
- "uri"
- ],
- "additionalProperties": false
- }
- },
- "reviews": {
- "default": [],
- "maxItems": 2000,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "inventoryId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "projectRevisionId": {
- "type": "string",
- "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"
- },
- "asset": {
- "type": "object",
- "properties": {
- "collectionId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "assetId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "revisionId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- }
- },
- "required": [
- "collectionId",
- "assetId",
- "revisionId"
- ],
- "additionalProperties": false
- },
- "reviewer": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "verdict": {
- "type": "string",
- "enum": [
- "comment",
- "changes-requested",
- "accepted"
- ]
- },
- "notes": {
- "type": "string",
- "maxLength": 4000
- }
- },
- "required": [
- "id",
- "inventoryId",
- "projectRevisionId",
- "asset",
- "reviewer",
- "verdict",
- "notes"
- ],
- "additionalProperties": false
- }
- }
- },
- "required": [
- "name"
- ],
- "additionalProperties": false
- }
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "shape:project-patch",
- "name": "project-patch",
- "summary": "The record kiln_project update takes: the same top-level fields as the draft, each optional; a supplied field replaces its previous value whole, so read and merge design before changing one preference.",
- "family": "tool-input",
- "tags": [
- "schema",
- "kiln_project",
- "patch"
- ],
- "aliases": [
- "project patch",
- "project update fields"
- ],
- "intents": [
- "update a project brief, design, inventory or material pins"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "docs/projects-and-live-review.md"
- ],
- "limitations": [],
- "kind": "shape",
- "shape": {
- "tool": "kiln_project",
- "field": "patch",
- "schema": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "brief": {
- "type": "string",
- "maxLength": 16000
- },
- "design": {
- "type": "object",
- "properties": {
- "style": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "scale": {
- "default": "",
- "type": "string",
- "maxLength": 1000
- },
- "palette": {
- "default": [],
- "maxItems": 64,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "role": {
- "type": "string",
- "minLength": 1,
- "maxLength": 100
- },
- "color": {
- "type": "string",
- "pattern": "^#[a-fA-F0-9]{6}$"
- }
- },
- "required": [
- "role",
- "color"
- ],
- "additionalProperties": false
- }
- },
- "materialRoles": {
- "default": [],
- "maxItems": 128,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "role": {
- "type": "string",
- "minLength": 1,
- "maxLength": 100
- },
- "description": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- }
- },
- "required": [
- "role"
- ],
- "additionalProperties": false
- }
- },
- "conventions": {
- "default": [],
- "maxItems": 100,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 1000
- }
- },
- "exceptions": {
- "default": [],
- "maxItems": 100,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 1000
- }
- }
- },
- "additionalProperties": false
- },
- "inventory": {
- "maxItems": 1000,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "kind": {
- "default": "asset",
- "type": "string",
- "enum": [
- "asset",
- "environment"
- ]
- },
- "brief": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "references": {
- "default": [],
- "maxItems": 64,
- "type": "array",
- "items": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- }
- },
- "asset": {
- "type": "object",
- "properties": {
- "collectionId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "assetId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "revisionId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- }
- },
- "required": [
- "collectionId",
- "assetId",
- "revisionId"
- ],
- "additionalProperties": false
- }
- },
- "required": [
- "id",
- "name"
- ],
- "additionalProperties": false
- }
- },
- "deliveryProfiles": {
- "maxItems": 32,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "target": {
- "type": "string",
- "enum": [
- "three",
- "godot",
- "unity",
- "unreal",
- "roblox",
- "sbox",
- "usdz",
- "custom"
- ]
- },
- "description": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "performanceIntent": {
- "default": "",
- "type": "string",
- "maxLength": 1000
- },
- "constraints": {
- "default": [],
- "maxItems": 100,
- "type": "array",
- "items": {
- "type": "string",
- "maxLength": 1000
- }
- }
- },
- "required": [
- "id",
- "target"
- ],
- "additionalProperties": false
- }
- },
- "materialDependencies": {
- "maxItems": 512,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "resourceId": {
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"
- },
- "revisionId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "role": {
- "type": "string",
- "maxLength": 100
- }
- },
- "required": [
- "resourceId",
- "revisionId",
- "sha256"
- ],
- "additionalProperties": false
- }
- },
- "references": {
- "maxItems": 256,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "title": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "uri": {
- "type": "string",
- "minLength": 1,
- "maxLength": 2048
- },
- "description": {
- "default": "",
- "type": "string",
- "maxLength": 4000
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- }
- },
- "required": [
- "id",
- "title",
- "uri"
- ],
- "additionalProperties": false
- }
- },
- "reviews": {
- "maxItems": 2000,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "inventoryId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "projectRevisionId": {
- "type": "string",
- "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"
- },
- "asset": {
- "type": "object",
- "properties": {
- "collectionId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "assetId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "revisionId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- }
- },
- "required": [
- "collectionId",
- "assetId",
- "revisionId"
- ],
- "additionalProperties": false
- },
- "reviewer": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "verdict": {
- "type": "string",
- "enum": [
- "comment",
- "changes-requested",
- "accepted"
- ]
- },
- "notes": {
- "type": "string",
- "maxLength": 4000
- }
- },
- "required": [
- "id",
- "inventoryId",
- "projectRevisionId",
- "asset",
- "reviewer",
- "verdict",
- "notes"
- ],
- "additionalProperties": false
- }
- }
- },
- "additionalProperties": false
- }
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "shape:material-draft",
- "name": "material-draft",
- "summary": "The record kiln_material create-procedural takes: materialId, name, tileable, sources with license, and maps whose layered procedural specs (solid, checker, stripes, gradient, bricks, noise) bake into PNG maps; optional tags, physicalSizeMeters and parameters.",
- "family": "tool-input",
- "tags": [
- "schema",
- "kiln_material",
- "draft"
- ],
- "aliases": [
- "procedural material",
- "material recipe draft",
- "texture layers"
- ],
- "intents": [
- "bake a custom tileable material from layers"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "docs/projects-and-live-review.md"
- ],
- "limitations": [],
- "kind": "shape",
- "shape": {
- "tool": "kiln_material",
- "field": "draft",
- "schema": {
- "type": "object",
- "properties": {
- "materialId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "tags": {
- "maxItems": 30,
- "type": "array",
- "items": {
- "type": "string",
- "minLength": 1,
- "maxLength": 80
- }
- },
- "tileable": {
- "type": "boolean"
- },
- "physicalSizeMeters": {
- "type": "object",
- "properties": {
- "width": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100000
- },
- "height": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100000
- }
- },
- "required": [
- "width",
- "height"
- ],
- "additionalProperties": false
- },
- "parameters": {
- "type": "object",
- "properties": {
- "baseColor": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "roughness": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "metalness": {
- "default": 0,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "emissive": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "emissiveIntensity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 64
- },
- "alphaMode": {
- "default": "opaque",
- "type": "string",
- "enum": [
- "opaque",
- "mask",
- "blend"
- ]
- },
- "alphaCutoff": {
- "default": 0.5,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "doubleSided": {
- "default": false,
- "type": "boolean"
- }
- },
- "additionalProperties": false
- },
- "sources": {
- "minItems": 1,
- "maxItems": 20,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "kind": {
- "type": "string",
- "enum": [
- "external",
- "procedural"
- ]
- },
- "provider": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "creator": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "assetId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "assetUrl": {
- "type": "string",
- "maxLength": 2000,
- "format": "uri"
- },
- "accessedAt": {
- "type": "string",
- "format": "date-time",
- "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
- },
- "license": {
- "type": "object",
- "properties": {
- "spdx": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "url": {
- "type": "string",
- "maxLength": 2000,
- "format": "uri"
- },
- "attribution": {
- "type": "string",
- "maxLength": 4000
- }
- },
- "required": [
- "spdx",
- "url",
- "attribution"
- ],
- "additionalProperties": false
- },
- "originalFiles": {
- "maxItems": 20,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "bytes": {
- "type": "integer",
- "exclusiveMinimum": 0,
- "maximum": 1073741824
- }
- },
- "required": [
- "name",
- "sha256",
- "bytes"
- ],
- "additionalProperties": false
- }
- }
- },
- "required": [
- "id",
- "kind",
- "provider",
- "creator",
- "license",
- "originalFiles"
- ],
- "additionalProperties": false
- }
- },
- "maps": {
- "minItems": 1,
- "maxItems": 5,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "slot": {
- "type": "string",
- "enum": [
- "baseColor",
- "normal",
- "metallicRoughness",
- "emissive",
- "occlusion"
- ]
- },
- "sourceId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "transforms": {
- "maxItems": 30,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "operation": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "tool": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "version": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "parameters": {
- "type": "object",
- "propertyNames": {
- "type": "string",
- "maxLength": 100
- },
- "additionalProperties": {
- "anyOf": [
- {
- "type": "string",
- "maxLength": 2000
- },
- {
- "type": "number"
- },
- {
- "type": "boolean"
- }
- ]
- }
- }
- },
- "required": [
- "operation",
- "tool",
- "version"
- ],
- "additionalProperties": false
- }
- },
- "normalConvention": {
- "type": "string",
- "const": "opengl"
- },
- "channelPacking": {
- "type": "string",
- "const": "r-occlusion-g-roughness-b-metallic"
- },
- "procedural": {
- "type": "object",
- "properties": {
- "schemaVersion": {
- "type": "number",
- "const": 2
- },
- "size": {
- "default": 256,
- "type": "integer",
- "minimum": 4,
- "maximum": 1024
- },
- "usage": {
- "default": "albedo",
- "type": "string",
- "enum": [
- "albedo",
- "normal",
- "roughness",
- "metalness",
- "metallicRoughness",
- "emissive",
- "occlusion"
- ]
- },
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 80
- },
- "layers": {
- "minItems": 1,
- "maxItems": 8,
- "type": "array",
- "items": {
- "oneOf": [
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "solid"
- },
- "color": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "color"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "checker"
- },
- "colorA": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "colorB": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "squares": {
- "default": 8,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "colorA",
- "colorB"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "stripes"
- },
- "colorA": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "colorB": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "count": {
- "default": 8,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "angleDeg": {
- "default": 0,
- "type": "number",
- "minimum": -36000,
- "maximum": 36000
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "colorA",
- "colorB"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "gradient"
- },
- "from": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "to": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "angleDeg": {
- "default": 0,
- "type": "number",
- "minimum": -36000,
- "maximum": 36000
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "from",
- "to"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "bricks"
- },
- "brick": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "mortar": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "rows": {
- "default": 8,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "cols": {
- "default": 4,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "mortarWidth": {
- "default": 0.06,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "stagger": {
- "default": 0.5,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "brick",
- "mortar"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "noise"
- },
- "colorA": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "colorB": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "scale": {
- "default": 8,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "octaves": {
- "default": 3,
- "type": "integer",
- "minimum": 1,
- "maximum": 6
- },
- "seed": {
- "default": 0,
- "type": "integer",
- "minimum": -2147483648,
- "maximum": 2147483647
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "colorA",
- "colorB"
- ],
- "additionalProperties": false
- }
- ]
- }
- }
- },
- "required": [
- "schemaVersion",
- "layers"
- ],
- "additionalProperties": false
- },
- "derive": {
- "type": "object",
- "properties": {
- "kind": {
- "type": "string",
- "const": "normal-from-height"
- },
- "strength": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 64
- }
- },
- "required": [
- "kind",
- "strength"
- ],
- "additionalProperties": false
- }
- },
- "required": [
- "slot",
- "sourceId",
- "transforms",
- "procedural"
- ],
- "additionalProperties": false
- }
- }
- },
- "required": [
- "materialId",
- "name",
- "tileable",
- "sources",
- "maps"
- ],
- "additionalProperties": false
- }
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "shape:material-import",
- "name": "material-import",
- "summary": "The record kiln_material import takes: schemaVersion 1 and complete normalized material records, each a manifest plus base64 PNG files keyed by map name.",
- "family": "tool-input",
- "tags": [
- "schema",
- "kiln_material",
- "payload"
- ],
- "aliases": [
- "material import payload",
- "material records"
- ],
- "intents": [
- "import a material library payload"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "docs/projects-and-live-review.md"
- ],
- "limitations": [],
- "kind": "shape",
- "shape": {
- "tool": "kiln_material",
- "field": "payload",
- "schema": {
- "type": "object",
- "properties": {
- "schemaVersion": {
- "type": "number",
- "const": 1
- },
- "records": {
- "maxItems": 16,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "manifest": {
- "type": "object",
- "properties": {
- "schemaVersion": {
- "type": "number",
- "const": 1
- },
- "materialId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "revisionId": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "tags": {
- "maxItems": 30,
- "type": "array",
- "items": {
- "type": "string",
- "minLength": 1,
- "maxLength": 80
- }
- },
- "tileable": {
- "type": "boolean"
- },
- "physicalSizeMeters": {
- "type": "object",
- "properties": {
- "width": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100000
- },
- "height": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100000
- }
- },
- "required": [
- "width",
- "height"
- ],
- "additionalProperties": false
- },
- "parameters": {
- "type": "object",
- "properties": {
- "baseColor": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "roughness": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "metalness": {
- "default": 0,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "emissive": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "emissiveIntensity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 64
- },
- "alphaMode": {
- "default": "opaque",
- "type": "string",
- "enum": [
- "opaque",
- "mask",
- "blend"
- ]
- },
- "alphaCutoff": {
- "default": 0.5,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "doubleSided": {
- "default": false,
- "type": "boolean"
- }
- },
- "additionalProperties": false
- },
- "sources": {
- "minItems": 1,
- "maxItems": 20,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "kind": {
- "type": "string",
- "enum": [
- "external",
- "procedural"
- ]
- },
- "provider": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "creator": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "assetId": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "assetUrl": {
- "type": "string",
- "maxLength": 2000,
- "format": "uri"
- },
- "accessedAt": {
- "type": "string",
- "format": "date-time",
- "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
- },
- "license": {
- "type": "object",
- "properties": {
- "spdx": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "url": {
- "type": "string",
- "maxLength": 2000,
- "format": "uri"
- },
- "attribution": {
- "type": "string",
- "maxLength": 4000
- }
- },
- "required": [
- "spdx",
- "url",
- "attribution"
- ],
- "additionalProperties": false
- },
- "originalFiles": {
- "maxItems": 20,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "bytes": {
- "type": "integer",
- "exclusiveMinimum": 0,
- "maximum": 1073741824
- }
- },
- "required": [
- "name",
- "sha256",
- "bytes"
- ],
- "additionalProperties": false
- }
- }
- },
- "required": [
- "id",
- "kind",
- "provider",
- "creator",
- "license",
- "originalFiles"
- ],
- "additionalProperties": false
- }
- },
- "maps": {
- "minItems": 1,
- "maxItems": 5,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "slot": {
- "type": "string",
- "enum": [
- "baseColor",
- "normal",
- "metallicRoughness",
- "emissive",
- "occlusion"
- ]
- },
- "file": {
- "type": "string",
- "enum": [
- "baseColor.png",
- "normal.png",
- "metallicRoughness.png",
- "emissive.png",
- "occlusion.png"
- ]
- },
- "sha256": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "bytes": {
- "type": "integer",
- "exclusiveMinimum": 0,
- "maximum": 8388608
- },
- "width": {
- "type": "integer",
- "exclusiveMinimum": 0,
- "maximum": 4096
- },
- "height": {
- "type": "integer",
- "exclusiveMinimum": 0,
- "maximum": 4096
- },
- "usage": {
- "type": "string",
- "enum": [
- "albedo",
- "normal",
- "metallicRoughness",
- "emissive",
- "occlusion"
- ]
- },
- "colorSpace": {
- "type": "string",
- "enum": [
- "srgb",
- "linear"
- ]
- },
- "normalConvention": {
- "type": "string",
- "const": "opengl"
- },
- "channelPacking": {
- "type": "string",
- "const": "r-occlusion-g-roughness-b-metallic"
- },
- "sourceId": {
- "type": "string",
- "pattern": "^[a-z][a-z0-9_-]{0,79}$"
- },
- "originalFile": {
- "type": "string",
- "minLength": 1,
- "maxLength": 200
- },
- "transforms": {
- "maxItems": 30,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "operation": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "tool": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "version": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- },
- "parameters": {
- "type": "object",
- "propertyNames": {
- "type": "string",
- "maxLength": 100
- },
- "additionalProperties": {
- "anyOf": [
- {
- "type": "string",
- "maxLength": 2000
- },
- {
- "type": "number"
- },
- {
- "type": "boolean"
- }
- ]
- }
- }
- },
- "required": [
- "operation",
- "tool",
- "version"
- ],
- "additionalProperties": false
- }
- },
- "procedural": {
- "type": "object",
- "properties": {
- "compiler": {
- "type": "string",
- "const": "kiln.procedural-texture.v2"
- },
- "spec": {
- "type": "object",
- "properties": {
- "schemaVersion": {
- "type": "number",
- "const": 2
- },
- "size": {
- "default": 256,
- "type": "integer",
- "minimum": 4,
- "maximum": 1024
- },
- "usage": {
- "default": "albedo",
- "type": "string",
- "enum": [
- "albedo",
- "normal",
- "roughness",
- "metalness",
- "metallicRoughness",
- "emissive",
- "occlusion"
- ]
- },
- "name": {
- "type": "string",
- "minLength": 1,
- "maxLength": 80
- },
- "layers": {
- "minItems": 1,
- "maxItems": 8,
- "type": "array",
- "items": {
- "oneOf": [
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "solid"
- },
- "color": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "color"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "checker"
- },
- "colorA": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "colorB": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "squares": {
- "default": 8,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "colorA",
- "colorB"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "stripes"
- },
- "colorA": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "colorB": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "count": {
- "default": 8,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "angleDeg": {
- "default": 0,
- "type": "number",
- "minimum": -36000,
- "maximum": 36000
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "colorA",
- "colorB"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "gradient"
- },
- "from": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "to": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "angleDeg": {
- "default": 0,
- "type": "number",
- "minimum": -36000,
- "maximum": 36000
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "from",
- "to"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "bricks"
- },
- "brick": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "mortar": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "rows": {
- "default": 8,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "cols": {
- "default": 4,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "mortarWidth": {
- "default": 0.06,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "stagger": {
- "default": 0.5,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "brick",
- "mortar"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "op": {
- "type": "string",
- "const": "noise"
- },
- "colorA": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "colorB": {
- "type": "integer",
- "minimum": 0,
- "maximum": 16777215
- },
- "scale": {
- "default": 8,
- "type": "integer",
- "minimum": 1,
- "maximum": 256
- },
- "octaves": {
- "default": 3,
- "type": "integer",
- "minimum": 1,
- "maximum": 6
- },
- "seed": {
- "default": 0,
- "type": "integer",
- "minimum": -2147483648,
- "maximum": 2147483647
- },
- "blend": {
- "default": "normal",
- "type": "string",
- "enum": [
- "normal",
- "multiply",
- "screen",
- "overlay"
- ]
- },
- "opacity": {
- "default": 1,
- "type": "number",
- "minimum": 0,
- "maximum": 1
- }
- },
- "required": [
- "op",
- "colorA",
- "colorB"
- ],
- "additionalProperties": false
- }
- ]
- }
- }
- },
- "required": [
- "schemaVersion",
- "layers"
- ],
- "additionalProperties": false
- },
- "derive": {
- "type": "object",
- "properties": {
- "kind": {
- "type": "string",
- "const": "normal-from-height"
- },
- "strength": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 64
- }
- },
- "required": [
- "kind",
- "strength"
- ],
- "additionalProperties": false
- },
- "recipeHash": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "pixelHash": {
- "type": "string",
- "pattern": "^sha256:[a-f0-9]{64}$"
- },
- "encoder": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string",
- "const": "sharp"
- },
- "version": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1000
- }
- },
- "required": [
- "name",
- "version"
- ],
- "additionalProperties": false
- }
- },
- "required": [
- "compiler",
- "spec",
- "recipeHash",
- "pixelHash",
- "encoder"
- ],
- "additionalProperties": false
- }
- },
- "required": [
- "slot",
- "file",
- "sha256",
- "bytes",
- "width",
- "height",
- "usage",
- "colorSpace",
- "sourceId",
- "transforms"
- ],
- "additionalProperties": false
- }
- }
- },
- "required": [
- "schemaVersion",
- "materialId",
- "revisionId",
- "name",
- "tags",
- "tileable",
- "parameters",
- "sources",
- "maps"
- ],
- "additionalProperties": false
- },
- "files": {
- "type": "object",
- "propertyNames": {
- "type": "string",
- "pattern": "^(baseColor|normal|metallicRoughness|emissive|occlusion)\\.png$"
- },
- "additionalProperties": {
- "type": "string",
- "maxLength": 11184812
- }
- }
- },
- "required": [
- "manifest",
- "files"
- ],
- "additionalProperties": false
- }
- }
- },
- "required": [
- "schemaVersion",
- "records"
- ],
- "additionalProperties": false
- }
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "shape:capture",
- "name": "capture",
- "summary": "The capture record kiln_render, kiln_edit and kiln_view_interior take: either preset/cells/backdrop for an orbit sheet, or kiln.capture.v1 or v2 with 1 to 9 shots, cols, size, output and backdrop; v2 shots may hide nodes.",
- "family": "tool-input",
- "tags": [
- "schema",
- "kiln_render",
- "capture"
- ],
- "aliases": [
- "capture config",
- "camera sheet",
- "exact cameras",
- "orbit grid"
- ],
- "intents": [
- "choose cameras for a render",
- "render exact orthographic or perspective views"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "docs/cameras.md"
- ],
- "limitations": [],
- "kind": "shape",
- "shape": {
- "tool": "kiln_render",
- "field": "capture",
- "schema": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "version": {
- "type": "string",
- "enum": [
- "kiln.capture.v1",
- "kiln.capture.v2"
- ]
- },
- "shots": {
- "minItems": 1,
- "maxItems": 9,
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string"
- },
- "subject": {
- "type": "object",
- "properties": {
- "path": {
- "type": "string"
- },
- "name": {
- "type": "string"
- }
- },
- "additionalProperties": false
- },
- "visibility": {
- "type": "string",
- "enum": [
- "context",
- "isolate"
- ]
- },
- "hide": {
- "maxItems": 64,
- "type": "array",
- "items": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1024
- }
- },
- "camera": {
- "oneOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "orbit"
- },
- "azimuthDeg": {
- "type": "number"
- },
- "elevationDeg": {
- "type": "number"
- },
- "relativeTo": {
- "type": "string",
- "enum": [
- "world",
- "asset",
- "part"
- ]
- },
- "padding": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "explicit"
- },
- "projection": {
- "type": "string",
- "enum": [
- "orthographic",
- "perspective"
- ]
- },
- "position": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "target": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "relativeTo": {
- "type": "string",
- "enum": [
- "world",
- "asset",
- "part",
- "local"
- ]
- },
- "frame": {
- "type": "object",
- "properties": {
- "origin": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "rotation": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- }
- },
- "additionalProperties": false
- },
- "framing": {
- "type": "string",
- "enum": [
- "explicit",
- "bounds"
- ]
- },
- "padding": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100
- },
- "targetOffset": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "up": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "halfHeight": {
- "type": "number",
- "exclusiveMinimum": 0
- },
- "fovDeg": {
- "type": "number",
- "exclusiveMinimum": 0,
- "exclusiveMaximum": 180
- },
- "near": {
- "type": "number",
- "exclusiveMinimum": 0
- },
- "far": {
- "type": "number",
- "exclusiveMinimum": 0
- }
- },
- "required": [
- "type",
- "projection",
- "position"
- ],
- "additionalProperties": false
- }
- ]
- }
- },
- "additionalProperties": false
- }
- },
- "cols": {
- "type": "integer",
- "minimum": 1,
- "maximum": 3
- },
- "size": {
- "type": "integer",
- "minimum": 128,
- "maximum": 2048
- },
- "output": {
- "type": "string",
- "enum": [
- "grid",
- "separate"
- ]
- },
- "backdrop": {
- "description": "neutral (default); light for dark parts, dark for light parts.",
- "type": "string",
- "enum": [
- "neutral",
- "dark",
- "light"
- ]
- }
- },
- "required": [
- "version",
- "shots"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "preset": {
- "description": "COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3.",
- "type": "string",
- "enum": [
- "1x1",
- "1x2",
- "2x1",
- "3x1",
- "2x2",
- "3x2",
- "3x3"
- ]
- },
- "cells": {
- "description": "Row-major cameras; omit for preset defaults. Count cannot exceed preset capacity (max 9).",
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "azimuthDeg": {
- "type": "number",
- "description": "0 = front, 90 = right, 180 = back, 270 = left. Wraps."
- },
- "elevationDeg": {
- "type": "number",
- "description": "0 eye level; positive above, negative below. Clamped -89..89."
- },
- "zoom": {
- "description": "Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing.",
- "type": "number"
- },
- "name": {
- "description": "Label; defaults to angles.",
- "type": "string"
- }
- },
- "required": [
- "azimuthDeg",
- "elevationDeg"
- ]
- }
- },
- "backdrop": {
- "description": "neutral (default); light for dark parts, dark for light parts.",
- "type": "string",
- "enum": [
- "neutral",
- "dark",
- "light"
- ]
- }
- },
- "additionalProperties": false
- }
- ]
- }
- }
- },
- {
- "version": "kiln.catalog-entry.v1",
- "id": "shape:camera-shot",
- "name": "camera-shot",
- "summary": "One shot, as kiln_inspect shot and kiln_screenshot_animation shot take it and as capture.shots lists it: optional name, subject (path or exact name), visibility, hide, and an orbit or explicit camera.",
- "family": "tool-input",
- "tags": [
- "schema",
- "kiln_inspect",
- "shot"
- ],
- "aliases": [
- "camera shot",
- "explicit camera",
- "orbit camera"
- ],
- "intents": [
- "frame one part with an exact camera"
- ],
- "stability": "stable",
- "related": [],
- "references": [
- "docs/cameras.md"
- ],
- "limitations": [],
- "kind": "shape",
- "shape": {
- "tool": "kiln_inspect",
- "field": "shot",
- "schema": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string"
- },
- "subject": {
- "type": "object",
- "properties": {
- "path": {
- "type": "string"
- },
- "name": {
- "type": "string"
- }
- },
- "additionalProperties": false
- },
- "visibility": {
- "type": "string",
- "enum": [
- "context",
- "isolate"
- ]
- },
- "hide": {
- "maxItems": 64,
- "type": "array",
- "items": {
- "type": "string",
- "minLength": 1,
- "maxLength": 1024
- }
- },
- "camera": {
- "oneOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "orbit"
- },
- "azimuthDeg": {
- "type": "number"
- },
- "elevationDeg": {
- "type": "number"
- },
- "relativeTo": {
- "type": "string",
- "enum": [
- "world",
- "asset",
- "part"
- ]
- },
- "padding": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "explicit"
- },
- "projection": {
- "type": "string",
- "enum": [
- "orthographic",
- "perspective"
- ]
- },
- "position": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "target": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "relativeTo": {
- "type": "string",
- "enum": [
- "world",
- "asset",
- "part",
- "local"
- ]
- },
- "frame": {
- "type": "object",
- "properties": {
- "origin": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "rotation": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- }
- },
- "additionalProperties": false
- },
- "framing": {
- "type": "string",
- "enum": [
- "explicit",
- "bounds"
- ]
- },
- "padding": {
- "type": "number",
- "exclusiveMinimum": 0,
- "maximum": 100
- },
- "targetOffset": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "up": {
- "minItems": 3,
- "maxItems": 3,
- "type": "array",
- "items": {
- "type": "number"
- }
- },
- "halfHeight": {
- "type": "number",
- "exclusiveMinimum": 0
- },
- "fovDeg": {
- "type": "number",
- "exclusiveMinimum": 0,
- "exclusiveMaximum": 180
- },
- "near": {
- "type": "number",
- "exclusiveMinimum": 0
- },
- "far": {
- "type": "number",
- "exclusiveMinimum": 0
- }
- },
- "required": [
- "type",
- "projection",
- "position"
- ],
- "additionalProperties": false
- }
- ]
- }
- },
- "additionalProperties": false
- }
- }
- }
- ]
-}
diff --git a/hosting/src/github.ts b/hosting/src/github.ts
deleted file mode 100644
index e1874f59..00000000
--- a/hosting/src/github.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';
-import { HttpFailure, readBounded, sha256 } from './http';
-
-export interface GitHubEnv {
- GITHUB_CLIENT_ID: string;
- GITHUB_CLIENT_SECRET: string;
-}
-
-async function upstreamJson(url: string, init: RequestInit): Promise<Record<string, unknown>> {
- const response = await fetch(url, {
- ...init,
- redirect: 'manual',
- signal: AbortSignal.timeout(10_000),
- });
- if (!response.ok) {
- void response.body?.cancel().catch(() => {});
- throw new HttpFailure(502, 'Sign-in provider unavailable; restart sign-in');
- }
- const value: unknown = JSON.parse(
- new TextDecoder().decode(await readBounded(response.body, 32_768)),
- );
- if (!value || typeof value !== 'object' || Array.isArray(value))
- throw new HttpFailure(502, 'Invalid sign-in response');
- return value as Record<string, unknown>;
-}
-
-export async function githubIdentity(
- code: string,
- verifier: string,
- origin: string,
- env: GitHubEnv,
-): Promise<VerifiedIdentity> {
- const token = await upstreamJson('https://github.com/login/oauth/access_token', {
- method: 'POST',
- headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- client_id: env.GITHUB_CLIENT_ID,
- client_secret: env.GITHUB_CLIENT_SECRET,
- code,
- code_verifier: verifier,
- redirect_uri: `${origin}/oauth/github/callback`,
- }),
- });
- if (
- typeof token.access_token !== 'string' ||
- !token.access_token ||
- token.access_token.length > 4096 ||
- typeof token.token_type !== 'string' ||
- token.token_type.toLowerCase() !== 'bearer'
- ) {
- throw new HttpFailure(400, 'Sign-in failed; restart sign-in');
- }
- const user = await upstreamJson('https://api.github.com/user', {
- headers: {
- accept: 'application/vnd.github+json',
- authorization: `Bearer ${token.access_token}`,
- 'user-agent': 'Kiln-Instrukt-Labs',
- 'x-github-api-version': '2026-03-10',
- },
- });
- if (typeof user.id !== 'number' || !Number.isSafeInteger(user.id) || user.id <= 0) {
- throw new HttpFailure(502, 'Invalid sign-in identity');
- }
- // Immutable provider id, never a mutable login or email. Upstream tokens are
- // discarded here; the account directory owns the provider-neutral subject.
- return { issuer: IDENTITY_ISSUERS.github, subject: String(user.id) };
-}
-
-export async function githubAuthorizationUrl(
- origin: string,
- state: string,
- verifier: string,
- env: GitHubEnv,
- selectAccount = false,
-): Promise<string> {
- const target = new URL('https://github.com/login/oauth/authorize');
- target.search = new URLSearchParams({
- client_id: env.GITHUB_CLIENT_ID,
- redirect_uri: `${origin}/oauth/github/callback`,
- scope: '',
- state,
- code_challenge: await sha256(verifier),
- code_challenge_method: 'S256',
- ...(selectAccount ? { prompt: 'select_account' } : {}),
- }).toString();
- return target.href;
-}
diff --git a/hosting/src/google-button.ts b/hosting/src/google-button.ts
deleted file mode 100644
index 5c74dd16..00000000
--- a/hosting/src/google-button.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-// Unmodified pre-approved Google sign-in PNG. See ../assets/README.md.
-export const GOOGLE_SIGN_IN_BUTTON =
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWgAAABQCAYAAAA0u++hAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAOdEVYdFNvZnR3YXJlAEZpZ21hnrGWYwAAFvJJREFUeAHtnQusHNV5x/8zu9f3jW3CwxhMXCAtYGNIyyutgeImNEVqcCmV3FKlBaVWKSK4kWncqAIDbepQh0chTWpVpEJIcVpSILQUTNW42CY0hcoYcB5gc3nZIAVf36fvY3cm3392v/VhsrOP67t7Z6+/n3U8OzszZ+fMnPOfb77znXM9xFi7bt2v+2FwVQisDBEuhmEYhtEwPGCnLHZmvMztGzZs6IttK7B+/fp5w4dGbwPCNTAMwzCajg/v3q7OrttFjw9yPRJoivPIoZHvidV8XkdHBy5ZfglOP+10SafBMAzDaBz79u3Dth3b8cKLL0TrtKi7O7svp0hn+MX5F134t7JYOX/+fHz+xpuwdMkSHCufDcMwjMbS29sbae4Fv3I+Xtn9Kg6NjS3I5XIdO3bseNpbt27d4lyYf4M7fumLf4n5JsyGYRgzQn9/P+657x6KtJjS4eV+Pszfxg3ni3qbOBuGYcwc1ODl4mImXuit9Ol35solv7YchmEYxszC/r8iV/koCvTChQthGIZhzCwanCHG82IfhmEYRioxgTYMw0gpJtCGYRgpxQTaMAwjpZhAG4ZhpBQTaMMwjJRiAm0YhpFSTKANwzBSigm0YRhGSjGBNgzDSCkm0IZhGCnFBNowDCOlZJFWdu1E+NJLwN49CPe8Dm9kBBgeKmzr6QEWLAC6ZXnOefDOPQ9YtgyGYRiziXQJ9PvvIXzmaYT/9h1gZBie5yEMw5/fb3gY2LMXsoMI+SsIv7VZBPtkEetl8K5dBZxwPAzDMFqddAi0iHH4T/cj3PI0EPjRPHvkQ9JMMaZY6zLawYeXaUPotcH76SDC7z0HbP1f4DcuBVZdLUJ9HAzDMFqVGRfo8KnNCDd/ExgYFY+4XxDfsPjHxl3ruSTKFGk/Sl5mjqxLEfz2SKQLLnXZ/l//A7z0MvD7vwN8cgUMwzBakZkV6G9vBJ7cDG9CTiOTQRgUreNIi71CKgoz//c8Z7sv+4uQex6LkJE9uS0vKSdpEtj/FnD3PeI22Qdc+4cwDMNoNWYmimNsEPiHP0b47ENAWyCPiTy8bCAWMa3jsKTNCoU5EudoxS9Y2kEk2WI5yzYKczAhacxJ44W05anIhWIYhtFqzIwF/dAfAO+8BrRnCtZwyM5AEeq8CHVQ7BgMcNgXLeslgY4saNnoc11EPZgsZpovWtDFxINPPBG4a2Mh2sMwDKPFaL5Ab7sNGNwFdGaL/X1ewedMQaa2BsV1psiS9orWchF+pyJNcfbyhe8jYS6qOpcnLhBx/mphaRiG0YI0V6D3fgt4/eti0WYLzpXIKC66NCKRprvCF33NR995vXPhfeYaYNm5wOmnH7aE6bLYsyeKkcajj0bheQVhDgtLxkjfdbeJs2EYLU3zBPqQdNrt+bKIrFi99DX7heRJiuzjotUcBj68jywEfvdz8Fb8Vvm8KNQUbaaVVwPPbAEe/mfgvfeKlnO6xPmdd97B888/Hy3J2WefHaVTTjkl8ZgtW7ZgcHAQF198ccX90oaWs9XOO4lWLo+eu9Y7nj8Ty2K0Bs0T6DfvlP/E4u0Sv3NWJDkTlIQ6GpAinX+BCLS/bAW869bLfr215/2pKwojCb/+NeCGG1MjzmwYa9eujRpKOa6//nqsWbMGxxxzzIe+v+OOO/Dggw9Gn9mgnnzyyZ/bJ43wobJ69erS+ubNm1taDO69994okSO5D8uXLy+J5Pbt2xsq9Hyos+4w8XM5+PvXXHNNlGbDQ7QabH+rVq2KPrM+sl62Cs2J4hh/E+h/COgQUe4S90VXDugRS7p3QpYTCHpzyPXkEV66Et6NX61PnBWK8vo7UyXOrBRJ4kzYiLhPvCFR6Nx8tHGnnXhZK5W9Fah2H7j+yCOPRCkNZWV94sOAD5UkcSY8b+7DuueW0UgfzbGg9/914ZcYQucXLWexosOsh8D3kZP13PFL0X31nZgtsPJrg6bVRWuFbg02nN27d0eNmvAzG8utt95aOpZWTfy1tBVg+Sqttxq0tnh/SLn7oG9Iuu9MWmauta/wnNSdxnrH86Uga93ikm88fDNo9Xs1W2mOQI9sE1H2igJN9wZ/OUAoYp0T98ZY+0fQu+IBzBZcfzNhwy0nXnRlEIq1K9CbNm0qvaJS2FvBvUF4roTlpzhcccUVaGXofuJ9YnnojkrrfWBdccWZ58z6VM69xO9Z37g/66iW0UgnjRfoYRHnybcKg0sigUYhbM6PgjYwjjnwF62G33MyZguuOFOkyjUANnjtfIo3JAoBG04ror7N2YC++aS5PKxD+qAnPNeNGzdWPIb7sM7RmmY9NNJL4wV6ZHth9F9h4F9xpKC4N3wPebRhrK0Tx56yErOVSr5A12qOH6Ov1hSJJAuHlp2+svIY7scHggq++kXjeTBvPS9+z+2al/4uv2fjrde94vpi3QdPuWgC9eHq+cTPvxrudYr/notb3iSXkXt+er2S7oPm5/42192y63VNgvuy7PxN7qdvHPVeb9dy5rHVxNndtx5xZvn0Xuk5M49671c8D16nWjsreTzrqL6hxq+bew+rXf9GlXG68dZ+8ZYoyu3vNtyFhtB3rZT8icMCrXNrhOLayHVivOf3MO/M2t0bf/PERCl02pMPhaT5FoZ+h8VlEG0tDkik0S4PhsJI8hAL5nq4/rI2NAK315hQiOtpDKwk6tssZxGxIrFhaqRHHB7D37vyyiuj9bh/1O28pP+R+ahPPE6957548eLS576+vtJn10fK8rAMruXnwt9Leni5MI9lzjzg5SIk2NDYcabwzaTc2wl9sdphpr/v3gf3GrpRGUm4ESzxKI6kyB4KAq9Nra6hePkbFTWjdS3J2OD58noliWy1+kpYZ3lfkvLg9eJ1K3fded34+/rQI+61qCWKQ91ESWWsdn7TzS3r/iJaNt6CnnwbkT9D59YoDk4J5bvQz6Bt7oWoh0dfyRZ0vpCNO2UHgMNTlOrkSqXnAlAScn7b2yEN8TI0BHVbaCOkEPGprK+WRworm2u9xVEroBZYKSv15PPctbNpumBjqHR+3F6LhacWlF7ncq/scSHktSkn0O5+jfSdVwq7pDhwOx+atQiBm0+j4pt5PkkPb0XfvCh88fNmmarVV6KRMOXy4LGuwRNHr9tUxTPewcp6xcR8VbD1/Jod8tr4MDsKtE5w5OksSH5xFLeHOd1n1pObWMW+uEb8aBlIvvlYCoopiqsu2teBY2sXjsng4HgGQ2NoGLSE3ArDG8xKRmsqyRKoBVYkt7JTkGiV0Vrlkr/LClSrQLNxqeW2a9euKGkeSiXLZyrouVEoec78zXjDjEckJOGKUrkHTfy7cuFybHiuC6Sa0NFa4zVyHwZ8gPE7TZUsQW5jeVlult99YGgccy2497gRHX28B64408DQ86ZQueXUsNK4BarGicJrxmNZX7l0y+5GxbjfubH16sbhOTAPno/2EUylTWnIoaJ1sly9jO/bDBpvQecGnPkz9MvCnM6+x1nsphDzHKNkUVehZEUXPw+NI7KkG4E2wngld2Nn631tUh+ZEn9d1wEIbKzlGksScYtNK7w2lkbE+MZdJ/rqqe4IDQurdm14rtpo1DfsPlzKiXbcinb3qcUKVQub10XFVDsUq6H1QsvldghrOXg+tbh4XEGqJNAqntVQV4UeExcu95pp+B6vF11per94PXQ/resKhdW9RpoHf1frK6+pRgERNyIqfu2Ivq3yOk7FkHAfCOXcX1ovtYxavmZZ0U0YqFKcvEjnySilABlMwp+iQLsek6DGfXWlFjGfDvRpz6dxuQ43Vl7e+Fqt3XhlTYr00A6+WkjqoHFf86d7oEyS+4Lfu0JTy++6nX7xjjtXeCk82qgqDahpdMRGUkeg+7uNGJikbw6Vknvt4i6fpLrGsrgPE/c4V+ArRcPE66srtHGDJOmBPRXR1CkYtByVyuieezMH9zTegs6IAOcPlszXaOrQaEPB+YDRXcCc+n1HoeaHw9NHJwlvGDuuVot7utBK7HZkaMVTHx1FvFoFcxtQNT9prf7IpHwaaSFUOvep/K5rRbPxaNndhsR9NAJAXRr8LVeYmjFPRZJITcV/6h5TTdQrdeCVe9Nyr121usbt6rONX1ul2oPPvYeuyNfaN6ARIfW87cWjcCq9ZbhlqdWgmg4aL9C+CHTuwIdcHEEYRt2EAb3DE2/UZ8YXFbn0pwm9w1/XeGipg7G3HU1HX8mY6J/TBkLBrmb1ug2pWoOutcHPxOCL6f7NuB9aLTptrPoKTBHQ7/R6J4UFNorpLLv7tlFJmFgXaACUw50/xT23euqa26mmx8YFup76muSaq3bt6n3IVQqTrEStrsPpoPEC3bEUGH8jEuQwLMxcx3EqefnEFBx8HL0n3Fh7fp7+CSyvfAiHV+XQ4nb6nhvlf1Yq+VApFq6fT0erVSKpAZWjmZVoplEBVj+om4hab64FphEfcSu7lYiX2/Xd1kq9/vc0U2+dd9tTuQFjSTTzOjVcoMOe5QgPPlb0PIfIUZxFqPl3UCaYRv4f3eIC8TPzasrv3/+M/3tV9/vurhCbSkaDV5pyWi3ohbX93JSgD01Djyq5LlwLqJbK5eZT7WnfzNewNEBxVd+lO+CGaINyw/L0VdwdzNNqAsVz5kNH3WUaolerlR7vxHMfYK5hwWtZ6drEI2P0WHdOGeZRycJNikhx86j2AKq3zsevUxpH7za+k7BjmQhygMkgj/EgwJh8HhGBHpLlgKx/kOvHu+/dV3N2C+d6klA17RssuFBCr+BMCUuPiDByj/zSiWgIGpSvAlApLKfeziC3AcXn+4jT7HCgmSZuHbvuDVcY3P3UxRT/vpVwO8d02HctD/u4zzXeWewKYaVBKsQVefe4eB6VcLe7Au3el0p56KjMenDz1tGDSZQLz2wGDRdor/cyTPhzMS6fR0WYC+IcYkDSAUk/Fd18af/9GBrvw3Tx7mCAR3ePI5/JIe/lEPicmCksinXh3/mnoiGwscR7pMtVLA1JUmoN0XIrvTtjnsKGRJ/iTFSmmURf94n78IpfV3c9yXqcCu5w8mYSjz7QyKBKb1jcxn3coe1x61E7/ogKfzl04iXFvb7uBFP8zSSjIR6K6p5L/MFbLg/mnXR+lXDfmrTdlLuHGqbIENB6wleng+bMZnfCTRjed7u4NDyxoEOMgmINDMlySJYDuQH8x+ursWrJ9ISv3Pf8MCayOXF2+8iGWfhhRvzfGXka6fPIxy+fWt1NMlVYMd0nOiuPG12gr9hKPdEDDNtz405ZadRKjPeiH01+aOK6OZRyE1G5ow/1u6kIdNxFxfvCvHWWuGa5TFjf3Lc1FRSdR8IV2nJvXuUG1ujgJe1A1JF0rujG58GOh9Kp8Kt4qhBrHu7cGko8lI7XkPvrfdU8dK4NPhjd+VLqrfNue2I+/Mzfc+dicd8g4nH2jaYpAt154s14+93bI3E+JOsjxTQkTuHB0I/S3oHvY+K1m/DZj92PI2HTywfw8Ov9yLS1oS1oQ15SNsgiI4ki7UlacQbdII17eeANZHC7a+HGRdndl9OL1toDrcH6rpUczzfeuI4WKEbxV+WkGO/piN7QtyX9zbhPt5mosOk0ono+ldwCGqefVH6Nf3aFP8lSZR7lBteUe3gk5aEDt+Jovu51jj9k1Eip9/pre1LLuNL5cV+21WbSlL+owg7ArgU3Y0A+HwyZPPQHkkSY+wOmrLg82vDU+4/izt03Yv/YPkyFr/3wbdzyfz/BWNsQJttGxIo+hFx2DJMZpnHk/EnkJV17fuOLrTe+kuuClWoqk6Vzf83bfZqrdXi0TsDuujlI0rWPW8tH4t6odzKpRqJDsauNTlXLlvWk2sOJ+5WbzzyeF/dJsiy5vdLwd53sqNJMfLo9fr46xuBI/lgCy8ZrkVRf3Os1lXj1I6Hxs9kVyeUP4pmdp4k74yCGRaCHxd0xLAI9JMLMNBh2yrJblj3omfOLuO6jq3H1SZ+sKe83R4fwJz/4AbbtH4E32SXWcifach2y7EA2P0cs6XZk8lmxpOdgUc8c/Pfnmhv7q69K8QER0/Wq5I4uVNwZvChAzX7yH23oPdYpKpv5GpyEdnzFp1Gd6sNb89OIDB35WU9ZtR1oCOpUBge5g2vcOu/O0jjVmf20fDrdqBo9zb6fOptd0wSa/HD/32Pbm38u7g0RZrGgR8TDQnEeRoesd4pg98h6IY1KOr59Ea456XL86vyzcU7PqZib7YryGciN4q3RA3j2QB+e2P8Gtr7/AcK8XMB8jzwJRKDzTO0izhTo9kikMyLOWXF37PijBTj5mAxaGZ27udJ8De4sZGmy8gyjXnQgV6X5Tiio6ksm7lS3rUjzpht1OOukz2P/eJ9Yug9EIj0i/uBRtOGQiOdY2CGpHeOSJiXlpHOvb+wDbNj7GAJ815lnyYtOO5RjArGQw6Abnt8t/uUx2SbFyWSime4KB3ilQ8J8iC9cOK/lxdmdt5iUE2n3bx6SVv/TU8bRC40Rja5Qa7acm8HtyJstf9GHNFWgyYrFd+PHw6/g1cHv41A4RzoN26M0hoI4809gTcpp5TidaEhf8eFx3V5xutIwmlAjL+scizgpAp2DF0wg9MdlmxRJhD+f8Yt/yaUwJ/TSY9vxhQsaODqlSeifKiKslKzAGgvr9jortf61CsNII+pCUbcGrWTWaTU6tGM2HgkyW2iqi0M5lBvAV17+bfx45DVxZXRI6pLULRZ1V5TGxB89IeKdE+s6mts5Elm1oSnWfmQth+KyCMQ1EgRdYiF3IxAXR5jn504RbEl5+qHb8QtdvfjPTy/FqeJ/ng2wl7mWqRW1MzEN/lDDmCoaNlhLbH/SX8xpNdTF0ZQojjid2blY//Fn8amFfyoWczsmxGoeF190JMqyzCNTnJTf07+QFeG5szl7HCUYRFZ0NK+0Nwnfn5ASTcDL0JqWJMulx7Vjx2eWzRpxJtqjXalXvFrPumG0CrVGRGkEy2xiRixol6ffexzf6Psm9o4NiMujS1JHJNiTYiFzxmh3ljoPBUs6WkaDT2hFt8uyM7KcA7Gcw0CXHbjpjKW4++PLMJvhq507Uf10R4gYRprQKAs3IupIIlPSyox0EpbjNxdchXPmXYQH+h7G5n3PRtYzfc+hY9yrMIeOXHteceJ/j9P1iy/aEz+0PyliPYnLTliEvzrzQlx2/ALMduqZhcswWh0NzTtaOr5nXKDJwo4F+PKZa3HD4s9i4xvfwbP9P0HfoQOl7SrMXmmqfxQngw4KnYVhHvPbsljaczK+9LEVuPS4RTAMw2h1UiHQyqKOE3DfWTdEn7f3/wjbJO04+CMczI3i7bEPMDA5GvURzst24ZhMN87p/ShObT8ey+efhUuOPQNzs50wDMOYLaRKoF2Wzz8zSoZhGEcrMxLFYRiGYVTHBNowDCOlmEAbhmGkFBNowzCMlGICbRiGkVJMoA3DMFKKCbRhGEZKMYE2DMNIKSbQhmEYKcUE2jAMI6WYQBuGYaQUE2jDMIyU4nvw+vhhz969MAzDMGaWffv3RUvR5p1+gPBxruzduweGYRjGzLJt+/bCBy/c6Xte+Fj05Y7tONB/AIZhGMbMQA1+4cUXos8ZZG7PPLf9ub5PLP/E/Fwuf/Gru1/FkiVL0NlpE98bhmE0E4rzNzb9I8bGxvh3Se676yt3bc5ww0UXXPS8n818WjYs2C6WdH9/P46dPx+9vb0wDMMwGgf7/14Uq/nb//ovGB4epjjv7O7svm7r1q1jnu60Zs2aeZn2zHoP/s0wDMMwmg4tZxHn9cLB4vqHWbdu3eIccusReufK6nkwDMMwGobneX0Iw8dD6Q/cuGHjVnfbzwDasyDjaUgtnwAAAABJRU5ErkJggg==';
diff --git a/hosting/src/google.ts b/hosting/src/google.ts
deleted file mode 100644
index 82932b59..00000000
--- a/hosting/src/google.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-import * as oauth from 'oauth4webapi';
-import { IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';
-import { HttpFailure, readBounded } from './http';
-
-export interface GoogleEnv {
- GOOGLE_CLIENT_ID: string;
- GOOGLE_CLIENT_SECRET: string;
-}
-
-/** Values retained server-side for one browser-bound, single-use login intent. */
-export interface GoogleFlow {
- state: string;
- verifier: string;
- nonce: string;
- selectAccount?: boolean;
-}
-
-const issuer = new URL(IDENTITY_ISSUERS.google);
-const unavailable = () =>
- new HttpFailure(502, 'Google sign-in provider unavailable; restart sign-in');
-const failed = () => new HttpFailure(400, 'Google sign-in failed; restart sign-in');
-
-function configuration(origin: string, flow: GoogleFlow, env: GoogleEnv): oauth.Client {
- if (
- new URL(origin).protocol !== 'https:' ||
- new URL(origin).origin !== origin ||
- !env.GOOGLE_CLIENT_ID ||
- env.GOOGLE_CLIENT_ID.length > 512 ||
- !env.GOOGLE_CLIENT_SECRET ||
- env.GOOGLE_CLIENT_SECRET.length > 4096
- )
- throw new HttpFailure(503, 'Google sign-in is not configured');
- if (
- !flow.state ||
- flow.state.length > 4096 ||
- !/^[A-Za-z0-9._~-]{43,128}$/.test(flow.verifier) ||
- !/^[A-Za-z0-9_-]{32,128}$/.test(flow.nonce)
- )
- throw failed();
- return { client_id: env.GOOGLE_CLIENT_ID, id_token_signed_response_alg: 'RS256' };
-}
-
-function endpoint(value: unknown, origin: string): string {
- if (typeof value !== 'string') throw unavailable();
- const url = new URL(value);
- if (url.origin !== origin || url.username || url.password || url.hash) throw unavailable();
- return url.href;
-}
-
-type GoogleHttpOptions = oauth.HttpRequestOptions<'GET' | 'POST', URLSearchParams | undefined>;
-
-function network(signal?: AbortSignal): GoogleHttpOptions {
- const deadline = AbortSignal.timeout(10_000);
- const execution = signal ? AbortSignal.any([signal, deadline]) : deadline;
- return {
- signal: execution,
- [oauth.customFetch]: async (url, options) => {
- try {
- const target = new URL(url);
- // The discovery document and provider endpoints are selected by this
- // adapter, never by callback input. Refuse redirects and non-Google I/O.
- if (
- ![
- 'https://accounts.google.com',
- 'https://oauth2.googleapis.com',
- 'https://www.googleapis.com',
- ].includes(target.origin)
- )
- throw unavailable();
- const response = await fetch(url, { ...options, redirect: 'manual', signal: execution });
- if ((response.status >= 300 && response.status < 400) || response.status >= 500) {
- void response.body?.cancel().catch(() => {});
- throw unavailable();
- }
- const bytes = await readBounded(response.body, 65_536, execution);
- return new Response(bytes, { status: response.status, headers: response.headers });
- } catch {
- throw unavailable();
- }
- },
- };
-}
-
-async function metadata(options: GoogleHttpOptions): Promise<oauth.AuthorizationServer> {
- try {
- const response = await oauth.discoveryRequest(issuer, options);
- const server = await oauth.processDiscoveryResponse(issuer, response);
- endpoint(server.authorization_endpoint, 'https://accounts.google.com');
- endpoint(server.token_endpoint, 'https://oauth2.googleapis.com');
- endpoint(server.jwks_uri, 'https://www.googleapis.com');
- return server;
- } catch {
- throw unavailable();
- }
-}
-
-export async function googleAuthorizationUrl(
- origin: string,
- flow: GoogleFlow,
- env: GoogleEnv,
- signal?: AbortSignal,
-): Promise<string> {
- const client = configuration(origin, flow, env);
- const server = await metadata(network(signal));
- const target = new URL(server.authorization_endpoint!);
- target.search = new URLSearchParams({
- client_id: client.client_id,
- response_type: 'code',
- redirect_uri: `${origin}/oauth/google/callback`,
- scope: 'openid profile',
- state: flow.state,
- nonce: flow.nonce,
- code_challenge: await oauth.calculatePKCECodeChallenge(flow.verifier),
- code_challenge_method: 'S256',
- ...(flow.selectAccount ? { prompt: 'select_account' } : {}),
- }).toString();
- return target.href;
-}
-
-export async function googleIdentity(
- request: Request,
- origin: string,
- flow: GoogleFlow,
- env: GoogleEnv,
-): Promise<VerifiedIdentity> {
- const client = configuration(origin, flow, env);
- const callback = new URL(request.url);
- if (
- request.method !== 'GET' ||
- callback.origin !== origin ||
- callback.pathname !== '/oauth/google/callback'
- )
- throw failed();
- const options = network(request.signal);
- const server = await metadata(options);
- try {
- const parameters = oauth.validateAuthResponse(server, client, callback, flow.state);
- const response = await oauth.authorizationCodeGrantRequest(
- server,
- client,
- oauth.ClientSecretPost(env.GOOGLE_CLIENT_SECRET),
- parameters,
- `${origin}/oauth/google/callback`,
- flow.verifier,
- options,
- );
- // Google documents both issuer spellings. Each goes through the complete
- // library validator; no JWT is decoded or modified by Kiln. The resulting
- // account key is always the canonical HTTPS issuer.
- let verified: oauth.TokenEndpointResponse | undefined;
- for (const acceptedIssuer of [server.issuer, 'accounts.google.com']) {
- const attempt = response.clone();
- const acceptedServer = { ...server, issuer: acceptedIssuer };
- try {
- verified = await oauth.processAuthorizationCodeResponse(acceptedServer, client, attempt, {
- expectedNonce: flow.nonce,
- requireIdToken: true,
- });
- } catch (error) {
- if (acceptedIssuer === server.issuer) continue;
- throw error;
- }
- await oauth.validateApplicationLevelSignature(acceptedServer, attempt, options);
- break;
- }
- const claims = verified && oauth.getValidatedIdTokenClaims(verified);
- if (!claims || !/^[\x21-\x7e]{1,255}$/.test(claims.sub)) throw failed();
- // This client has no cross-client/hybrid sign-in. The library requires azp
- // for multiple audiences; also reject a foreign azp with a single audience.
- if (claims.azp !== undefined && claims.azp !== client.client_id) throw failed();
- // Upstream access/ID tokens are intentionally discarded at this boundary.
- return { issuer: IDENTITY_ISSUERS.google, subject: claims.sub };
- } catch (error) {
- if (error instanceof HttpFailure) throw error;
- throw failed();
- }
-}
diff --git a/hosting/src/html-page.ts b/hosting/src/html-page.ts
deleted file mode 100644
index e8b2f97a..00000000
--- a/hosting/src/html-page.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-export const escapeHtml = (value: string) =>
- value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
-
-/** Content is trusted application markup; escape each interpolated user value. */
-export function htmlPage(title: string, content: string, options: ResponseInit = {}): Response {
- const nonce = crypto.randomUUID().replace(/-/g, '');
- const headers = new Headers(options.headers);
- headers.set('content-type', 'text/html; charset=utf-8');
- headers.set(
- 'content-security-policy',
- `default-src 'none'; img-src data:; style-src 'nonce-${nonce}'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'`,
- );
- return new Response(
- `<!doctype html><html lang="en"><head><meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)} · Kiln</title>
-<style nonce="${nonce}">
-:root{font-family:system-ui,sans-serif;color:#292821;background:#f6f4ef;color-scheme:light}
-*{box-sizing:border-box}body{margin:0}main{max-width:42rem;margin:8vh auto;padding:1.5rem}
-header{display:flex;align-items:baseline;flex-wrap:wrap;gap:.8rem;margin-bottom:2.5rem}header strong{font-size:1.7rem}header a{text-decoration:none;color:inherit}
-header span,footer{font-size:.9rem;color:#59594f}h1{font-size:2rem;line-height:1.2;overflow-wrap:anywhere}
-p,li{line-height:1.6}section{border:1px solid #d6d3c9;background:#fff;border-radius:.75rem;padding:1.5rem;margin:1.5rem 0}
-h2{font-size:1.15rem;margin-top:0}button{font:inherit;font-weight:600;min-height:2.75rem;padding:.65rem 1.2rem;border:0;border-radius:.35rem;background:#3d5139;color:#fff;cursor:pointer}
-button:focus-visible,a:focus-visible{outline:3px solid #a25c24;outline-offset:4px}a{color:#365231}code{overflow-wrap:anywhere}
-article+article{border-top:1px solid #d6d3c9;margin-top:1.5rem;padding-top:1.5rem}article h3,article p{overflow-wrap:anywhere}
-article form{display:flex;align-items:center;flex-wrap:wrap;gap:.75rem}select{font:inherit;min-height:2.75rem;border:1px solid #747775;border-radius:.35rem;background:#fff;color:#292821;padding:.4rem}
-select:focus-visible{outline:3px solid #a25c24;outline-offset:4px}
-.provider-buttons{display:flex;flex-wrap:wrap;gap:.75rem}.google-button{padding:0;background:transparent;line-height:0}
-.google-button img{display:block;width:198px;height:44px}.github-button{width:198px;min-height:44px;padding:0;background:#fff;color:#1f1f1f;border:1px solid #747775;font-size:14px;font-weight:500}
-.secondary{background:transparent;color:#365231;border:1px solid #747775}.permission-list{padding-left:1.25rem}.client-detail{overflow-wrap:anywhere}
-footer{margin-top:2rem}footer nav{display:flex;gap:1rem;flex-wrap:wrap}
-</style></head><body><main><header><strong><a href="/">Kiln</a></strong><span>by Instrukt Labs</span></header>
-${content}<footer><nav aria-label="Support and policies"><a href="/account">Your account</a><a href="/privacy">Privacy</a><a href="/terms">Terms</a><a href="/support">Support</a>
-<a href="https://github.com/instruktlabs/kiln">Open source</a></nav></footer></main></body></html>`,
- { ...options, headers },
- );
-}
diff --git a/hosting/src/http.ts b/hosting/src/http.ts
deleted file mode 100644
index 2daa571b..00000000
--- a/hosting/src/http.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-export class HttpFailure extends Error {
- constructor(
- readonly status: number,
- message: string,
- ) {
- super(message);
- }
-}
-
-export function serviceFailure(error: unknown): Response {
- // Only intentionally public errors may supply a response message.
- if (error instanceof HttpFailure) return new Response(error.message, { status: error.status });
- return new Response('Service temporarily unavailable', { status: 503 });
-}
-
-// Bound bytes while reading, including chunked bodies without Content-Length.
-export async function readBounded(
- body: ReadableStream<Uint8Array> | null,
- limit: number,
- signal?: AbortSignal,
-): Promise<Uint8Array<ArrayBuffer>> {
- if (signal?.aborted) {
- void body?.cancel().catch(() => {});
- throw new HttpFailure(499, 'Request cancelled');
- }
- if (!body) return new Uint8Array();
- const reader = body.getReader();
- const deadlineAt = Date.now() + 10_000;
- let bytes = new Uint8Array(Math.min(limit, 64 * 1024));
- let length = 0;
- let timer: ReturnType<typeof setTimeout> | undefined;
- let onAbort: () => void = () => {};
- const timeout = new Promise<never>((_, reject) => {
- onAbort = () => {
- reject(new HttpFailure(499, 'Request cancelled'));
- void reader.cancel().catch(() => {});
- };
- signal?.addEventListener('abort', onAbort, { once: true });
- timer = setTimeout(() => {
- reject(new HttpFailure(408, 'Request timed out'));
- void reader.cancel().catch(() => {});
- }, 10_000);
- });
- void timeout.catch(() => {});
- const check = () => {
- if (signal?.aborted) throw new HttpFailure(499, 'Request cancelled');
- if (Date.now() >= deadlineAt) throw new HttpFailure(408, 'Request timed out');
- };
- try {
- for (;;) {
- check();
- const { done, value } = await Promise.race([reader.read(), timeout]);
- check();
- if (done) break;
- const nextLength = length + value.byteLength;
- if (nextLength > limit) {
- throw new HttpFailure(413, 'Request too large');
- }
- if (nextLength > bytes.byteLength) {
- const grown = new Uint8Array(Math.min(limit, Math.max(nextLength, bytes.byteLength * 2)));
- grown.set(bytes.subarray(0, length));
- bytes = grown;
- }
- // Copy before the next read; neither tiny chunks nor reused buffers retain
- // an unbounded collection of views or change previously received bytes.
- bytes.set(value, length);
- length = nextLength;
- }
- return bytes.byteLength === length ? bytes : bytes.slice(0, length);
- } catch (error) {
- void reader.cancel().catch(() => {});
- throw error;
- } finally {
- signal?.removeEventListener('abort', onAbort);
- if (timer !== undefined) clearTimeout(timer);
- reader.releaseLock();
- }
-}
-
-export async function boundedRequest(request: Request, limit: number): Promise<Request> {
- const declared = request.headers.get('content-length');
- if (declared && (!/^\d+$/.test(declared) || Number(declared) > limit)) {
- void request.body?.cancel().catch(() => {});
- throw new HttpFailure(413, 'Request too large');
- }
- if (!request.body) return request;
- const body = await readBounded(request.body, limit, request.signal);
- return new Request(request, { body });
-}
-
-export function privateResponse(response: Response): Response {
- const headers = new Headers(response.headers);
- headers.set('cache-control', 'no-store');
- headers.set('referrer-policy', 'no-referrer');
- headers.set('x-content-type-options', 'nosniff');
- return new Response(response.body, {
- status: response.status,
- statusText: response.statusText,
- headers,
- });
-}
-
-export async function sha256(value: string): Promise<string> {
- const bytes = new Uint8Array(
- await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)),
- );
- return btoa(String.fromCharCode(...bytes))
- .replace(/\+/g, '-')
- .replace(/\//g, '_')
- .replace(/=+$/, '');
-}
diff --git a/hosting/src/identity-actions.ts b/hosting/src/identity-actions.ts
deleted file mode 100644
index 9d6007ce..00000000
--- a/hosting/src/identity-actions.ts
+++ /dev/null
@@ -1,322 +0,0 @@
-import { IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';
-import type { SignInEnv } from './auth';
-import { BROWSER_COOKIE_ATTRIBUTES, browserToken, randomBrowserToken } from './browser-cookies';
-import {
- clearBrowserSessionCookie,
- D1BrowserSessions,
- type BrowserSession,
-} from './browser-sessions';
-import { accountNoticePage } from './account-page';
-import { githubAuthorizationUrl, githubIdentity } from './github';
-import { googleAuthorizationUrl, googleIdentity } from './google';
-import { HttpFailure, sha256 } from './http';
-import type { SignInProvider } from './login-intents';
-
-const COOKIE = '__Host-kiln-identity';
-const clearCookie = `${COOKIE}=; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=0`;
-const denied = () =>
- new HttpFailure(403, 'Sign-in method change unavailable; return to your account and try again');
-const invalid = () =>
- new HttpFailure(
- 400,
- 'Invalid or expired sign-in confirmation; return to your account and try again',
- );
-const isProvider = (value: unknown): value is SignInProvider =>
- value === 'google' || value === 'github';
-const hash = (origin: string, kind: 'state' | 'binding', value: string) =>
- sha256(JSON.stringify(['kiln-identity-action-v1', origin, kind, value]));
-interface Flow {
- purpose: 'link' | 'unlink';
- phase: 'confirm' | 'target';
- provider: SignInProvider;
- target: SignInProvider;
- confirmer: SignInProvider;
- confirmedSubject: string | null;
- confirmedAt: number | null;
- expiresAt: number;
- verifier: string;
- nonce: string;
-}
-const currentSession = `s.token_hash=? AND s.account_id=? AND s.account_epoch=?
- AND s.expires_at>? AND s.idle_expires_at>? AND a.state='active'
- AND a.authorization_epoch=s.account_epoch`;
-const proofArgs = (proof: BrowserSession, now: number) => [
- proof.binding,
- proof.accountId,
- proof.accountEpoch,
- now,
- now,
-];
-
-/** Every phase is purpose-bound, browser-bound and consumed before provider I/O. */
-async function redirect(
- request: Request,
- origin: string,
- env: SignInEnv,
- proof: BrowserSession,
- flow: Pick<
- Flow,
- 'purpose' | 'phase' | 'provider' | 'target' | 'confirmer' | 'confirmedSubject' | 'confirmedAt'
- >,
-): Promise<Response> {
- const state = `ki1_${randomBrowserToken()}`,
- binding = randomBrowserToken();
- const verifier = randomBrowserToken(),
- nonce = randomBrowserToken(),
- now = Date.now();
- const previous = browserToken(request, origin, COOKIE);
- const database = env.ACCOUNTS.withSession('first-primary');
- const rows = await database.batch([
- database
- .prepare(`DELETE FROM kiln_identity_actions WHERE state_hash IN
- (SELECT state_hash FROM kiln_identity_actions WHERE expires_at<=? LIMIT 128)`)
- .bind(now),
- database
- .prepare('DELETE FROM kiln_identity_actions WHERE binding_hash=?')
- .bind(previous ? await hash(origin, 'binding', previous) : ''),
- database
- .prepare(`INSERT INTO kiln_identity_actions
- (state_hash,binding_hash,session_hash,account_id,account_epoch,purpose,phase,provider,target,confirmer,
- confirmed_subject,confirmed_at,verifier,nonce,expires_at)
- SELECT ?,?,s.token_hash,s.account_id,s.account_epoch,?,?,?,?,?,?,?,?,?,? FROM kiln_browser_sessions s
- JOIN kiln_accounts a ON a.id=s.account_id WHERE ${currentSession}
- AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=s.account_id AND i.issuer=?
- AND (? IS NULL OR i.subject=?))
- AND (SELECT COUNT(*) FROM kiln_identities i WHERE i.account_id=s.account_id AND i.issuer=?)=?
- AND (SELECT COUNT(*) FROM kiln_identity_actions WHERE account_id=s.account_id)<4
- AND (SELECT COUNT(*) FROM kiln_identity_actions)<4096 RETURNING state_hash`)
- .bind(
- await hash(origin, 'state', state),
- await hash(origin, 'binding', binding),
- flow.purpose,
- flow.phase,
- flow.provider,
- flow.target,
- flow.confirmer,
- flow.confirmedSubject,
- flow.confirmedAt,
- verifier,
- nonce,
- now + 300_000,
- ...proofArgs(proof, now),
- IDENTITY_ISSUERS[flow.confirmer],
- flow.confirmedSubject,
- flow.confirmedSubject,
- IDENTITY_ISSUERS[flow.target],
- flow.purpose === 'link' ? 0 : 1,
- ),
- ]);
- if (rows[2]?.results.length !== 1) throw denied();
- const location =
- flow.provider === 'google'
- ? await googleAuthorizationUrl(
- origin,
- { state, verifier, nonce, selectAccount: true },
- env,
- request.signal,
- )
- : await githubAuthorizationUrl(origin, state, verifier, env, true);
- return new Response(null, {
- status: 302,
- headers: {
- location,
- 'set-cookie': `${COOKIE}=${binding}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=300`,
- },
- });
-}
-
-export async function beginIdentityAction(
- request: Request,
- origin: string,
- env: SignInEnv,
-): Promise<Response> {
- if (request.method !== 'POST')
- return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });
- if (new URL(request.url).search || request.headers.get('origin') !== origin) throw denied();
- if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')
- throw new HttpFailure(415, 'Expected form data');
- const form = await request.formData(),
- fields = ['csrf', 'action', 'provider', 'target'];
- if (
- fields.some((field) => form.getAll(field).length !== 1) ||
- [...form.keys()].some((field) => !fields.includes(field))
- )
- throw denied();
- const purpose = form.get('action'),
- provider = form.get('provider'),
- target = form.get('target');
- // Unlink proves control of the method that will remain, never the one removed.
- if (
- (purpose !== 'link' && purpose !== 'unlink') ||
- !isProvider(provider) ||
- !isProvider(target) ||
- provider === target
- )
- throw denied();
- const proof = await new D1BrowserSessions(env.ACCOUNTS, origin).authorizeForm(
- request,
- String(form.get('csrf')),
- );
- return redirect(request, origin, env, proof, {
- purpose,
- provider,
- target,
- phase: 'confirm',
- confirmer: provider,
- confirmedSubject: null,
- confirmedAt: null,
- });
-}
-
-/** Called only with a consumed confirmation and freshly validated provider response. */
-async function changeIdentity(
- env: SignInEnv,
- proof: BrowserSession,
- flow: Flow,
- confirmed: VerifiedIdentity,
- target: VerifiedIdentity,
-) {
- const now = Date.now();
- if (
- now >= flow.expiresAt ||
- (flow.phase === 'target' &&
- (!flow.confirmedAt || now - flow.confirmedAt > 300_000 || flow.confirmedAt > now))
- )
- throw invalid();
- const database = env.ACCOUNTS.withSession('first-primary');
- const authorized = `EXISTS (SELECT 1 FROM kiln_browser_sessions s JOIN kiln_accounts a ON a.id=s.account_id
- WHERE ${currentSession} AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=s.account_id AND i.issuer=? AND i.subject=?))`;
- const args = [...proofArgs(proof, now), confirmed.issuer, confirmed.subject];
- const mutation =
- flow.purpose === 'link'
- ? database
- .prepare(`INSERT INTO kiln_identities (issuer,subject,account_id,created_at)
- SELECT ?,?,?,? WHERE ${authorized}
- AND NOT EXISTS (SELECT 1 FROM kiln_identities WHERE issuer=? AND (subject=? OR account_id=?))
- ON CONFLICT DO NOTHING`)
- .bind(
- target.issuer,
- target.subject,
- proof.accountId,
- now,
- ...args,
- target.issuer,
- target.subject,
- proof.accountId,
- )
- : database
- .prepare(`DELETE FROM kiln_identities WHERE account_id=? AND issuer=? AND ${authorized}
- AND (SELECT COUNT(*) FROM kiln_identities WHERE account_id=?)>1`)
- .bind(proof.accountId, target.issuer, ...args, proof.accountId);
- // Each of the next three statements depends on exactly one preceding change.
- // D1 batch is a transaction: identity, notification record, epoch and session
- // revocation either commit together or all roll back. No external I/O in between.
- const result = await database.batch([
- mutation,
- database
- .prepare(`INSERT INTO kiln_account_events(id,account_id,kind,provider,created_at)
- SELECT ?,?,?,?,? WHERE changes()=1`)
- .bind(crypto.randomUUID(), proof.accountId, flow.purpose, flow.target, now),
- database
- .prepare(`UPDATE kiln_accounts SET authorization_epoch=authorization_epoch+1
- WHERE id=? AND authorization_epoch=? AND changes()=1 RETURNING id`)
- .bind(proof.accountId, proof.accountEpoch),
- database
- .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=? AND changes()=1')
- .bind(proof.accountId),
- database
- .prepare(`DELETE FROM kiln_account_events WHERE id IN
- (SELECT id FROM kiln_account_events WHERE account_id=? ORDER BY created_at DESC,id DESC LIMIT -1 OFFSET 20)`)
- .bind(proof.accountId),
- ]);
- if (result[2]?.results.length !== 1) throw denied();
-}
-
-export async function finishIdentityAction(
- request: Request,
- origin: string,
- env: SignInEnv,
- provider: SignInProvider,
-): Promise<Response> {
- const url = new URL(request.url),
- state = url.searchParams.get('state') ?? '';
- const binding = browserToken(request, origin, COOKIE);
- if (
- request.method !== 'GET' ||
- url.pathname !== `/oauth/${provider}/callback` ||
- url.searchParams.getAll('state').length !== 1 ||
- !/^ki1_[a-f0-9]{64}$/.test(state) ||
- !binding
- )
- throw invalid();
- let proof: BrowserSession;
- try {
- proof = await new D1BrowserSessions(env.ACCOUNTS, origin).read(request);
- } catch (error) {
- if (error instanceof HttpFailure && error.status === 401) throw invalid();
- throw error;
- }
- const flow = await env.ACCOUNTS.withSession('first-primary')
- .prepare(`DELETE FROM kiln_identity_actions
- WHERE state_hash=? AND binding_hash=? AND provider=? AND session_hash=? AND account_id=? AND account_epoch=? AND expires_at>?
- AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_identity_actions.account_id AND a.state='active'
- AND a.authorization_epoch=kiln_identity_actions.account_epoch)
- RETURNING purpose,phase,provider,target,confirmer,confirmed_subject AS confirmedSubject,confirmed_at AS confirmedAt,
- expires_at AS expiresAt,verifier,nonce`)
- .bind(
- await hash(origin, 'state', state),
- await hash(origin, 'binding', binding),
- provider,
- proof.binding,
- proof.accountId,
- proof.accountEpoch,
- Date.now(),
- )
- .first<Flow>();
- if (!flow) throw invalid();
- if (url.searchParams.has('error'))
- return new Response('Confirmation was cancelled. Return to your account to try again.', {
- status: 400,
- headers: { 'set-cookie': clearCookie },
- });
- const code = url.searchParams.get('code');
- if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1) throw invalid();
- const identity =
- provider === 'google'
- ? await googleIdentity(request, origin, { ...flow, state }, env)
- : await githubIdentity(code, flow.verifier, origin, env);
- if (Date.now() >= flow.expiresAt) throw invalid();
- if (flow.phase === 'confirm' && flow.purpose === 'link')
- return redirect(request, origin, env, proof, {
- ...flow,
- phase: 'target',
- provider: flow.target,
- confirmedSubject: identity.subject,
- confirmedAt: Date.now(),
- });
- const confirmed =
- flow.phase === 'confirm'
- ? identity
- : {
- issuer: IDENTITY_ISSUERS[flow.confirmer],
- subject: flow.confirmedSubject ?? '',
- };
- if (
- confirmed.issuer !== IDENTITY_ISSUERS[flow.confirmer] ||
- (flow.phase === 'target' && (flow.purpose !== 'link' || provider !== flow.target))
- )
- throw invalid();
- await changeIdentity(
- env,
- proof,
- flow,
- confirmed,
- flow.purpose === 'link' ? identity : { issuer: IDENTITY_ISSUERS[flow.target], subject: '' },
- );
- const response = accountNoticePage(
- flow.purpose === 'link' ? 'Sign-in method added' : 'Sign-in method removed',
- );
- response.headers.append('set-cookie', clearCookie);
- response.headers.append('set-cookie', clearBrowserSessionCookie);
- return response;
-}
diff --git a/hosting/src/login-intents.ts b/hosting/src/login-intents.ts
deleted file mode 100644
index 3372a59e..00000000
--- a/hosting/src/login-intents.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { HttpFailure, sha256 } from './http';
-
-export type SignInProvider = 'google' | 'github';
-export interface LoginIntent {
- id: string;
- state: string;
- provider: SignInProvider;
- purpose: 'sign-in';
-}
-
-/** Complements browser validation in the OAuth library with atomic replay guards. */
-export class D1LoginIntents {
- constructor(
- private readonly database: D1Database,
- private readonly origin: string,
- ) {}
- async claimConsent(handle: string): Promise<void> {
- bounded(handle);
- const now = Date.now();
- const session = this.database.withSession('first-primary');
- const results = await session.batch([
- session
- .prepare(
- 'DELETE FROM kiln_consent_claims WHERE handle_hash IN (SELECT handle_hash FROM kiln_consent_claims WHERE expires_at<? LIMIT 128)',
- )
- .bind(now),
- session
- .prepare(
- 'INSERT INTO kiln_consent_claims(handle_hash, expires_at) VALUES (?, ?) ON CONFLICT DO NOTHING RETURNING handle_hash',
- )
- .bind(await sha256(JSON.stringify([this.origin, handle])), now + 86_400_000),
- ]);
- // Retain the claim much longer than the library's ten-minute transaction.
- // Call only after its browser-cookie validation, so a stranger cannot burn it.
- if (results[1]?.results.length !== 1) throw expired();
- }
- async create(intent: LoginIntent): Promise<void> {
- validate(intent);
- const now = Date.now();
- const session = this.database.withSession('first-primary');
- await session.batch([
- session
- .prepare(
- 'DELETE FROM kiln_login_intents WHERE id IN (SELECT id FROM kiln_login_intents WHERE expires_at<? LIMIT 128)',
- )
- .bind(now),
- session
- .prepare(
- 'INSERT INTO kiln_login_intents(id, state_hash, provider, purpose, expires_at) VALUES (?, ?, ?, ?, ?)',
- )
- .bind(
- intent.id,
- await this.stateHash(intent.state),
- intent.provider,
- intent.purpose,
- now + 600_000,
- ),
- ]);
- }
- async consume(intent: LoginIntent): Promise<void> {
- validate(intent);
- const row = await this.database
- .withSession('first-primary')
- .prepare(
- 'DELETE FROM kiln_login_intents WHERE id=? AND state_hash=? AND provider=? AND purpose=? AND expires_at>? RETURNING id',
- )
- .bind(
- intent.id,
- await this.stateHash(intent.state),
- intent.provider,
- intent.purpose,
- Date.now(),
- )
- .first();
- if (!row) throw expired();
- }
- private stateHash(state: string): Promise<string> {
- return sha256(JSON.stringify([this.origin, state]));
- }
-}
-
-const expired = () => new HttpFailure(400, 'Invalid or expired sign-in; restart sign-in');
-function bounded(value: unknown): asserts value is string {
- if (typeof value !== 'string' || !value || value.length > 4096) throw expired();
-}
-function validate(intent: LoginIntent): void {
- if (
- !intent ||
- !/^[a-f0-9-]{36}$/.test(intent.id) ||
- !['google', 'github'].includes(intent.provider) ||
- intent.purpose !== 'sign-in'
- )
- throw expired();
- bounded(intent.state);
-}
diff --git a/hosting/src/material-index.ts b/hosting/src/material-index.ts
deleted file mode 100644
index 82eba7b1..00000000
--- a/hosting/src/material-index.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import type { ArtifactStore } from './artifact-store';
-import { HttpFailure } from './http';
-
-const id = /^[a-z][a-z0-9_-]{0,79}(?![\s\S])/;
-const revision = /^sha256:[a-f0-9]{64}(?![\s\S])/;
-const cursor = /^materials\/[a-z][a-z0-9_-]{0,79}\/[a-f0-9]{64}(?![\s\S])/;
-const fileId = /^[a-f0-9]{32}(?![\s\S])/;
-const allowedFiles = new Set([
- 'manifest.json',
- 'baseColor.png',
- 'normal.png',
- 'metallicRoughness.png',
- 'emissive.png',
- 'occlusion.png',
-]);
-const invalid = () => new HttpFailure(400, 'Invalid saved material');
-function object(value: unknown): Record<string, unknown> {
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalid();
- return value as Record<string, unknown>;
-}
-function key(materialId: unknown, revisionId: unknown): string {
- if (
- typeof materialId !== 'string' ||
- !id.test(materialId) ||
- typeof revisionId !== 'string' ||
- !revision.test(revisionId)
- )
- throw invalid();
- return `materials/${materialId}/${revisionId.slice(7)}`;
-}
-
-/** Tenant ownership and immutable pins; the native SDK verifies material contents. */
-export class MaterialIndex {
- constructor(private readonly artifacts: ArtifactStore) {}
-
- commit(input: unknown) {
- const value = object(input);
- if (Object.keys(value).some((name) => !['materialId', 'revisionId', 'files'].includes(name)))
- throw invalid();
- const logicalKey = key(value.materialId, value.revisionId);
- const entries = Object.entries(object(value.files));
- if (
- entries.length < 2 ||
- entries.length > 6 ||
- !entries.some(([name]) => name === 'manifest.json') ||
- entries.some(
- ([name, value]) =>
- !allowedFiles.has(name) || typeof value !== 'string' || !fileId.test(value),
- )
- )
- throw invalid();
- const files = Object.fromEntries(entries) as Record<string, string>;
- this.artifacts.assertFileNames(files);
- return this.artifacts.save({
- key: logicalKey,
- files,
- metadata: {
- kind: 'kiln.hosted-material.v1',
- materialId: value.materialId,
- revisionId: value.revisionId,
- },
- });
- }
-
- read(materialId: unknown, revisionId: unknown) {
- return this.artifacts.groupByKey(key(materialId, revisionId));
- }
-
- list(input: unknown) {
- const value = object(input);
- const after = value.after ?? '';
- if (
- Object.keys(value).some((name) => name !== 'after') ||
- typeof after !== 'string' ||
- (after !== '' && !cursor.test(after))
- )
- throw invalid();
- return this.artifacts.groupPage('materials/', after);
- }
-}
diff --git a/hosting/src/native-assets.ts b/hosting/src/native-assets.ts
deleted file mode 100644
index 6e9ed99d..00000000
--- a/hosting/src/native-assets.ts
+++ /dev/null
@@ -1,454 +0,0 @@
-import {
- ASSET_LIMIT,
- ASSET_MATERIAL_BYTES,
- ASSET_MATERIAL_FILE,
- assetIdSchema,
- assetManifestSchema,
- encodeAssetBundle,
- validateRecordShape,
- type AssetDraft,
- type AssetLibrary,
- type AssetManifest,
- type AssetRecord,
-} from '@instruktlabs/kiln/assets';
-import { verifyAssetRecord, resolveSavedAssetMaterials } from '@instruktlabs/kiln/assets/node';
-import { createMaterialLibraryPayload } from '@instruktlabs/kiln/material-library/node';
-import type { MaterialLibrary, MaterialRecordV1 } from '../../src/material-library';
-import { programReference } from '../../src/program-store';
-import { NativeHttpClient, StorageFailure, type NativeStorageOptions } from './native-http';
-import { DOWNLOAD_FILES, DOWNLOAD_TOKEN } from './download-path';
-
-type Group = {
- id: string;
- key: string;
- files: Record<string, string>;
- metadata: {
- kind: string;
- collection: string;
- assetId: string;
- revisionId: string;
- parentRevision?: string;
- };
-};
-const text = (bytes: Uint8Array) =>
- new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
-const jsonBytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value));
-const failure = () => new Error('Saved asset integrity check failed');
-const fileId = /^[a-f0-9]{32}(?![\s\S])/;
-const media: Record<string, string> = {
- 'asset.glb': 'model/gltf-binary',
- 'source.kiln.js': 'application/javascript',
- 'preview.png': 'image/png',
- 'manifest.json': 'application/json',
- [ASSET_MATERIAL_FILE]: 'application/json',
-};
-function identity(raw: string): string {
- const value = assetIdSchema.parse(raw);
- if (!/^[a-z][a-z0-9_-]{0,79}(?![\s\S])/.test(value)) throw new Error('Invalid asset identity');
- return value;
-}
-function collection(value: string): string {
- if (value !== 'project' && value !== 'library') throw new Error('Unknown collection');
- return value;
-}
-function path(target: string, assetId: string, revisionId: string): string {
- return `/internal/assets/${collection(target)}/${identity(assetId)}/${identity(revisionId)}`;
-}
-async function hash(bytes: Uint8Array): Promise<string> {
- return Array.from(
- new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes))),
- (byte) => byte.toString(16).padStart(2, '0'),
- ).join('');
-}
-
-/** Canonical engine records with durable tenant storage; no local workspace or provider credentials. */
-export class NativeAssetLibrary implements AssetLibrary {
- private readonly http: NativeHttpClient;
- constructor(
- private readonly options: NativeStorageOptions & {
- materials?: MaterialLibrary;
- /** Host-only proof for newly evaluated saves; imports retain original provenance. */
- executionIdentity?: (draft: Pick<AssetDraft, 'code' | 'glb'>) => string;
- } = {},
- ) {
- this.http = new NativeHttpClient(
- { ...options, timeoutMs: options.timeoutMs ?? 60_000 },
- 'Asset storage',
- );
- }
- collections() {
- return [
- { id: 'project', label: 'Workspace storage' },
- { id: 'library', label: 'User library storage' },
- ];
- }
- private async json(route: string, input?: unknown, limit = 4096): Promise<unknown> {
- const bytes = await this.http.bytes(route, {
- method: input === undefined ? 'GET' : 'POST',
- body: input === undefined ? undefined : jsonBytes(input),
- limit,
- statuses: [200, 201],
- headers: input === undefined ? undefined : { 'content-type': 'application/json' },
- });
- try {
- return JSON.parse(text(bytes));
- } catch {
- throw failure();
- }
- }
- private group(raw: unknown, target: string, assetId?: string, revisionId?: string): Group {
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw failure();
- const value = raw as Group;
- const meta = value.metadata;
- if (
- typeof value.id !== 'string' ||
- !fileId.test(value.id) ||
- !meta ||
- meta.kind !== 'kiln.hosted-asset.v1' ||
- meta.collection !== target ||
- (assetId !== undefined && meta.assetId !== assetId) ||
- (revisionId !== undefined && meta.revisionId !== revisionId) ||
- value.key !==
- `assets/${collection(target)}/${identity(meta.assetId)}/${identity(meta.revisionId)}` ||
- !value.files ||
- typeof value.files !== 'object' ||
- Array.isArray(value.files) ||
- !value.files['manifest.json'] ||
- !value.files['asset.glb'] ||
- Object.entries(value.files).some(
- ([name, id]) => !Object.hasOwn(media, name) || typeof id !== 'string' || !fileId.test(id),
- )
- )
- throw failure();
- return value;
- }
- private async find(
- target: string,
- assetId: string,
- revisionId: string,
- ): Promise<Group | undefined> {
- try {
- return this.group(
- await this.json(path(target, assetId, revisionId)),
- target,
- assetId,
- revisionId,
- );
- } catch (error) {
- if (error instanceof StorageFailure && error.status === 404) return undefined;
- throw error;
- }
- }
- private async download(id: string, limit: number): Promise<Uint8Array> {
- if (!fileId.test(id)) throw failure();
- return this.http.bytes(`/mcp/artifacts/${id}`, { limit });
- }
- private async manifest(group: Group): Promise<AssetManifest> {
- const raw = JSON.parse(text(await this.download(group.files['manifest.json']!, 1024 * 1024)));
- assetManifestSchema.parse(raw);
- if (
- raw.assetId !== group.metadata.assetId ||
- raw.revisionId !== group.metadata.revisionId ||
- raw.parentRevision !== group.metadata.parentRevision
- )
- throw failure();
- // Preserve unknown provenance exactly as the Node library does; parsing validates only.
- return raw as AssetManifest;
- }
- async list(target: string): Promise<AssetManifest[]> {
- collection(target);
- const records: AssetManifest[] = [];
- let after: string | undefined;
- let bytes = 0;
- for (;;) {
- const page = (await this.json(
- '/internal/assets/list',
- { collection: target, ...(after ? { after } : {}) },
- 2 * 1024 * 1024,
- )) as { records: unknown[]; next: string | null };
- if (
- !page ||
- !Array.isArray(page.records) ||
- page.records.length > 32 ||
- (page.next !== null &&
- (typeof page.next !== 'string' ||
- !page.next.startsWith(`assets/${target}/`) ||
- page.next <= (after ?? '')))
- )
- throw failure();
- for (const raw of page.records) {
- const manifest = await this.manifest(this.group(raw, target));
- bytes += jsonBytes(manifest).length;
- if (bytes > ASSET_LIMIT || records.length >= 10_000)
- throw new Error('Asset catalogue exceeds host response limits');
- records.push(manifest);
- }
- if (page.next === null) break;
- after = page.next;
- }
- return records.sort(
- (a, b) => b.createdAt.localeCompare(a.createdAt) || a.revisionId.localeCompare(b.revisionId),
- );
- }
- async read(target: string, assetId: string, revisionId: string): Promise<AssetRecord> {
- const group = await this.find(target, assetId, revisionId);
- if (!group) throw new Error('Saved asset not found in this collection');
- const manifest = await this.manifest(group);
- let total = 0;
- const files: Record<string, Uint8Array> = {};
- for (const [name, info] of Object.entries(manifest.files)) {
- if (!['asset.glb', 'source.kiln.js', 'preview.png'].includes(name) || !group.files[name])
- throw failure();
- total += info.bytes;
- if (total > ASSET_LIMIT) throw failure();
- files[name] = await this.download(
- group.files[name]!,
- name === 'source.kiln.js' ? 1024 * 1024 : ASSET_LIMIT,
- );
- }
- const allowed = new Set([...Object.keys(files), 'manifest.json', ASSET_MATERIAL_FILE]);
- if (Object.keys(group.files).some((name) => !allowed.has(name))) throw failure();
- const record: AssetRecord = { manifest, files };
- if (group.files[ASSET_MATERIAL_FILE])
- record.materialResources = JSON.parse(
- text(await this.download(group.files[ASSET_MATERIAL_FILE]!, ASSET_MATERIAL_BYTES)),
- );
- await verifyAssetRecord(record);
- // Saved hosted records always retain a complete editable material closure.
- await resolveSavedAssetMaterials(record);
- return record;
- }
- private async prepare(input: AssetRecord[]): Promise<AssetRecord[]> {
- if (!input.length || input.length > 100) throw new Error('Import requires 1..100 revisions');
- let bytes = 0;
- const keys = new Set<string>();
- for (const record of input) {
- validateRecordShape(record);
- const key = `${identity(record.manifest.assetId)}/${identity(record.manifest.revisionId)}`;
- if (keys.has(key)) throw new Error('Duplicate asset revision');
- keys.add(key);
- const manifestBytes = jsonBytes(record.manifest).length;
- if (manifestBytes > 1024 * 1024) throw new Error('Manifest exceeds 1 MiB');
- bytes +=
- manifestBytes + Object.values(record.files).reduce((sum, file) => sum + file.length, 0);
- if (record.materialResources) bytes += jsonBytes(record.materialResources).length;
- if (bytes > ASSET_LIMIT) throw new Error('Asset batch exceeds 64 MiB');
- }
- const records = structuredClone(input);
- let preparedBytes = 0;
- for (const record of records) {
- await verifyAssetRecord(record);
- if (record.files['source.kiln.js'])
- await programReference(text(record.files['source.kiln.js']));
- const materials = await resolveSavedAssetMaterials(record, this.options.materials);
- if (materials.length)
- record.materialResources = await createMaterialLibraryPayload(materials);
- else delete record.materialResources;
- preparedBytes += Object.values(this.inventory(record)).reduce(
- (sum, file) => sum + file.length,
- 0,
- );
- if (preparedBytes > ASSET_LIMIT) throw new Error('Asset batch exceeds 64 MiB');
- }
- return records;
- }
- private inventory(record: AssetRecord): Record<string, Uint8Array> {
- const files: Record<string, Uint8Array> = {
- ...record.files,
- 'manifest.json': jsonBytes(record.manifest),
- };
- if (record.materialResources) {
- const bytes = jsonBytes(record.materialResources);
- if (bytes.length > ASSET_MATERIAL_BYTES)
- throw new Error('Asset material payload exceeds byte limit');
- files[ASSET_MATERIAL_FILE] = bytes;
- }
- return files;
- }
- private same(a: AssetRecord, b: AssetRecord): boolean {
- return (
- JSON.stringify(a.manifest) === JSON.stringify(b.manifest) &&
- JSON.stringify(a.materialResources) === JSON.stringify(b.materialResources)
- );
- }
- private async publish(
- target: string,
- record: AssetRecord,
- mode: 'save' | 'import',
- ): Promise<void> {
- const { assetId, revisionId, parentRevision } = record.manifest;
- if (await this.find(target, assetId, revisionId)) {
- if (!this.same(await this.read(target, assetId, revisionId), record))
- throw new Error('Saved revision is immutable');
- return;
- }
- const files: Record<string, string> = {};
- let committed = false;
- try {
- for (const [name, data] of Object.entries(this.inventory(record))) {
- const bytes = Uint8Array.from(data);
- const digest = await hash(bytes);
- const response = await this.http.bytes('/internal/artifacts', {
- method: 'POST',
- body: bytes,
- limit: 2048,
- statuses: [201],
- headers: {
- 'content-type': media[name]!,
- 'x-artifact-name': name,
- 'x-artifact-sha256': digest,
- },
- });
- const receipt = JSON.parse(text(response));
- if (
- !receipt ||
- typeof receipt.id !== 'string' ||
- !fileId.test(receipt.id) ||
- receipt.bytes !== bytes.length ||
- receipt.sha256 !== digest
- )
- throw failure();
- files[name] = receipt.id;
- }
- try {
- const result = await this.json('/internal/assets/commit', {
- collection: target,
- assetId,
- revisionId,
- parentRevision,
- files,
- mode,
- });
- this.group(result, target, assetId, revisionId);
- committed = true;
- } catch (error) {
- if (!(error instanceof StorageFailure) || error.status !== 409) throw error;
- const existing = await this.find(target, assetId, revisionId);
- if (!existing || !this.same(await this.read(target, assetId, revisionId), record))
- throw new Error('Saved revision is immutable or requires parentRevision');
- }
- } finally {
- if (!committed && Object.keys(files).length) {
- // Cleanup is independently bounded even when the triggering request was
- // cancelled. The tenant checks pins atomically, including a lost commit ack.
- const cleanup = new NativeHttpClient(
- { ...this.options, signal: undefined, timeoutMs: 5000 },
- 'Asset cleanup',
- );
- await cleanup
- .bytes('/internal/artifacts/discard', {
- method: 'POST',
- body: jsonBytes(Object.values(files)),
- headers: { 'content-type': 'application/json' },
- limit: 1024,
- })
- .catch(() => {});
- // Failed cleanup stays charged to quota and expires through tenant recovery.
- }
- }
- }
- async import(target: string, input: AssetRecord[]): Promise<AssetManifest[]> {
- collection(target);
- const records = await this.prepare(input);
- if (this.options.materials) {
- const resources = new Map<string, MaterialRecordV1>();
- for (const record of records)
- for (const material of await resolveSavedAssetMaterials(record))
- resources.set(
- `${material.manifest.materialId}/${material.manifest.revisionId}`,
- material,
- );
- if (resources.size) await this.options.materials.import([...resources.values()]);
- }
- for (const record of records) await this.publish(target, record, 'import');
- return records.map((record) => record.manifest);
- }
- async save(target: string, draft: AssetDraft): Promise<AssetManifest> {
- collection(target);
- const code = draft.code,
- glb = Uint8Array.from(draft.glb);
- const build = draft.build
- ? { ...draft.build, rebuild: draft.build.rebuild ?? ('engine-required' as const) }
- : undefined;
- if (this.options.executionIdentity) {
- if (!build) throw new Error('Saved asset has no matching verified evaluation');
- const engine = this.options.executionIdentity({ code, glb });
- if (
- typeof engine !== 'string' ||
- !/^cloudflare-container:sha256:[a-f0-9]{64}(?![\s\S])/.test(engine)
- )
- throw new Error('Saved asset has no matching verified evaluation');
- build.engine = engine;
- }
- const assetId = identity(draft.assetId ?? `a_${crypto.randomUUID().replaceAll('-', '')}`);
- if (draft.parentRevision) await this.read(target, assetId, draft.parentRevision);
- if (code !== undefined) await programReference(code);
- const files: Record<string, Uint8Array> = { 'asset.glb': glb };
- if (code !== undefined) files['source.kiln.js'] = new TextEncoder().encode(code);
- if (draft.preview) files['preview.png'] = Uint8Array.from(draft.preview);
- const inventory: AssetManifest['files'] = {};
- for (const [name, bytes] of Object.entries(files))
- inventory[name] = { bytes: bytes.length, sha256: `sha256:${await hash(bytes)}` };
- const manifest = assetManifestSchema.parse({
- version: 'kiln.asset.v1',
- assetId,
- revisionId: `r_${crypto.randomUUID().replaceAll('-', '')}`,
- parentRevision: draft.parentRevision,
- name: draft.name,
- tags: draft.tags ?? [],
- createdAt: new Date().toISOString(),
- description: draft.description,
- brief: draft.brief,
- attribution: draft.attribution,
- editable: code !== undefined,
- files: inventory,
- build,
- preview: draft.previewInfo,
- });
- const [record] = await this.prepare([{ manifest, files }]);
- await this.publish(target, record!, 'save');
- return manifest;
- }
- async exportBundle(input: AssetRecord[]): Promise<Uint8Array> {
- return encodeAssetBundle(await this.prepare(input));
- }
- /** Browser delivery uses the current Kiln account; links never embed a tenant or bearer credential. */
- async downloadUrls(
- publicOrigin: string,
- target: string,
- assetId: string,
- revisionId: string,
- ): Promise<Record<string, string>> {
- const origin = new URL(publicOrigin);
- if (origin.protocol !== 'https:' || origin.origin !== publicOrigin)
- throw new Error('Invalid public origin');
- const raw = await this.json('/internal/downloads', {
- collection: collection(target),
- assetId: identity(assetId),
- revisionId: identity(revisionId),
- });
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw failure();
- const value = raw as { ticket: string; expiresAt: number; files: string[] };
- if (
- typeof value.ticket !== 'string' ||
- !DOWNLOAD_TOKEN.test(value.ticket) ||
- !Number.isSafeInteger(value.expiresAt) ||
- value.expiresAt <= Date.now() ||
- !Array.isArray(value.files) ||
- !value.files.length ||
- value.files.length > DOWNLOAD_FILES.size ||
- new Set(value.files).size !== value.files.length ||
- value.files.some((name) => typeof name !== 'string' || !DOWNLOAD_FILES.has(name))
- )
- throw failure();
- return Object.fromEntries(
- value.files.map((name) => [name, `${publicOrigin}/downloads/${value.ticket}/${name}`]),
- );
- }
- /** Host UI/account operation; the engine's MCP registry defines no extra delete tool. */
- async deleteRevision(target: string, assetId: string, revisionId: string): Promise<void> {
- const group = await this.find(target, assetId, revisionId);
- if (!group) throw new Error('Saved asset not found in this collection');
- await this.http.bytes(`/internal/groups/${group.id}`, { method: 'DELETE', limit: 1024 });
- }
-}
diff --git a/hosting/src/native-build-identity.ts b/hosting/src/native-build-identity.ts
deleted file mode 100644
index 6c514289..00000000
--- a/hosting/src/native-build-identity.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { createHash } from 'node:crypto';
-import type { AssetDraft } from '@instruktlabs/kiln/assets';
-
-const unavailable = () => new Error('Saved asset has no matching verified evaluation');
-const hash = (bytes: string | Uint8Array) => createHash('sha256').update(bytes).digest('hex');
-function key(code: string | undefined, glb: Uint8Array): string {
- if (
- typeof code !== 'string' ||
- Buffer.byteLength(code) > 1024 * 1024 ||
- !(glb instanceof Uint8Array) ||
- glb.byteLength === 0 ||
- glb.byteLength > 4 * 1024 * 1024
- )
- throw unavailable();
- return `${hash(code)}:${hash(glb)}`;
-}
-
-/** One admitted request's accepted evaluations; never persisted or supplied by authored source. */
-export class NativeBuildIdentities {
- private readonly records = new Map<string, string>();
- record(code: string, glb: Uint8Array, image: string | undefined): void {
- if (typeof image !== 'string' || !/^sha256:[a-f0-9]{64}(?![\s\S])/.test(image))
- throw unavailable();
- const id = key(code, glb),
- value = `cloudflare-container:${image}`;
- const prior = this.records.get(id);
- if ((prior && prior !== value) || (!prior && this.records.size >= 16)) throw unavailable();
- this.records.set(id, value);
- }
- forDraft(draft: Pick<AssetDraft, 'code' | 'glb'>): string {
- const value = this.records.get(key(draft.code, draft.glb));
- if (!value) throw unavailable();
- return value;
- }
-}
diff --git a/hosting/src/native-evaluator.ts b/hosting/src/native-evaluator.ts
deleted file mode 100644
index 937b4eff..00000000
--- a/hosting/src/native-evaluator.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import {
- createEvaluatorPortV2,
- EvaluatorPortError,
- type EvaluatorPortV2,
-} from '@instruktlabs/kiln/evaluator';
-import { NativeHttpClient, StorageFailure } from './native-http';
-
-export interface NativeEvaluatorOptions {
- fetch?: (request: Request) => Promise<Response>;
-}
-type EvaluationResult = Awaited<ReturnType<EvaluatorPortV2['render']>>;
-export interface NativeEvaluatorPort extends EvaluatorPortV2 {
- executionImage(result: EvaluationResult): string | undefined;
-}
-
-/** Validate first; clamping must not turn NaN, zero or negative controls into authority. */
-function capped(value: number | undefined, max: number): number {
- if (value === undefined) return max;
- if (!Number.isSafeInteger(value) || value < 1) throw new EvaluatorPortError('INPUT_INVALID');
- return Math.min(value, max);
-}
-
-/**
- * The host's protocol client, never an in-process evaluator. The controller binds
- * a fresh isolated job to this fixed virtual hostname outside the native host.
- * A deadline/cancellation result alone does not establish VM cleanup or release
- * global admission; the controller must retain its lease until destruction.
- */
-export function createNativeEvaluatorPort(
- options: NativeEvaluatorOptions = {},
-): NativeEvaluatorPort {
- const verified = new WeakMap<EvaluationResult, string>();
- return {
- executionImage: (result) => verified.get(result),
- async render(code, renderOptions, controls = {}) {
- let image: string | undefined;
- // Per-call closure: overlapping responses cannot exchange their image identities.
- const port = createEvaluatorPortV2(async (json, controls) => {
- const body = new TextEncoder().encode(json);
- if (body.byteLength > 4 * 1024 * 1024) throw new EvaluatorPortError('INPUT_INVALID');
- const client = new NativeHttpClient(
- { fetch: options.fetch, timeoutMs: controls.deadlineMs, signal: () => controls.signal },
- 'Evaluator',
- 'evaluator',
- );
- try {
- const result = await client.bytes('/evaluate', {
- method: 'POST',
- body,
- headers: {
- 'content-type': 'application/json',
- 'x-kiln-deadline-ms': String(controls.deadlineMs),
- 'x-kiln-max-response-bytes': String(controls.maxResponseBytes),
- },
- limit: controls.maxResponseBytes,
- onResponseHeaders: (headers) => {
- const value = headers.get('x-kiln-execution-image');
- if (!value || !/^sha256:[a-f0-9]{64}(?![\s\S])/.test(value))
- throw new Error('Missing verified evaluation identity');
- image = value;
- },
- });
- return new TextDecoder('utf-8', { fatal: true }).decode(result);
- } catch (error) {
- if (error instanceof StorageFailure && error.status === 504)
- throw new EvaluatorPortError('DEADLINE_EXCEEDED');
- if (error instanceof StorageFailure && error.status === 499)
- throw new EvaluatorPortError('CANCELLED');
- // The SDK maps other transport failures to a fixed WORKER_FAILED message.
- throw error;
- }
- });
- const result = await port.render(code, renderOptions, {
- signal: controls.signal,
- deadlineMs: capped(controls.deadlineMs, 60_000),
- maxGlbBytes: capped(controls.maxGlbBytes, 4 * 1024 * 1024),
- maxResponseBytes: capped(controls.maxResponseBytes, 8 * 1024 * 1024),
- });
- if (!image) throw new EvaluatorPortError('WORKER_FAILED');
- verified.set(result, image);
- return result;
- },
- };
-}
diff --git a/hosting/src/native-host.ts b/hosting/src/native-host.ts
deleted file mode 100644
index e2e641f7..00000000
--- a/hosting/src/native-host.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { createServer } from 'node:http';
-import { toNodeHandler, type FetchLikeMcpHandler } from '@modelcontextprotocol/node';
-
-/** Private port adapter. Only the externally scoped VM controller may reach it. */
-export function createNativeHttpServer(
- handler: FetchLikeMcpHandler,
- options: { requestTimeoutMs?: number } = {},
-) {
- const timeout = options.requestTimeoutMs ?? 10_000;
- if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 10_000)
- throw new Error('Invalid native upload deadline');
- const adapter = toNodeHandler(handler, { maxRequestBodySize: 1024 * 1024, onerror: () => {} });
- const server = createServer(
- {
- requestTimeout: timeout,
- headersTimeout: timeout,
- connectionsCheckingInterval: Math.min(1000, timeout),
- keepAliveTimeout: 5000,
- maxHeaderSize: 16 * 1024,
- },
- (request, response) => {
- const refuse = (status: number) => {
- response.writeHead(status, {
- 'content-type': 'text/plain',
- 'cache-control': 'no-store',
- connection: 'close',
- });
- response.end('Invalid native request', () => request.destroy());
- };
- if (request.headers.host !== 'kiln-native.internal') return refuse(421);
- if (request.url === '/_ready' && request.method === 'GET') {
- response.writeHead(204, { 'cache-control': 'no-store' });
- response.end();
- return;
- }
- if (request.url !== '/mcp') return refuse(404);
- const declared = request.headers['content-length'];
- if (declared !== undefined && (!/^\d+$/.test(declared) || Number(declared) > 1024 * 1024))
- return refuse(413);
- // The SDK buffers the request before calling fetch. Bound that phase as well
- // as the handler's own execution deadline; disconnects are propagated by SDK.
- const timer = setTimeout(() => request.destroy(), timeout);
- timer.unref();
- const clear = () => clearTimeout(timer);
- request.once('end', clear);
- request.once('close', clear);
- void adapter(request, response).catch(() => response.destroy());
- },
- );
- server.maxConnections = 4;
- server.maxRequestsPerSocket = 16;
- return server;
-}
diff --git a/hosting/src/native-http.ts b/hosting/src/native-http.ts
deleted file mode 100644
index a6e71c3d..00000000
--- a/hosting/src/native-http.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-export interface NativeStorageOptions {
- fetch?: (request: Request) => Promise<Response>;
- /** Supply the native host's per-request signal. */
- signal?: () => AbortSignal | undefined;
- timeoutMs?: number;
-}
-export interface NativeStorageRequest {
- method?: 'GET' | 'POST' | 'DELETE';
- body?: Uint8Array<ArrayBuffer>;
- headers?: Record<string, string>;
- limit: number;
- statuses?: readonly number[];
- /** Synchronous validation of metadata from the fixed private service. */
- onResponseHeaders?: (headers: Headers) => void;
-}
-export class StorageFailure extends Error {
- constructor(
- readonly status: number,
- message: string,
- ) {
- super(message);
- }
-}
-/** Fixed-origin native transport; ownership is bound by an interceptor outside the image. */
-export class NativeHttpClient {
- private readonly timeoutMs: number;
- private readonly send: (request: Request) => Promise<Response>;
- private readonly origin: string;
- constructor(
- private readonly options: NativeStorageOptions = {},
- private readonly label = 'Storage',
- private readonly service: 'storage' | 'evaluator' | 'renderer' = 'storage',
- ) {
- if (service !== 'storage' && service !== 'evaluator' && service !== 'renderer')
- throw new Error('Invalid private service');
- this.origin = `http://kiln-${service}.internal`;
- this.timeoutMs = options.timeoutMs ?? 15_000;
- if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 60_000)
- throw new Error('Invalid storage timeout');
- this.send = options.fetch ?? ((request) => fetch(request));
- }
- async bytes(path: string, request: NativeStorageRequest): Promise<Uint8Array> {
- const { body, limit, headers, method = 'GET', statuses = [200], onResponseHeaders } = request;
- const url = new URL(path, this.origin);
- if (
- url.href !== `${this.origin}${path}` ||
- url.search ||
- url.hash ||
- !(this.service === 'evaluator'
- ? path === '/evaluate'
- : this.service === 'renderer'
- ? path === '/render'
- : path.startsWith('/internal/') || /^\/mcp\/artifacts\/[a-f0-9]{32}$/.test(path))
- )
- throw new Error('Invalid private service path');
- if (
- !Number.isSafeInteger(limit) ||
- limit < 0 ||
- limit > 64 * 1024 * 1024 ||
- (body?.byteLength ?? 0) > 64 * 1024 * 1024
- )
- throw new Error('Invalid storage size limit');
- const outgoing = new Headers(headers);
- const allowedHeaders =
- this.service !== 'storage'
- ? ['content-type', 'x-kiln-deadline-ms', 'x-kiln-max-response-bytes']
- : ['content-type', 'x-artifact-name', 'x-artifact-sha256'];
- for (const name of outgoing.keys())
- if (!allowedHeaders.includes(name)) throw new Error('Invalid private service header');
- if (body !== undefined) outgoing.set('content-length', String(body.byteLength));
- const parent = this.options.signal?.();
- if (parent?.aborted) throw new StorageFailure(499, `${this.label} request cancelled`);
- const controller = new AbortController();
- const deadlineAt = Date.now() + this.timeoutMs;
- const cancel = () => controller.abort();
- let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
- let responseBody: ReadableStream<Uint8Array> | null | undefined;
- let timedOut = false;
- let finished = false;
- let abortListener: () => void = () => {};
- const expired = () => {
- if (Date.now() >= deadlineAt) {
- timedOut = true;
- controller.abort();
- }
- return controller.signal.aborted;
- };
- const check = () => {
- if (expired())
- throw new StorageFailure(
- timedOut ? 504 : 499,
- timedOut ? `${this.label} request timed out` : `${this.label} request cancelled`,
- );
- };
- const aborted = new Promise<never>((_, reject) => {
- abortListener = () => {
- reject(
- new StorageFailure(
- timedOut ? 504 : 499,
- timedOut ? `${this.label} request timed out` : `${this.label} request cancelled`,
- ),
- );
- void reader?.cancel().catch(() => {});
- };
- controller.signal.addEventListener('abort', abortListener, { once: true });
- });
- parent?.addEventListener('abort', cancel, { once: true });
- const timer = setTimeout(() => {
- timedOut = true;
- controller.abort();
- }, this.timeoutMs);
- try {
- const request = new Request(url, {
- method,
- body,
- headers: outgoing,
- redirect: 'error',
- credentials: 'omit',
- signal: controller.signal,
- });
- const pending = this.send(request).then((response) => {
- responseBody = response.body;
- // Even a non-cooperative injected transport cannot leave a late body open.
- if (finished || expired()) void response.body?.cancel().catch(() => {});
- return response;
- });
- const response = await Promise.race([pending, aborted]);
- check();
- if (!statuses.includes(response.status)) {
- void response.body?.cancel().catch(() => {});
- throw new StorageFailure(
- response.status,
- response.status === 507
- ? `${this.label} quota reached; delete unneeded saved work and retry`
- : `${this.label} unavailable; retry the request`,
- );
- }
- const declared = response.headers.get('content-length');
- if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > limit)) {
- void response.body?.cancel().catch(() => {});
- throw new StorageFailure(502, `Invalid ${this.label.toLowerCase()} response`);
- }
- onResponseHeaders?.(new Headers(response.headers));
- if (!response.body) {
- if (declared !== null && Number(declared) !== 0)
- throw new StorageFailure(502, `Invalid ${this.label.toLowerCase()} response`);
- return new Uint8Array();
- }
- reader = response.body.getReader();
- let bytes = new Uint8Array(Math.min(limit, 64 * 1024));
- let length = 0;
- for (;;) {
- // Continuously available chunks can starve timers with microtasks.
- check();
- const { done, value } = await Promise.race([reader.read(), aborted]);
- check();
- if (done) break;
- const nextLength = length + value.byteLength;
- if (nextLength > limit) {
- void reader.cancel().catch(() => {});
- throw new StorageFailure(502, `${this.label} response exceeds its size limit`);
- }
- if (nextLength > bytes.byteLength) {
- const grown = new Uint8Array(Math.min(limit, Math.max(nextLength, bytes.byteLength * 2)));
- grown.set(bytes.subarray(0, length));
- bytes = grown;
- }
- bytes.set(value, length);
- length = nextLength;
- }
- if (declared !== null && Number(declared) !== length)
- throw new StorageFailure(502, `Invalid ${this.label.toLowerCase()} response`);
- return bytes.byteLength === length ? bytes : bytes.slice(0, length);
- } catch (error) {
- if (error instanceof StorageFailure) throw error;
- if (controller.signal.aborted)
- throw new StorageFailure(
- timedOut ? 504 : 499,
- timedOut ? `${this.label} request timed out` : `${this.label} request cancelled`,
- );
- // Never expose network diagnostics, response bodies, paths or abort reasons.
- throw new StorageFailure(503, `${this.label} unavailable; retry the request`);
- } finally {
- finished = true;
- clearTimeout(timer);
- parent?.removeEventListener('abort', cancel);
- controller.signal.removeEventListener('abort', abortListener);
- // Cancellation can win after headers arrive but before a reader attaches.
- // Also close a partially read stream on any validation/read failure.
- void (reader ? reader.cancel() : responseBody?.cancel())?.catch(() => {});
- reader?.releaseLock();
- }
- }
-}
diff --git a/hosting/src/native-materials.ts b/hosting/src/native-materials.ts
deleted file mode 100644
index 8a8eaf3b..00000000
--- a/hosting/src/native-materials.ts
+++ /dev/null
@@ -1,292 +0,0 @@
-import {
- canonicalMaterialJson,
- MATERIAL_LIBRARY_LIMITS,
- validateMaterialRecordShape,
- type MaterialLibrary,
- type MaterialManifestV1,
- type MaterialRecordV1,
-} from '@instruktlabs/kiln/material-library';
-import {
- validateMaterialManifestIdentity,
- verifyMaterialRecordV1,
-} from '@instruktlabs/kiln/material-library/node';
-import { NativeHttpClient, StorageFailure, type NativeStorageOptions } from './native-http';
-
-const BATCH_BYTES = 64 * 1024 * 1024;
-const id = /^[a-z][a-z0-9_-]{0,79}(?![\s\S])/;
-const revision = /^sha256:[a-f0-9]{64}(?![\s\S])/;
-const fileId = /^[a-f0-9]{32}(?![\s\S])/;
-const cursor = /^materials\/[a-z][a-z0-9_-]{0,79}\/[a-f0-9]{64}(?![\s\S])/;
-const filesAllowed = new Set([
- 'manifest.json',
- 'baseColor.png',
- 'normal.png',
- 'metallicRoughness.png',
- 'emissive.png',
- 'occlusion.png',
-]);
-const text = (bytes: Uint8Array) => new TextDecoder('utf-8', { fatal: true }).decode(bytes);
-const jsonBytes = (value: unknown) => new TextEncoder().encode(canonicalMaterialJson(value));
-const failure = () => new Error('Saved material integrity check failed');
-type Group = {
- id: string;
- key: string;
- files: Record<string, string>;
- metadata: { kind: string; materialId: string; revisionId: string };
-};
-function identity(materialId: string, revisionId: string): string {
- if (
- typeof materialId !== 'string' ||
- !id.test(materialId) ||
- typeof revisionId !== 'string' ||
- !revision.test(revisionId)
- )
- throw new Error('Invalid material identity');
- return `materials/${materialId}/${revisionId.slice(7)}`;
-}
-async function hash(bytes: Uint8Array): Promise<string> {
- return Array.from(
- new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes))),
- (byte) => byte.toString(16).padStart(2, '0'),
- ).join('');
-}
-
-/** Durable per-tenant materials using the installed engine's verification contract. */
-export class NativeMaterialLibrary implements MaterialLibrary {
- private readonly http: NativeHttpClient;
- constructor(private readonly options: NativeStorageOptions = {}) {
- this.http = new NativeHttpClient(
- { ...options, timeoutMs: options.timeoutMs ?? 60_000 },
- 'Material storage',
- );
- }
- private async json(path: string, input?: unknown, limit = 4096): Promise<unknown> {
- const bytes = await this.http.bytes(path, {
- method: input === undefined ? 'GET' : 'POST',
- body: input === undefined ? undefined : jsonBytes(input),
- headers: input === undefined ? undefined : { 'content-type': 'application/json' },
- limit,
- statuses: [200, 201],
- });
- try {
- return JSON.parse(text(bytes));
- } catch {
- throw failure();
- }
- }
- private group(raw: unknown, materialId?: string, revisionId?: string): Group {
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw failure();
- const value = raw as Group;
- const meta = value.metadata;
- if (
- typeof value.id !== 'string' ||
- !fileId.test(value.id) ||
- !meta ||
- typeof meta !== 'object' ||
- Array.isArray(meta) ||
- Object.keys(meta).some((name) => !['kind', 'materialId', 'revisionId'].includes(name)) ||
- meta.kind !== 'kiln.hosted-material.v1' ||
- (materialId !== undefined && meta.materialId !== materialId) ||
- (revisionId !== undefined && meta.revisionId !== revisionId) ||
- value.key !== identity(meta.materialId, meta.revisionId) ||
- !value.files ||
- typeof value.files !== 'object' ||
- Array.isArray(value.files) ||
- !value.files['manifest.json'] ||
- Object.keys(value.files).length < 2 ||
- Object.entries(value.files).some(
- ([name, value]) =>
- !filesAllowed.has(name) || typeof value !== 'string' || !fileId.test(value),
- )
- )
- throw failure();
- return value;
- }
- private async find(materialId: string, revisionId: string): Promise<Group | undefined> {
- const path = `/internal/${identity(materialId, revisionId)}`;
- try {
- return this.group(await this.json(path), materialId, revisionId);
- } catch (error) {
- if (error instanceof StorageFailure && error.status === 404) return undefined;
- throw error;
- }
- }
- private download(id: string, limit: number): Promise<Uint8Array> {
- if (!fileId.test(id)) throw failure();
- return this.http.bytes(`/mcp/artifacts/${id}`, { limit });
- }
- private async manifest(group: Group): Promise<MaterialManifestV1> {
- const manifest = validateMaterialManifestIdentity(
- JSON.parse(
- text(
- await this.download(
- group.files['manifest.json']!,
- MATERIAL_LIBRARY_LIMITS.maxManifestBytes,
- ),
- ),
- ),
- );
- if (
- manifest.materialId !== group.metadata.materialId ||
- manifest.revisionId !== group.metadata.revisionId ||
- Object.keys(group.files).length !== manifest.maps.length + 1 ||
- manifest.maps.some((map) => !group.files[map.file])
- )
- throw failure();
- return manifest;
- }
- async read(materialId: string, revisionId: string): Promise<MaterialRecordV1> {
- const group = await this.find(materialId, revisionId);
- if (!group) throw new Error('Saved material not found');
- const manifest = await this.manifest(group);
- const files: Record<string, Uint8Array> = {};
- for (const map of manifest.maps)
- files[map.file] = await this.download(group.files[map.file]!, map.bytes);
- const record = { manifest, files };
- await verifyMaterialRecordV1(record);
- return record;
- }
- async list(): Promise<MaterialManifestV1[]> {
- const records: MaterialManifestV1[] = [];
- let after = '';
- let bytes = 0;
- for (;;) {
- const page = (await this.json(
- '/internal/materials/list',
- after ? { after } : {},
- 128 * 1024,
- )) as { records: unknown[]; next: string | null };
- if (
- !page ||
- !Array.isArray(page.records) ||
- page.records.length > 32 ||
- (page.next !== null &&
- (typeof page.next !== 'string' || !cursor.test(page.next) || page.next <= after))
- )
- throw failure();
- let previous = after;
- for (const raw of page.records) {
- const group = this.group(raw);
- if (group.key <= previous) throw failure();
- previous = group.key;
- const manifest = await this.manifest(group);
- bytes += jsonBytes(manifest).length;
- if (bytes > BATCH_BYTES || records.length >= 10_000)
- throw new Error('Material catalogue exceeds host response limits');
- records.push(manifest);
- }
- if (page.next === null) break;
- if (page.records.length !== 32 || page.next !== previous) throw failure();
- after = page.next;
- }
- return records;
- }
- private async prepare(input: MaterialRecordV1[]): Promise<MaterialRecordV1[]> {
- if (!Array.isArray(input) || !input.length || input.length > 100)
- throw new Error('Import requires 1..100 material revisions');
- let bytes = 0;
- let pixels = 0;
- const keys = new Set<string>();
- for (const record of input) {
- const manifest = validateMaterialRecordShape(record);
- const key = identity(manifest.materialId, manifest.revisionId);
- if (keys.has(key)) throw new Error('Duplicate material revision');
- keys.add(key);
- bytes += jsonBytes(manifest).length;
- for (const map of manifest.maps) {
- bytes += map.bytes;
- pixels += map.width * map.height;
- }
- if (bytes > BATCH_BYTES || pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels)
- throw new Error('Material batch exceeds host byte or pixel limits');
- }
- // Copy all caller-owned buffers before the first asynchronous verification.
- const records = input.map((record) => ({
- manifest: structuredClone(record.manifest),
- files: Object.fromEntries(
- Object.entries(record.files).map(([name, bytes]) => [name, Uint8Array.from(bytes)]),
- ),
- }));
- for (const record of records) await verifyMaterialRecordV1(record);
- return records;
- }
- private async same(record: MaterialRecordV1): Promise<boolean> {
- const existing = await this.read(record.manifest.materialId, record.manifest.revisionId);
- return canonicalMaterialJson(existing.manifest) === canonicalMaterialJson(record.manifest);
- }
- private async publish(record: MaterialRecordV1): Promise<void> {
- const { materialId, revisionId } = record.manifest;
- if (await this.find(materialId, revisionId)) {
- if (!(await this.same(record))) throw new Error('Saved material revision is immutable');
- return;
- }
- const files: Record<string, string> = {};
- let committed = false;
- try {
- for (const [name, data] of Object.entries({
- ...record.files,
- 'manifest.json': jsonBytes(record.manifest),
- })) {
- const bytes = Uint8Array.from(data);
- const digest = await hash(bytes);
- const receipt = JSON.parse(
- text(
- await this.http.bytes('/internal/artifacts', {
- method: 'POST',
- body: bytes,
- limit: 2048,
- statuses: [201],
- headers: {
- 'content-type': name === 'manifest.json' ? 'application/json' : 'image/png',
- 'x-artifact-name': name,
- 'x-artifact-sha256': digest,
- },
- }),
- ),
- );
- if (
- !receipt ||
- typeof receipt.id !== 'string' ||
- !fileId.test(receipt.id) ||
- receipt.bytes !== bytes.length ||
- receipt.sha256 !== digest
- )
- throw failure();
- files[name] = receipt.id;
- }
- try {
- this.group(
- await this.json('/internal/materials/commit', { materialId, revisionId, files }),
- materialId,
- revisionId,
- );
- committed = true;
- } catch (error) {
- if (!(error instanceof StorageFailure) || error.status !== 409) throw error;
- if (!(await this.same(record))) throw new Error('Saved material revision is immutable');
- }
- } finally {
- if (!committed && Object.keys(files).length) {
- // Pins protect committed data even when its acknowledgement was lost.
- // Failed cleanup stays quota-counted until normal unsaved-work expiry.
- const cleanup = new NativeHttpClient(
- { ...this.options, signal: undefined, timeoutMs: 5000 },
- 'Material cleanup',
- );
- await cleanup
- .bytes('/internal/artifacts/discard', {
- method: 'POST',
- body: jsonBytes(Object.values(files)),
- headers: { 'content-type': 'application/json' },
- limit: 1024,
- })
- .catch(() => {});
- }
- }
- }
- async import(input: MaterialRecordV1[]): Promise<MaterialManifestV1[]> {
- const records = await this.prepare(input);
- for (const record of records) await this.publish(record);
- return records.map((record) => record.manifest);
- }
-}
diff --git a/hosting/src/native-mcp.ts b/hosting/src/native-mcp.ts
deleted file mode 100644
index 52246f33..00000000
--- a/hosting/src/native-mcp.ts
+++ /dev/null
@@ -1,327 +0,0 @@
-import { createMcpHandler, type Server } from '@modelcontextprotocol/server';
-import type { KilnToolContext } from '@instruktlabs/kiln/tools';
-import type { EvaluatorPortV2, IsolatedEvaluatorHost } from '@instruktlabs/kiln/evaluator';
-import type { PbrRenderPort } from '@instruktlabs/kiln/composer';
-import { NativeProgramStore } from './native-programs';
-import { NativeAssetLibrary } from './native-assets';
-import { NativeMaterialLibrary } from './native-materials';
-import { NativeMaterialWorkspace } from './native-workspace';
-import type { NativeStorageOptions } from './native-http';
-import {
- createNativeEvaluatorPort,
- type NativeEvaluatorOptions,
- type NativeEvaluatorPort,
-} from './native-evaluator';
-import { NativeBuildIdentities } from './native-build-identity';
-import { HttpFailure, privateResponse, readBounded, serviceFailure } from './http';
-import { createNativeRenderPort } from './native-render';
-import { RENDER_LIMITS } from './render-limits';
-
-export interface NativeMcpRuntime {
- createServer: (context: KilnToolContext) => Server;
- evaluatorPort: EvaluatorPortV2 & Partial<Pick<NativeEvaluatorPort, 'executionImage'>>;
- viewRenderPort?: PbrRenderPort;
-}
-
-async function loadInstalledEngine(): Promise<NativeMcpRuntime['createServer']> {
- try {
- const entry = new URL(import.meta.resolve('@instruktlabs/kiln'));
- // This private host pins the engine's shipped bundle alongside its SDK.
- // Do not resolve a checkout source file or a caller-supplied module URL.
- const engine = await import(new URL('../dist/mcp-engine.mjs', entry).href);
- if (typeof engine.createKilnMcpServer !== 'function') throw new Error('Invalid engine');
- return engine.createKilnMcpServer;
- } catch {
- throw new Error('Native engine installation is unavailable');
- }
-}
-
-/** Installed-package nested-isolation route. A failed probe has no fallback. */
-export async function loadNativeMcpRuntime(
- host: IsolatedEvaluatorHost = { bwrapPath: '/usr/bin/bwrap' },
-): Promise<NativeMcpRuntime> {
- const createServer = await loadInstalledEngine();
- try {
- const evaluator = await import('@instruktlabs/kiln/evaluator');
- await evaluator.assertIsolatedEvaluatorReady(host);
- return {
- createServer,
- evaluatorPort: {
- render: (code, options, controls) =>
- evaluator.renderGLBViaIsolatedEvaluator(code, options, { ...controls, host }),
- },
- };
- } catch {
- throw new Error('Native isolation readiness failed; no evaluator is available');
- }
-}
-
-/**
- * Explicit externally isolated profile. The controller supplies the private
- * evaluator route; unavailable transport fails closed on calls. Never selected
- * automatically after a failed nested-isolation readiness check.
- */
-export async function loadContainerMcpRuntime(
- options: NativeEvaluatorOptions = {},
- rendering: { fetch?: (request: Request) => Promise<Response> } = {},
-): Promise<NativeMcpRuntime> {
- return {
- createServer: await loadInstalledEngine(),
- evaluatorPort: createNativeEvaluatorPort(options),
- viewRenderPort: createNativeRenderPort(rendering),
- };
-}
-
-export interface NativeMcpOptions {
- publicOrigin: string;
- storage?: NativeStorageOptions;
- requestTimeoutMs?: number;
- maxConcurrent?: number;
- maxResponseBytes?: number;
-}
-
-const REQUEST_BYTES = 1024 * 1024;
-const MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
-function integer(value: number, max: number): number {
- if (!Number.isSafeInteger(value) || value < 1 || value > max)
- throw new Error('Invalid native host limit');
- return value;
-}
-
-/** One externally tenant-bound native host. Never expose its private port directly. */
-export function createNativeMcpHandler(runtime: NativeMcpRuntime, options: NativeMcpOptions) {
- if (
- typeof runtime?.createServer !== 'function' ||
- typeof runtime?.evaluatorPort?.render !== 'function'
- )
- throw new Error('A qualified evaluator port is required');
- const publicOrigin = new URL(options.publicOrigin);
- if (publicOrigin.protocol !== 'https:' || publicOrigin.origin !== options.publicOrigin)
- throw new Error('Invalid public origin');
- const timeoutMs = integer(options.requestTimeoutMs ?? 120_000, 120_000);
- const maxConcurrent = integer(options.maxConcurrent ?? 1, 4);
- const maxResponseBytes = integer(
- options.maxResponseBytes ?? MAX_RESPONSE_BYTES,
- MAX_RESPONSE_BYTES,
- );
- const active = new Set<{ abort: () => void }>();
- let closed = false;
-
- return {
- async close() {
- closed = true;
- for (const lease of active) lease.abort();
- },
- async fetch(request: Request): Promise<Response> {
- // The outside controller owns identity, authentication and port reachability.
- const url = new URL(request.url);
- if (url.origin !== 'http://kiln-native.internal')
- return privateResponse(new Response('Invalid internal origin', { status: 421 }));
- if (url.pathname !== '/mcp')
- return privateResponse(new Response('Not found', { status: 404 }));
- if (url.search || url.hash)
- return privateResponse(new Response('Invalid internal request', { status: 400 }));
- if (
- (request.headers.has('origin') && request.headers.get('origin') !== options.publicOrigin) ||
- ['authorization', 'cookie', 'x-kiln-tenant', 'x-user-id', 'cf-access-jwt-assertion'].some(
- (name) => request.headers.has(name),
- )
- )
- return privateResponse(
- new Response('Forbidden internal credentials or Origin', { status: 403 }),
- );
- if (closed) return privateResponse(new Response('Native host is closed', { status: 503 }));
- if (active.size >= maxConcurrent)
- return privateResponse(
- new Response('Native host is busy; retry shortly', {
- status: 429,
- headers: { 'retry-after': '2' },
- }),
- );
-
- const controller = new AbortController();
- let timedOut = false;
- let responseDone = false;
- let evaluations = 0;
- let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
- let transport: ReturnType<typeof createMcpHandler> | undefined;
- const lease = { abort: () => controller.abort() };
- const release = () => {
- if (responseDone && evaluations === 0) active.delete(lease);
- };
- const abortError = () =>
- new HttpFailure(
- timedOut ? 504 : 499,
- timedOut ? 'Native request timed out' : 'Native request cancelled',
- );
- let rejectAbort: (reason: unknown) => void = () => {};
- const aborted = new Promise<never>((_, reject) => {
- rejectAbort = reject;
- });
- // Body admission or an already-aborted caller can fail before fetch races it.
- void aborted.catch(() => {});
- const onAbort = () => {
- rejectAbort(abortError());
- void reader?.cancel().catch(() => {});
- finish();
- };
- controller.signal.addEventListener('abort', onAbort, { once: true });
- request.signal.addEventListener('abort', lease.abort, { once: true });
- active.add(lease);
- const timer = setTimeout(() => {
- timedOut = true;
- controller.abort();
- }, timeoutMs);
- const finish = () => {
- if (responseDone) return;
- responseDone = true;
- clearTimeout(timer);
- request.signal.removeEventListener('abort', lease.abort);
- controller.signal.removeEventListener('abort', onAbort);
- void transport?.close().catch(() => {});
- release();
- };
- try {
- if (request.signal.aborted) controller.abort();
- if (controller.signal.aborted) throw abortError();
- const declared = request.headers.get('content-length');
- if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > REQUEST_BYTES))
- throw new HttpFailure(413, 'Request too large');
- const bytes = await readBounded(request.body, REQUEST_BYTES, controller.signal);
- const incoming = new Request(request, {
- body: request.body === null ? undefined : bytes,
- signal: controller.signal,
- });
- transport = createMcpHandler(
- () => {
- const storage = { ...options.storage, signal: () => controller.signal };
- const materials = new NativeMaterialLibrary(storage);
- const builds = runtime.evaluatorPort.executionImage
- ? new NativeBuildIdentities()
- : undefined;
- const assets = new NativeAssetLibrary({
- ...storage,
- materials,
- executionIdentity: builds ? (draft) => builds.forDraft(draft) : undefined,
- });
- return runtime.createServer({
- programStore: new NativeProgramStore(storage),
- assetLibrary: assets,
- materialLibrary: materials,
- workspace: new NativeMaterialWorkspace(materials),
- assetDownloadUrls: (collection, assetId, revisionId) =>
- assets.downloadUrls(options.publicOrigin, collection, assetId, revisionId),
- evaluatorProfile: 'evaluator-required',
- evaluatorPort: {
- render: async (code, renderOptions, controls) => {
- if (controller.signal.aborted) throw abortError();
- evaluations++;
- try {
- const result = await runtime.evaluatorPort.render(
- code,
- renderOptions,
- controls,
- );
- if (controller.signal.aborted) throw abortError();
- builds?.record(
- code,
- result.glb,
- runtime.evaluatorPort.executionImage?.(result),
- );
- return result;
- } finally {
- evaluations--;
- release();
- }
- },
- },
- ...(runtime.viewRenderPort
- ? {
- viewRenderPort: async (input, execution) => {
- if (controller.signal.aborted) throw abortError();
- evaluations++;
- try {
- return await runtime.viewRenderPort!(input, {
- signal: execution?.signal
- ? AbortSignal.any([execution.signal, controller.signal])
- : controller.signal,
- });
- } finally {
- evaluations--;
- release();
- }
- },
- viewRenderTimeoutMs: RENDER_LIMITS.deadlineMs,
- }
- : {}),
- captureLimits: {
- maxTotalPixels: 8 * 1024 * 1024,
- maxOutputBytes: RENDER_LIMITS.pngBytes,
- },
- evaluationControls: () => ({
- signal: controller.signal,
- deadlineMs: Math.min(timeoutMs, 60_000),
- maxGlbBytes: 16 * 1024 * 1024,
- maxResponseBytes: 32 * 1024 * 1024,
- }),
- cacheEvaluations: false,
- cacheCaptures: false,
- });
- },
- {
- legacy: 'stateless',
- maxRequestBodySize: REQUEST_BYTES,
- maxSubscriptions: 0,
- onerror: () => {},
- },
- );
- const pending = transport.fetch(incoming).then((response) => {
- if (responseDone || controller.signal.aborted)
- void response.body?.cancel().catch(() => {});
- return response;
- });
- const response = await Promise.race([pending, aborted]);
- if (!response.body) {
- finish();
- return privateResponse(response);
- }
- reader = response.body.getReader();
- let total = 0;
- const stream = new ReadableStream<Uint8Array>({
- async pull(output) {
- try {
- const chunk = await Promise.race([reader!.read(), aborted]);
- if (chunk.done) {
- output.close();
- finish();
- return;
- }
- total += chunk.value.byteLength;
- if (total > maxResponseBytes)
- throw new HttpFailure(502, 'MCP response exceeds host size limit');
- output.enqueue(chunk.value);
- } catch (error) {
- controller.abort();
- output.error(
- error instanceof HttpFailure ? error : new Error('Native response unavailable'),
- );
- finish();
- }
- },
- cancel() {
- controller.abort();
- void reader?.cancel().catch(() => {});
- finish();
- },
- });
- return privateResponse(
- new Response(stream, { status: response.status, headers: response.headers }),
- );
- } catch (error) {
- void request.body?.cancel().catch(() => {});
- finish();
- return privateResponse(serviceFailure(controller.signal.aborted ? abortError() : error));
- }
- },
- };
-}
diff --git a/hosting/src/native-programs.ts b/hosting/src/native-programs.ts
deleted file mode 100644
index 8595e836..00000000
--- a/hosting/src/native-programs.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import {
- assertProgramRef,
- MAX_PROGRAM_BYTES,
- programNotFound,
- programReference,
- type ProgramStore,
- type ProgramStoreStats,
-} from '../../src/program-store';
-import { HOSTED_PROGRAM_RETENTION } from './program-contract';
-
-import { NativeHttpClient, StorageFailure, type NativeStorageOptions } from './native-http';
-
-const malformed = () => new StorageFailure(502, 'Invalid source storage response');
-const record = (value: unknown): value is Record<string, unknown> =>
- typeof value === 'object' && value !== null && !Array.isArray(value);
-const count = (value: unknown): value is number =>
- typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
-
-/** Native host adapter only. No tenant selector, cloud credential or arbitrary URL is accepted. */
-export class NativeProgramStore implements ProgramStore {
- readonly retention = HOSTED_PROGRAM_RETENTION;
- private readonly storage: NativeHttpClient;
- constructor(options: NativeStorageOptions = {}) {
- this.storage = new NativeHttpClient(options, 'Source storage');
- }
-
- private canonical(ref: string): string {
- assertProgramRef(ref);
- if (ref.startsWith('sha256:')) return ref;
- if (ref.length === 66) return `sha256:${ref.slice(2)}`;
- throw this.notFound(ref);
- }
-
- private notFound(ref: string): Error {
- return programNotFound(ref, 'This account has no retained source for that reference.');
- }
-
- private async json(body?: Uint8Array<ArrayBuffer>): Promise<Record<string, unknown>> {
- const bytes = await this.storage.bytes('/internal/programs', {
- limit: 2048,
- body,
- method: body === undefined ? 'GET' : 'POST',
- statuses: body === undefined ? [200] : [201],
- headers: body === undefined ? undefined : { 'content-type': 'application/javascript' },
- });
- try {
- const value: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
- if (!record(value)) throw malformed();
- return value;
- } catch {
- throw malformed();
- }
- }
-
- async put(code: string): Promise<string> {
- const ref = await programReference(code);
- const response = await this.json(new TextEncoder().encode(code));
- if (
- response.programRef !== ref ||
- response.shortRef !== `p_${ref.slice(7)}` ||
- typeof response.artifactId !== 'string' ||
- !/^[a-f0-9]{32}$/.test(response.artifactId)
- )
- throw malformed();
- return ref;
- }
-
- async get(ref: string): Promise<string> {
- const canonical = this.canonical(ref);
- let bytes: Uint8Array;
- try {
- bytes = await this.storage.bytes(`/internal/programs/${encodeURIComponent(ref)}`, {
- limit: MAX_PROGRAM_BYTES,
- });
- } catch (error) {
- if (error instanceof StorageFailure && error.status === 404) throw this.notFound(ref);
- throw error;
- }
- try {
- const source = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
- if ((await programReference(source)) !== canonical) throw malformed();
- return source;
- } catch {
- throw new StorageFailure(502, 'Stored program integrity check failed');
- }
- }
-
- async shortRef(ref: string): Promise<string> {
- await this.get(ref);
- return `p_${this.canonical(ref).slice(7)}`;
- }
-
- async stats(): Promise<ProgramStoreStats> {
- const value = await this.json();
- if (
- !count(value.entries) ||
- !count(value.bytes) ||
- (value.maxBytes !== undefined && !count(value.maxBytes)) ||
- value.maxSourceBytes !== MAX_PROGRAM_BYTES ||
- value.eviction !== 'none'
- )
- throw malformed();
- return {
- entries: value.entries,
- bytes: value.bytes,
- ...(value.maxBytes === undefined ? {} : { maxBytes: value.maxBytes }),
- maxSourceBytes: MAX_PROGRAM_BYTES,
- eviction: 'none',
- };
- }
-}
diff --git a/hosting/src/native-render.ts b/hosting/src/native-render.ts
deleted file mode 100644
index f773c684..00000000
--- a/hosting/src/native-render.ts
+++ /dev/null
@@ -1,263 +0,0 @@
-import { createHash, randomUUID } from 'node:crypto';
-import {
- validatePbrRenderRequest,
- type PbrRenderRequest,
- type PbrRenderResult,
- type PbrRenderPort,
-} from '@instruktlabs/kiln/composer';
-import { NativeHttpClient } from './native-http';
-import { RENDER_LIMITS } from './render-limits';
-export { RENDER_LIMITS } from './render-limits';
-
-const fail = () => new Error('Invalid hosted render message');
-const hash = (bytes: Uint8Array): `sha256:${string}` =>
- `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
-const object = (value: unknown): Record<string, unknown> => {
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw fail();
- return value as Record<string, unknown>;
-};
-function keys(value: Record<string, unknown>, allowed: readonly string[]) {
- if (Object.keys(value).some((key) => !allowed.includes(key))) throw fail();
-}
-function json(bytes: Uint8Array, limit: number): Record<string, unknown> {
- if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > limit)
- throw fail();
- try {
- return object(
- JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)),
- );
- } catch {
- throw fail();
- }
-}
-function serialize(value: unknown, limit: number): Uint8Array<ArrayBuffer> {
- const bytes = new TextEncoder().encode(JSON.stringify(value));
- if (bytes.byteLength > limit) throw fail();
- return bytes;
-}
-function base64(value: unknown, limit: number): Buffer {
- if (
- typeof value !== 'string' ||
- !value.length ||
- value.length % 4 !== 0 ||
- value.length > Math.ceil(limit / 3) * 4 ||
- !/^[A-Za-z0-9+/]*={0,2}$/.test(value)
- )
- throw fail();
- const bytes = Buffer.from(value, 'base64');
- if (bytes.byteLength > limit || bytes.toString('base64') !== value) throw fail();
- return bytes;
-}
-function admitted(value: unknown): PbrRenderRequest {
- const request = validatePbrRenderRequest(value);
- if (request.glb.byteLength > RENDER_LIMITS.glbBytes) throw fail();
- if (!request.cameras) {
- request.viewDirs ??= [[1, 0.35, 1]];
- request.size ??= 384;
- }
- const width = request.width ?? request.size!;
- const height = request.height ?? request.size!;
- const count = request.cameras?.length ?? request.viewDirs!.length;
- const beauty = request.beautySize ?? 0;
- if (
- Math.max(width, height, beauty) > RENDER_LIMITS.dimension ||
- width * height * count + beauty * beauty > RENDER_LIMITS.pixels
- )
- throw fail();
- return request;
-}
-export interface RenderInput {
- requestId: string;
- inputGlbSha256: `sha256:${string}`;
- request: PbrRenderRequest;
-}
-export function encodeRenderRequest(
- value: PbrRenderRequest,
-): RenderInput & { bytes: Uint8Array<ArrayBuffer> } {
- const request = admitted(value);
- const { glb, ...options } = request;
- const requestId = randomUUID();
- return {
- request,
- requestId,
- inputGlbSha256: hash(glb),
- bytes: serialize(
- {
- version: 'kiln.hosted-render.request.v1',
- requestId,
- glbBase64: Buffer.from(glb).toString('base64'),
- options,
- },
- RENDER_LIMITS.requestBytes,
- ),
- };
-}
-/** Validated before renderer import, GPU initialization or image decoding in the child VM. */
-export function decodeRenderRequest(bytes: Uint8Array): RenderInput {
- const value = json(bytes, RENDER_LIMITS.requestBytes);
- keys(value, ['version', 'requestId', 'glbBase64', 'options']);
- if (
- value.version !== 'kiln.hosted-render.request.v1' ||
- typeof value.requestId !== 'string' ||
- !/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/.test(value.requestId)
- )
- throw fail();
- const options = object(value.options);
- if (Object.hasOwn(options, 'glb')) throw fail();
- const glb = base64(value.glbBase64, RENDER_LIMITS.glbBytes);
- return {
- requestId: value.requestId,
- inputGlbSha256: hash(glb),
- request: admitted({ ...options, glb }),
- };
-}
-interface RenderOutput {
- rendererId: string;
- backend: string;
- software: boolean;
- views: Uint8Array[];
- beauty?: Uint8Array;
- cameras?: PbrRenderResult['cameras'];
- width?: number;
- height?: number;
- lightingPresetId?: string;
-}
-/** No rendering or degradation here; the one-shot producer supplies only rendered bytes. */
-export function encodeRenderResult(
- input: RenderInput,
- output: RenderOutput,
-): Uint8Array<ArrayBuffer> {
- const value = {
- version: 'kiln.hosted-render.result.v1',
- requestId: input.requestId,
- inputGlbSha256: input.inputGlbSha256,
- rendererId: output.rendererId,
- backend: output.backend,
- software: output.software,
- viewsBase64: output.views.map((bytes) => Buffer.from(bytes).toString('base64')),
- ...(output.beauty ? { beautyBase64: Buffer.from(output.beauty).toString('base64') } : {}),
- ...(output.cameras
- ? {
- cameras: output.cameras,
- width: output.width,
- height: output.height,
- lightingPresetId: output.lightingPresetId,
- }
- : {}),
- };
- const bytes = serialize(value, RENDER_LIMITS.responseBytes);
- decodeRenderResult(bytes, input);
- return bytes;
-}
-export function decodeRenderResult(bytes: Uint8Array, input: RenderInput): PbrRenderResult {
- const value = json(bytes, RENDER_LIMITS.responseBytes);
- keys(value, [
- 'version',
- 'requestId',
- 'inputGlbSha256',
- 'rendererId',
- 'backend',
- 'software',
- 'viewsBase64',
- 'beautyBase64',
- 'cameras',
- 'width',
- 'height',
- 'lightingPresetId',
- ]);
- if (
- value.version !== 'kiln.hosted-render.result.v1' ||
- value.requestId !== input.requestId ||
- value.inputGlbSha256 !== input.inputGlbSha256 ||
- value.software !== true ||
- value.backend !== 'vulkan' ||
- typeof value.rendererId !== 'string' ||
- !value.rendererId.trim() ||
- value.rendererId.length > 512 ||
- [...value.rendererId].some(
- (character) => character.charCodeAt(0) < 32 || character === '\u007f',
- )
- )
- throw fail();
- const expected = input.request.cameras?.length ?? input.request.viewDirs!.length;
- if (!Array.isArray(value.viewsBase64) || value.viewsBase64.length !== expected) throw fail();
- const viewsPng = value.viewsBase64.map((value) => base64(value, RENDER_LIMITS.pngBytes));
- const beautyPng =
- value.beautyBase64 === undefined
- ? undefined
- : base64(value.beautyBase64, RENDER_LIMITS.pngBytes);
- if (Boolean(beautyPng) !== Boolean(input.request.beautySize)) throw fail();
- if (
- viewsPng.reduce((sum, png) => sum + png.byteLength, beautyPng?.byteLength ?? 0) >
- RENDER_LIMITS.pngBytes
- )
- throw fail();
- const result: PbrRenderResult = {
- ok: true,
- rendererId: value.rendererId,
- backend: 'vulkan',
- viewsPng,
- derivativeFidelity: { materialFaithful: true, inputGlbSha256: input.inputGlbSha256 },
- ...(beautyPng ? { beautyPng } : {}),
- };
- if (input.request.cameras) {
- const validated = validatePbrRenderRequest({
- glb: input.request.glb,
- cameras: value.cameras,
- width: value.width,
- height: value.height,
- lightingPresetId: value.lightingPresetId,
- });
- if (
- !validated.cameras ||
- JSON.stringify(validated.cameras) !== JSON.stringify(input.request.cameras) ||
- validated.width !== input.request.width ||
- validated.height !== input.request.height ||
- validated.lightingPresetId !== (input.request.lightingPresetId ?? 'review-neutral-v1')
- )
- throw fail();
- Object.assign(result, {
- cameras: validated.cameras,
- width: validated.width,
- height: validated.height,
- lightingPresetId: validated.lightingPresetId,
- });
- } else if (
- ['cameras', 'width', 'height', 'lightingPresetId'].some((key) => Object.hasOwn(value, key))
- )
- throw fail();
- return result;
-}
-export function createNativeRenderPort(
- options: { fetch?: (request: Request) => Promise<Response> } = {},
-): PbrRenderPort {
- return async (request, execution) => {
- try {
- execution?.signal?.throwIfAborted();
- const input = encodeRenderRequest(request);
- const client = new NativeHttpClient(
- { fetch: options.fetch, signal: () => execution?.signal, timeoutMs: 60_000 },
- 'Renderer',
- 'renderer',
- );
- const bytes = await client.bytes('/render', {
- method: 'POST',
- body: input.bytes,
- headers: {
- 'content-type': 'application/json',
- 'x-kiln-deadline-ms': String(RENDER_LIMITS.deadlineMs),
- 'x-kiln-max-response-bytes': String(RENDER_LIMITS.responseBytes),
- },
- limit: RENDER_LIMITS.responseBytes,
- });
- return decodeRenderResult(bytes, input);
- } catch {
- // The engine owns PNG validation, deadline policy and CPU degradation.
- return {
- ok: false,
- rendererId: 'unavailable',
- error: 'Hosted software rendering is unavailable',
- };
- }
- };
-}
diff --git a/hosting/src/native-workspace.ts b/hosting/src/native-workspace.ts
deleted file mode 100644
index b30983b4..00000000
--- a/hosting/src/native-workspace.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { AsyncLocalStorage } from 'node:async_hooks';
-import {
- workspaceSelectionSchema,
- type WorkspaceBinding,
- type WorkspacePort,
- type WorkspaceSelection,
-} from '@instruktlabs/kiln/workspace';
-import {
- MATERIAL_LIBRARY_LIMITS,
- type MaterialLibrary,
- type MaterialRecordV1,
-} from '@instruktlabs/kiln/material-library';
-import { createMaterialLibraryPayload } from '@instruktlabs/kiln/material-library/node';
-
-/** Standalone operations bind explicit material revisions, never a local directory or inferred project. */
-export class NativeMaterialWorkspace implements WorkspacePort {
- private readonly active = new AsyncLocalStorage<WorkspaceBinding>();
- constructor(private readonly materials: MaterialLibrary) {}
- current(): WorkspaceBinding | undefined {
- return this.active.getStore();
- }
-
- async run<T>(requested: WorkspaceSelection, execute: () => Promise<T>): Promise<T> {
- const selection = workspaceSelectionSchema.parse(requested);
- if (selection.projectId != null || selection.projectRevision !== undefined)
- throw new Error(
- 'Hosted project storage is not available; omit the project or use projectId: null with explicit materialDependencies.',
- );
- const existing = this.current();
- const inherit = existing && selection.projectId !== null;
- if (inherit && selection.materialDependencies === undefined) return execute();
- const pins = new Map<string, WorkspaceBinding['materialDependencies'][number]>();
- for (const pin of inherit ? existing.materialDependencies : []) pins.set(pin.resourceId, pin);
- for (const pin of selection.materialDependencies ?? []) pins.set(pin.resourceId, pin);
- const dependencies = [...pins.values()].sort((a, b) =>
- a.resourceId.localeCompare(b.resourceId),
- );
- if (dependencies.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
- throw new Error(
- `An evaluation may resolve at most ${MATERIAL_LIBRARY_LIMITS.maxPayloadRecords} material resources; select a smaller dependency closure.`,
- );
- // Validate the entire selection before reading any tenant storage.
- for (const pin of dependencies) {
- if (
- !/^[a-z][a-z0-9_-]{0,79}(?![\s\S])/.test(pin.resourceId) ||
- !/^sha256:[a-f0-9]{64}(?![\s\S])/.test(pin.revisionId)
- )
- throw new Error('Invalid material identity');
- if (pin.sha256 !== pin.revisionId)
- throw new Error(`Material lock hash mismatch: ${pin.resourceId}`);
- }
- const records: MaterialRecordV1[] = [];
- let bytes = 0,
- pixels = 0;
- // Bound accumulated decoded resources before reading another record. The
- // native library separately verifies each immutable record before returning it.
- for (const pin of dependencies) {
- let record: MaterialRecordV1;
- try {
- record = await this.materials.read(pin.resourceId, pin.revisionId);
- } catch {
- throw new Error(`Locked material unavailable: ${pin.resourceId} at ${pin.revisionId}`);
- }
- if (
- record.manifest.materialId !== pin.resourceId ||
- record.manifest.revisionId !== pin.revisionId
- )
- throw new Error('Locked material identity mismatch');
- for (const map of record.manifest.maps) {
- bytes += map.bytes;
- pixels += map.width * map.height;
- }
- if (
- bytes > MATERIAL_LIBRARY_LIMITS.maxPayloadBytes ||
- pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels
- )
- throw new Error('Material resource payload exceeds byte or pixel budget');
- records.push(record);
- }
- const materialResources = await createMaterialLibraryPayload(records);
- return this.active.run({ materialDependencies: dependencies, materialResources }, execute);
- }
-}
diff --git a/hosting/src/operations.ts b/hosting/src/operations.ts
deleted file mode 100644
index 07925cf2..00000000
--- a/hosting/src/operations.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { routeClass } from './request-limits';
-import type { TenantEnv } from './gateway';
-
-export interface OperationsEnv {
- OPERATIONS?: Pick<AnalyticsEngineDataset, 'writeDataPoint'>;
-}
-interface DeletionHealth {
- pending: number;
- oldestPendingMs: number;
- overdue: number;
-}
-interface ComputeHealth {
- paused: boolean;
- activeRequests: number;
- pendingCleanup: number;
- maxConcurrent: number;
-}
-export interface OperationalHealth {
- deletion: DeletionHealth | null;
- compute: ComputeHealth | null;
-}
-const count = (value: unknown): value is number =>
- typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
-function deletionHealth(value: unknown): DeletionHealth | null {
- if (!value || typeof value !== 'object') return null;
- const v = value as DeletionHealth;
- if (!count(v.pending) || !count(v.oldestPendingMs) || !count(v.overdue) || v.overdue > v.pending)
- return null;
- return { pending: v.pending, oldestPendingMs: v.oldestPendingMs, overdue: v.overdue };
-}
-function computeHealth(value: unknown): ComputeHealth | null {
- if (!value || typeof value !== 'object') return null;
- const v = value as ComputeHealth;
- if (
- typeof v.paused !== 'boolean' ||
- !count(v.activeRequests) ||
- !count(v.pendingCleanup) ||
- !count(v.maxConcurrent) ||
- v.maxConcurrent === 0 ||
- v.pendingCleanup > v.activeRequests
- )
- return null;
- return {
- paused: v.paused,
- activeRequests: v.activeRequests,
- pendingCleanup: v.pendingCleanup,
- maxConcurrent: v.maxConcurrent,
- };
-}
-function emit(env: OperationsEnv, index: string, labels: string[], values: number[]): void {
- try {
- // Explicit positional fields only. Never log a Request, response, exception,
- // account, URL, environment or arbitrary caller-provided object.
- env.OPERATIONS?.writeDataPoint({
- indexes: [index],
- blobs: ['kiln.ops.v1', ...labels],
- doubles: [1, ...values],
- });
- } catch {
- /* Observability failure cannot change authorization or cleanup. */
- }
-}
-export function recordResponse(
- env: OperationsEnv,
- path: string,
- status: number,
- elapsedMs: number,
-): void {
- if (
- typeof path !== 'string' ||
- !Number.isInteger(status) ||
- status < 100 ||
- status > 599 ||
- !Number.isFinite(elapsedMs) ||
- elapsedMs < 0 ||
- elapsedMs > Number.MAX_SAFE_INTEGER
- )
- return;
- emit(env, 'http', ['http', routeClass(path), String(status)], [Math.round(elapsedMs)]);
-}
-export function recordHealth(
- env: OperationsEnv,
- health: OperationalHealth,
- recovered: boolean,
-): void {
- const deletion = deletionHealth(health.deletion),
- compute = computeHealth(health.compute);
- emit(
- env,
- 'health:deletion',
- ['health', 'deletion', deletion ? 'ok' : 'unavailable'],
- deletion
- ? [deletion.pending, deletion.oldestPendingMs, deletion.overdue, Number(recovered === true)]
- : [-1, -1, -1, Number(recovered === true)],
- );
- emit(
- env,
- 'health:compute',
- ['health', 'compute', compute ? 'ok' : 'unavailable'],
- compute
- ? [
- Number(compute.paused),
- compute.activeRequests,
- compute.pendingCleanup,
- compute.maxConcurrent,
- ]
- : [-1, -1, -1, -1],
- );
-}
-async function boundedRead(read: () => Promise<unknown>): Promise<unknown> {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- return await Promise.race([
- read(),
- new Promise<null>((resolve) => {
- timer = setTimeout(() => resolve(null), 2000);
- }),
- ]);
- } catch {
- return null;
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
-}
-export async function readOperationalHealth(
- env: Pick<TenantEnv, 'NATIVE_COMPUTE'> & { ACCOUNTS: D1Database },
- now = Date.now(),
-): Promise<OperationalHealth> {
- const [deletion, compute] = await Promise.all([
- boundedRead(async () =>
- env.ACCOUNTS.withSession('first-primary')
- .prepare(
- `SELECT COUNT(*) AS pending, COALESCE(MAX(0,?-MIN(created_at)),0) AS oldestPendingMs,
- COALESCE(SUM(created_at<=?),0) AS overdue FROM kiln_deletions
- WHERE phase IN ('compute','storage','grants','identity')`,
- )
- .bind(now, now - 15 * 60_000)
- .first(),
- ),
- boundedRead(async () => env.NATIVE_COMPUTE?.health()),
- ]);
- return { deletion: deletionHealth(deletion), compute: computeHealth(compute) };
-}
diff --git a/hosting/src/program-contract.ts b/hosting/src/program-contract.ts
deleted file mode 100644
index f24f1c99..00000000
--- a/hosting/src/program-contract.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export const HOSTED_PROGRAM_RETENTION =
- 'unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas';
diff --git a/hosting/src/programs.ts b/hosting/src/programs.ts
deleted file mode 100644
index 67b318d7..00000000
--- a/hosting/src/programs.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import {
- assertProgramRef,
- MAX_PROGRAM_BYTES,
- programNotFound,
- programReference,
- type ProgramStore,
- type ProgramStoreStats,
-} from '../../src/program-store';
-import type { ArtifactStore } from './artifact-store';
-import { HttpFailure, readBounded } from './http';
-import { HOSTED_PROGRAM_RETENTION } from './program-contract';
-
-const SOURCE_NAME = 'source.kiln.js';
-const SOURCE_MEDIA = 'application/javascript';
-
-export function decodeProgram(bytes: Uint8Array): string {
- try {
- return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
- } catch {
- throw new HttpFailure(400, 'Program must be valid UTF-8');
- }
-}
-
-/** A host adapter for the existing engine contract, scoped to one tenant store. */
-export class HostedProgramStore implements ProgramStore {
- private readonly pending = new Map<string, Promise<string>>();
- readonly retention = HOSTED_PROGRAM_RETENTION;
-
- constructor(private readonly artifacts: ArtifactStore) {}
-
- private canonical(ref: string): string {
- try {
- assertProgramRef(ref);
- } catch {
- throw new HttpFailure(400, 'Invalid program reference');
- }
- if (ref.startsWith('sha256:')) return ref;
- // Full-digest p_ handles are a supported engine shape. They are immutable
- // without an ever-growing alias table or reassigning an expired short prefix.
- if (ref.length === 66) return `sha256:${ref.slice(2)}`;
- throw this.notFound(ref);
- }
-
- private notFound(ref: string) {
- return new HttpFailure(
- 404,
- programNotFound(
- ref,
- 'This account has no retained source for that reference; unsaved source expires after seven days.',
- ).message,
- );
- }
-
- artifact(ref: string) {
- const canonical = this.canonical(ref);
- const record = this.artifacts.findContent(canonical.slice(7), SOURCE_NAME, SOURCE_MEDIA);
- if (!record) throw this.notFound(ref);
- return record;
- }
-
- async get(ref: string): Promise<string> {
- const record = this.artifact(ref);
- const response = await this.artifacts.download(record.id);
- try {
- const code = decodeProgram(await readBounded(response.body, MAX_PROGRAM_BYTES));
- if ((await programReference(code)) !== this.canonical(ref))
- throw new Error('Source digest mismatch');
- return code;
- } catch {
- throw new HttpFailure(502, 'Stored program integrity check failed');
- }
- }
-
- async put(code: string): Promise<string> {
- let ref: string;
- try {
- ref = await programReference(code);
- } catch {
- throw new HttpFailure(400, 'Program must be valid Unicode within the 1 MiB source limit');
- }
- const existing = this.pending.get(ref);
- if (existing) return existing;
- const storing = this.store(ref, code);
- this.pending.set(ref, storing);
- try {
- return await storing;
- } finally {
- this.pending.delete(ref);
- }
- }
-
- private async store(ref: string, code: string): Promise<string> {
- if (this.artifacts.findContent(ref.slice(7), SOURCE_NAME, SOURCE_MEDIA)) {
- await this.get(ref);
- return ref;
- }
- const bytes = new TextEncoder().encode(code);
- await this.artifacts.upload(
- new Request('https://tenant.internal/internal/artifacts', {
- method: 'POST',
- body: bytes,
- headers: {
- 'content-type': SOURCE_MEDIA,
- 'content-length': String(bytes.byteLength),
- 'x-artifact-name': SOURCE_NAME,
- 'x-artifact-sha256': ref.slice(7),
- },
- }),
- );
- return ref;
- }
-
- async shortRef(ref: string): Promise<string> {
- await this.get(ref);
- return `p_${this.canonical(ref).slice(7)}`;
- }
-
- async stats(): Promise<ProgramStoreStats> {
- return {
- ...this.artifacts.contentStats(SOURCE_NAME, SOURCE_MEDIA),
- maxSourceBytes: MAX_PROGRAM_BYTES,
- eviction: 'none',
- };
- }
-}
diff --git a/hosting/src/public-pages.ts b/hosting/src/public-pages.ts
deleted file mode 100644
index d40eeef6..00000000
--- a/hosting/src/public-pages.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { escapeHtml, htmlPage } from './html-page';
-import { HttpFailure } from './http';
-
-const contact = '<a href="mailto:[email protected]">[email protected]</a>';
-
-function home(origin: string): Response {
- return htmlPage(
- 'Editable 3D assets',
- `<h1>From JavaScript to editable 3D assets</h1>
-<p>Kiln lets your coding assistant create, inspect, render and save 3D assets. Keep the source, materials and GLB together so you can reopen and change your work.</p>
-<section><h2>Use hosted Kiln</h2><p>Hosted access is free within personal usage and storage quotas. Sign in with Google or GitHub to keep your saved work private and connect an app. No payment information is required.</p>
-<p><a href="/account">Sign in or manage your account</a></p><p>MCP server address:<br><code>${escapeHtml(origin)}/mcp</code></p>
-<p>Your app must support a remote MCP server with sign-in. Review the app name and requested access before connecting it.</p></section>
-<section><h2>Work locally</h2><p>The open source <code>@instruktlabs/kiln</code> package includes the SDK, CLI and local MCP server. Local use does not require a Kiln account.</p><p><a href="https://github.com/instruktlabs/kiln">Read the installation guide and source</a></p></section>
-<p>Kiln is operated by Instrukt Labs. Read <a href="/privacy">how hosted data is handled</a> or <a href="/support">get help</a>.</p>`,
- );
-}
-
-function privacy(): Response {
- return htmlPage(
- 'Privacy',
- `<h1>Hosted Kiln privacy</h1><p>This notice covers the Kiln hosted service operated by Instrukt Labs. It does not cover your local Kiln workspace or the assistant you connect. Contact ${contact} about privacy or access to your data.</p>
-<section><h2>Sign-in and account data</h2>
-<p>Google or GitHub confirms your identity. Kiln receives provider identity and profile information during sign-in, and keeps the provider name and stable account identifier to associate you with a Kiln account. It does not retain your provider profile name, photo or email address. Provider access and ID tokens are discarded after verification.</p>
-<p>Google sign-in requests basic identity and profile access. GitHub sign-in uses your public identity without requesting repository or private-email permissions. Kiln does not request Google Drive, Gmail or GitHub repository access.</p>
-<p>Kiln stores its own account, session, connected-app, usage and security-activity records. Essential cookies keep sign-in, account confirmations and your browser session bound to you. Browser sessions expire after 30 minutes without activity or 24 hours in total; connected apps can stay authorized for up to 30 days.</p>
-<p>Adding another sign-in method requires confirmation of both identities. Accounts are never automatically joined by matching email addresses. Security notices are in-app only: Kiln does not collect a separate security contact email or send alerts about sign-in method changes or deletion.</p></section>
-<section><h2>Your source and assets</h2>
-<p>Kiln processes the source, geometry, material files, previews, names and metadata you or your connected app send. It stores these privately for your account and returns requested results to the apps you authorize. The hosted service does not call a model provider. Your assistant handles its own conversations and copies under its provider's policies.</p>
-<p>Unsaved work expires seven days after upload; background cleanup removes expired files. Saved source, assets and material dependencies remain until deleted, within your storage quota. Removing a saved revision removes that entry; files shared with another revision can remain, and unsaved copies follow the seven-day policy. Download links require your signed-in account and expire after ten minutes.</p></section>
-<section><h2>Service providers and operations</h2>
-<p>Cloudflare processes network requests, runs Kiln and stores hosted data. Google and GitHub process the sign-in you choose. Kiln's operational metrics record request categories, status codes, timing and aggregate service health, without source, file contents, account identifiers, IP addresses or credentials. These metrics are retained for three months. Cloudflare also processes its own infrastructure and security data under its policies.</p>
-<p>Kiln pages do not load advertising or tracking scripts. If you contact support, your email and the details you choose to send are processed in the support inbox to handle your request. Do not include passwords, tokens or recovery codes.</p></section>
-<section><h2>Your controls and deletion</h2>
-<p>Use <a href="/account">Your account</a> to review sign-in methods, security activity and connected apps. Browser sign-out leaves app connections working. Disconnecting an app blocks its new requests but does not erase copies already returned to it or cancel work already admitted.</p>
-<p>You can download your work and request account deletion after confirming a linked sign-in method. Access is revoked while cleanup stops outstanding work and removes active files and identity records. If cleanup is interrupted, the request stays pending while it retries. The private deletion receipt is available for seven days after completion.</p>
-<p>Minimal pseudonymous retirement records remain to prevent old credentials or delayed jobs from restoring deleted data. Expiring authorization records and provider backups are separate from active-service deletion: Cloudflare's database recovery history can retain prior account data for up to 30 days. Deletion does not remove copies you downloaded or sent to another app.</p>
-<p>For access, correction or deletion questions, contact ${contact}. Use the identity provider's own account controls for your Google or GitHub data.</p></section>`,
- );
-}
-
-function support(): Response {
- return htmlPage(
- 'Support',
- `<h1>Get help with Kiln</h1><p>Kiln is an open source project operated by Instrukt Labs. Hosted access is free within quotas; there is no paid support tier.</p>
-<section><h2>Account, privacy or security</h2><p>Email ${contact}. Include a short description and, when relevant, the time and the support reference shown by Kiln. Never send passwords, access tokens, recovery codes or private source you do not want to share.</p><p>Use email for security reports and private account details. Do not put them in public issues. Support cannot restore account access solely because an email address matches; your linked Google or GitHub identity establishes ownership.</p></section>
-<section><h2>Common account questions</h2><p>Use the same sign-in method as before to reach your work. Add another method from <a href="/account">Your account</a>; separately created accounts cannot be merged.</p><p>A download link requires the account that saved the asset. If it has expired, request a fresh link from your connected app. A quota response means the operation was refused; try again after the stated delay or free saved storage as appropriate.</p><p>Browser sign-out and disconnecting an app are separate controls. Account deletion removes hosted files, so download anything you want to keep first.</p></section>
-<section><h2>Bug reports and contributions</h2><p><a href="https://github.com/instruktlabs/kiln/issues">Open a public issue</a> with your Kiln version, operating system, expected behavior and a small reproduction you are comfortable making public. Remove credentials and private assets before posting.</p></section>`,
- );
-}
-
-function terms(): Response {
- return htmlPage(
- 'Terms',
- `<h1>Terms of hosted use</h1><p>These terms describe use of the hosted Kiln service operated by Instrukt Labs. By using hosted Kiln, you agree to these terms. Questions can be sent to ${contact}.</p>
-<section><h2>Access and accounts</h2>
-<p>Hosted access is free within usage and storage quotas. Kiln does not collect payment details or charge your account for exceeding a quota. Requests can be limited, refused or paused when capacity is unavailable. Voluntary sponsorship does not create a paid service level or change your quotas.</p>
-<p>Use an identity you control when signing in with Google or GitHub. Keep that account secure and review which apps you connect to Kiln. A connected app can act on the work in your Kiln account within the access you grant. Account controls let you disconnect an app or request account deletion after identity confirmation.</p>
-<p>Security activity is shown in your account. Kiln v1 does not send email alerts about sign-in changes or deletion requests.</p></section>
-<section><h2>Your work and permissions</h2>
-<p>You retain whatever rights you hold in your inputs and outputs. Instrukt Labs does not claim ownership of your assets. You authorize Kiln and its service providers to process, store, render and return your submitted work as needed to operate the service and fulfill your requests. This does not authorize publication of your private assets.</p>
-<p>Submit only material you have permission to use. You are responsible for respecting copyright, licenses and other rights in your inputs and in how you use the results. Kiln does not determine whether an asset is legally cleared for your intended use.</p>
-<p>The <a href="/privacy">privacy notice</a> explains account data, service providers, retention and deletion. Unsaved work expires after seven days; saved work remains within quota until deleted. Download copies you need to keep independently. Your assistant and other apps may retain their own copies under their own terms.</p></section>
-<section><h2>Acceptable use</h2>
-<p>Use Kiln lawfully. Do not attempt to access another person's private assets, bypass account or resource limits, interfere with the service, or run code intended to escape evaluation boundaries. Do not submit passwords, provider keys, authentication codes or payment information as source or tool arguments.</p>
-<p>We may limit or suspend hosted access to address abuse, security problems, capacity or service maintenance. Contact support if you believe a restriction is mistaken.</p></section>
-<section><h2>Availability and results</h2>
-<p>Hosted Kiln is provided as available, without a guaranteed uptime or response time. Features and limits may change. Experimental helpers are labeled in the catalog. Inspect outputs before relying on them: syntax checks, structural QA and rendered previews do not guarantee suitability for your destination application.</p>
-<p>These hosted-use terms do not replace the MIT license for the open source Kiln software or any licenses attached to material resources. You can use the local package independently of the hosted service.</p></section>
-<section><h2>Changes and contact</h2>
-<p>Updates to these terms will be posted here. Material changes to hosted access or data handling will be surfaced in the service before they take effect; a policy edit does not authorize an undisclosed new use of existing private data. For support, privacy or security questions, contact ${contact}.</p></section>`,
- );
-}
-
-/** Public information is available without authentication or a storage lookup. */
-export function publicPage(request: Request, origin: string): Response | undefined {
- const url = new URL(request.url);
- if (!['/', '/privacy', '/support', '/terms'].includes(url.pathname)) return undefined;
- if (url.search)
- throw new HttpFailure(400, 'Query parameters are not supported on information pages');
- if (request.method !== 'GET' && request.method !== 'HEAD') {
- if (!request.bodyUsed) void request.body?.cancel().catch(() => {});
- return new Response('Method not allowed', { status: 405, headers: { allow: 'GET, HEAD' } });
- }
- const response =
- url.pathname === '/'
- ? home(origin)
- : url.pathname === '/privacy'
- ? privacy()
- : url.pathname === '/terms'
- ? terms()
- : support();
- return request.method === 'HEAD' ? new Response(null, { headers: response.headers }) : response;
-}
diff --git a/hosting/src/public-tools.ts b/hosting/src/public-tools.ts
deleted file mode 100644
index fe362d3f..00000000
--- a/hosting/src/public-tools.ts
+++ /dev/null
@@ -1,227 +0,0 @@
-import type { Tool } from '@modelcontextprotocol/server';
-
-export const HOSTED_TOOL_SURFACE = 'kiln.hosted-tools.v1';
-
-interface Operation {
- description: string;
- fields: readonly string[];
-}
-
-// Routing and field selection only. Every field's schema comes from the pinned
-// engine registry; the engine still owns parsing, requirements and execution.
-const actions: Record<string, Record<string, Operation>> = {
- kiln_renderer: {
- status: { description: 'Inspect the hosted renderer status.', fields: [] },
- reprobe: {
- description:
- 'Refresh renderer availability for this hosted call. Does not install or repair a service.',
- fields: [],
- },
- },
- kiln_material: {
- presets: {
- description: 'List shipped material recipes, optionally filtered by tag.',
- fields: ['tag'],
- },
- 'create-preset': {
- description:
- 'Bake and retain an immutable material from a shipped preset. Supply presetId, seed, creator and license; pin the returned materialId/revisionId for rendering.',
- fields: ['presetId', 'seed', 'creator', 'license', 'size', 'materialId'],
- },
- list: {
- description: 'List private material revisions, optionally filtered by tag.',
- fields: ['tag'],
- },
- get: {
- description:
- 'Read a private material revision, provenance and portable material specification. Supply materialId; omit revisionId only when the material has one revision.',
- fields: ['materialId', 'revisionId'],
- },
- 'create-procedural': {
- description:
- 'Bake and retain an immutable material from a bounded procedural draft. Supply draft; pin the returned materialId/revisionId for rendering. Does not fetch URLs or execute source.',
- fields: ['draft'],
- },
- import: {
- description:
- 'Import complete normalized material records and embedded PNGs into the private account. Supply payload. Does not fetch URLs or execute source.',
- fields: ['payload'],
- },
- },
- kiln_assets: {
- collections: {
- description:
- 'List the private account asset collections. A collection is a storage destination, not project membership.',
- fields: [],
- },
- catalog: {
- description: 'Search saved assets across the private account collections, with pagination.',
- fields: ['assetId', 'query', 'offset', 'limit'],
- },
- list: {
- description: 'Search saved assets in one private account collection, with pagination.',
- fields: ['collection', 'assetId', 'query', 'offset', 'limit'],
- },
- get: {
- description:
- 'Read a saved asset revision and its authenticated download links. Supply assetId; omit revisionId for the newest revision.',
- fields: ['collection', 'assetId', 'revisionId'],
- },
- restore: {
- description:
- 'Restore exact saved source as a retained programRef for editing or rendering. Supply assetId; omit revisionId for the newest revision. Does not overwrite the saved revision. Binary-only assets have no source.',
- fields: ['collection', 'assetId', 'revisionId'],
- },
- },
-};
-
-const direct = new Set([
- 'kiln_discover',
- 'kiln_validate',
- 'kiln_render',
- 'kiln_screenshot_animation',
- 'kiln_view_interior',
- 'kiln_inspect',
- 'kiln_edit',
- 'kiln_source',
- 'kiln_save',
- 'kiln_present',
- 'kiln_export',
- 'kiln_import',
-]);
-
-const nativeJob =
- ' Runs an isolated hosted job and consumes the account request quota. Temporary job records and any produced artifacts are retained under the hosted retention policy.';
-export const hostedInstructions =
- 'Kiln turns authored JavaScript into editable GLB assets in your private account. ' +
- 'Use kiln_discover for geometry helper contracts and input shapes; it cannot execute operations. ' +
- 'Use kiln_capabilities for hosted runtime facts. Send new source once to kiln_validate or kiln_render, ' +
- 'then preserve the exact programRef for later reads, edits and renders. ' +
- 'Read viewFidelity before judging materials: CPU images show geometry; software-rendered PBR views can show materials. ' +
- 'Rendering is managed by the service and requires no local installation. ' +
- 'Each material, asset and renderer operation has its own named tool. ' +
- 'Engine diagnostics can mention their local multi-action names; use the corresponding exposed operation here. ' +
- 'Save only when requested. Unsaved work expires after seven days; saved assets remain until deleted within quotas.';
-
-interface Route {
- engineName: string;
- fixed: Record<string, unknown>;
- tool: Tool;
-}
-
-export function createPublicTools(engineTools: readonly Tool[]) {
- const routes = new Map<string, Route>();
- const seen = new Set<string>();
- function add(
- original: Tool,
- name: string,
- fields: readonly string[],
- fixed: Record<string, unknown>,
- description: string,
- ) {
- const schema = original.inputSchema;
- const properties = Object.fromEntries(
- fields.map((key) => {
- if (!Object.hasOwn(schema.properties ?? {}, key))
- throw new Error(`Missing engine field ${original.name}.${key}`);
- return [key, structuredClone(schema.properties![key])];
- }),
- );
- const tool = {
- ...structuredClone(original),
- name,
- description: description + (name === 'kiln_discover' ? '' : nativeJob),
- inputSchema: {
- ...structuredClone(schema),
- properties,
- additionalProperties: false,
- required: (schema.required ?? []).filter((key) => fields.includes(key)),
- },
- annotations: {
- ...original.annotations,
- // Even private reads use a stateful, quota-admitted native job. This
- // conservative hosted annotation differs deliberately from local reads.
- readOnlyHint: name === 'kiln_discover',
- destructiveHint: original.annotations?.destructiveHint ?? false,
- openWorldHint: original.annotations?.openWorldHint ?? false,
- },
- } as Tool;
- if (routes.has(name)) throw new Error('Duplicate hosted tool');
- routes.set(name, { engineName: original.name, fixed, tool });
- }
- for (const tool of engineTools) {
- if (seen.has(tool.name)) throw new Error('Duplicate engine tool');
- seen.add(tool.name);
- const operations = actions[tool.name];
- if (operations) {
- const advertised = tool.inputSchema.properties?.action as { enum?: unknown } | undefined;
- const expected = Object.keys(operations).sort();
- if (
- !Array.isArray(advertised?.enum) ||
- JSON.stringify([...advertised.enum].sort()) !== JSON.stringify(expected)
- )
- throw new Error(`Unreviewed engine actions in ${tool.name}`);
- for (const [action, operation] of Object.entries(operations)) {
- add(
- tool,
- `${tool.name}_${action.replaceAll('-', '_')}`,
- operation.fields,
- { action },
- operation.description,
- );
- }
- } else {
- if (!direct.has(tool.name)) throw new Error(`Unreviewed engine tool ${tool.name}`);
- const fields = Object.keys(tool.inputSchema.properties ?? {});
- if (fields.includes('action')) throw new Error(`Unreviewed engine actions in ${tool.name}`);
- if (tool.name === 'kiln_discover') {
- if (!fields.includes('capabilities')) throw new Error('Missing engine capabilities input');
- add(
- tool,
- tool.name,
- fields.filter((key) => key !== 'capabilities'),
- {},
- 'Read the Kiln geometry-helper catalog and complete input shapes. Search with ordinary modeling language, or fetch up to six exact IDs. Does not execute source, fetch URLs, or expose hidden callable operations.',
- );
- add(
- tool,
- 'kiln_capabilities',
- [],
- { capabilities: true },
- 'Inspect this hosted runtime, supported rendering, camera and storage capabilities.',
- );
- } else {
- add(
- tool,
- tool.name,
- fields,
- {},
- tool.name === 'kiln_import'
- ? 'Copy a pinned private asset revision between account collections, preserving identity and provenance. Copies do not track later edits.'
- : (tool.description ?? tool.name),
- );
- }
- }
- }
- if (seen.size !== direct.size + Object.keys(actions).length)
- throw new Error('Missing engine tools');
- return {
- tools: [...routes.values()].map((route) => route.tool),
- // A caller cannot pick an engine action, supply unadvertised arguments, or
- // introduce another tool. No fallback to the local multi-action names.
- resolve(
- name: string,
- args: Record<string, unknown>,
- ): { name: string; arguments: Record<string, unknown> } | undefined {
- const route = routes.get(name);
- if (
- !route ||
- Object.keys(args).some(
- (key) => !Object.hasOwn(route.tool.inputSchema.properties ?? {}, key),
- )
- )
- return undefined;
- return { name: route.engineName, arguments: { ...args, ...route.fixed } };
- },
- };
-}
diff --git a/hosting/src/render-limits.ts b/hosting/src/render-limits.ts
deleted file mode 100644
index 70bc0f7f..00000000
--- a/hosting/src/render-limits.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/** Private host admission bounds; these do not change the published engine limits. */
-export const RENDER_LIMITS = Object.freeze({
- glbBytes: 4 * 1024 * 1024,
- requestBytes: 6 * 1024 * 1024,
- responseBytes: 20 * 1024 * 1024,
- pngBytes: 12 * 1024 * 1024,
- dimension: 1024,
- pixels: 3 * 1024 * 1024,
- deadlineMs: 30_000,
-});
diff --git a/hosting/src/render-worker.ts b/hosting/src/render-worker.ts
deleted file mode 100644
index 0074193c..00000000
--- a/hosting/src/render-worker.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { DurableObject } from 'cloudflare:workers';
-import { ContainerRenderJob } from './container-job';
-import { handleRenderRequest } from './evaluation-request';
-
-/** Private image-bound rendering job; no source evaluation or public entrypoint. */
-export class KilnRenderJob extends DurableObject {
- private readonly job = new ContainerRenderJob(this.ctx);
-
- fetch(request: Request): Promise<Response> {
- return handleRenderRequest(request, this.job);
- }
- cancel(): Promise<void> {
- return this.job.cancel();
- }
- alarm(): Promise<void> {
- return this.job.alarm();
- }
-}
-
-export default {
- fetch(): Response {
- return new Response('Not found', { status: 404 });
- },
-};
diff --git a/hosting/src/request-job.ts b/hosting/src/request-job.ts
deleted file mode 100644
index 5995bb02..00000000
--- a/hosting/src/request-job.ts
+++ /dev/null
@@ -1,435 +0,0 @@
-import { ContainerJobFailure, destroyContainer } from './container-job';
-import { HttpFailure, privateResponse, readBounded } from './http';
-import { EXECUTION_PROFILES, type ExecutionKind } from './execution-profiles';
-
-interface RequestRecord {
- state: 'running' | 'closing' | 'finished';
- tenant?: string;
- deadlineAt: number;
- children: { id: string; kind: ExecutionKind }[];
- activeChild?: string;
-}
-
-export interface NativeRequestPorts {
- publicOrigin: string;
- storageInterceptor: Fetcher;
- evaluationInterceptor: Fetcher;
- renderInterceptor: Fetcher;
- storage(tenant: string, request: Request): Promise<Response>;
- evaluate(id: string, request: Request): Promise<Response>;
- cancelEvaluation(id: string): Promise<void>;
- render(id: string, request: Request): Promise<Response>;
- cancelRender(id: string): Promise<void>;
-}
-
-const MCP_HEADERS = new Set([
- 'accept',
- 'content-type',
- 'content-length',
- 'mcp-protocol-version',
- 'mcp-method',
- 'mcp-name',
- 'mcp-session-id',
- 'last-event-id',
-]);
-const STORAGE_HEADERS = new Set([
- 'content-type',
- 'content-length',
- 'x-artifact-name',
- 'x-artifact-sha256',
-]);
-const EVALUATION_HEADERS = new Set([
- 'content-type',
- 'content-length',
- 'x-kiln-deadline-ms',
- 'x-kiln-max-response-bytes',
-]);
-const TRANSPORT_HEADERS = new Set([
- 'accept',
- 'accept-encoding',
- 'accept-language',
- 'connection',
- 'host',
- 'user-agent',
- 'sec-fetch-mode',
-]);
-
-function checkHeaders(request: Request, allowed: Set<string>, transport = false): Headers {
- const headers = new Headers();
- for (const [key, value] of request.headers) {
- if (value.length > 4096 || (!allowed.has(key) && !(transport && TRANSPORT_HEADERS.has(key))))
- throw new HttpFailure(400, 'Invalid private request header');
- if (allowed.has(key)) headers.set(key, value);
- }
- return headers;
-}
-
-export function nativeRequestHeaders(tenant: string, request: Request): Headers {
- if (
- !/^[A-Za-z0-9_-]{43}$/.test(tenant) ||
- request.url !== 'https://tenant.internal/mcp' ||
- !['GET', 'POST', 'DELETE'].includes(request.method)
- )
- throw new HttpFailure(400, 'Invalid native request');
- return checkHeaders(request, MCP_HEADERS);
-}
-
-async function untilAbort<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {
- let abort: () => void = () => {};
- const stopped = new Promise<never>((_, reject) => {
- abort = () => reject(new HttpFailure(499, 'Request cancelled'));
- signal.addEventListener('abort', abort, { once: true });
- if (signal.aborted) abort();
- });
- try {
- return await Promise.race([pending, stopped]);
- } finally {
- signal.removeEventListener('abort', abort);
- }
-}
-
-async function cleanupChild(cancel: Promise<void>): Promise<void> {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- await Promise.race([
- cancel,
- new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(new ContainerJobFailure('CLEANUP_FAILED')), 10_000);
- }),
- ]);
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
-}
-
-/** One coordinator VM per admitted MCP request. Only its outside parent owns tenancy. */
-export class NativeRequestJob {
- private readonly stopped = new AbortController();
- private closing?: Promise<void>;
- constructor(
- private readonly context: Pick<DurableObjectState, 'container' | 'storage'>,
- private readonly ports: NativeRequestPorts,
- ) {}
-
- private check(): void {
- if (this.stopped.signal.aborted) throw new HttpFailure(499, 'Request cancelled');
- }
-
- private async active(): Promise<RequestRecord & { tenant: string }> {
- this.check();
- const record = await this.context.storage.get<RequestRecord>('request');
- this.check();
- if (record?.state !== 'running' || !record.tenant)
- throw new HttpFailure(409, 'Native request is not active');
- if (Date.now() >= record.deadlineAt) throw new HttpFailure(504, 'Native request timed out');
- return record as RequestRecord & { tenant: string };
- }
-
- async run(tenant: string, request: Request, deadlineAt: number): Promise<Response> {
- const container = this.context.container;
- const image = container?.images.coordinator;
- let origin: URL;
- try {
- origin = new URL(this.ports.publicOrigin);
- } catch {
- throw new HttpFailure(503, 'Native host is not configured');
- }
- if (
- !container ||
- !image ||
- image.length > 512 ||
- !/^[a-zA-Z0-9._:/-]+@sha256:[a-f0-9]{64}$/.test(image) ||
- origin.protocol !== 'https:' ||
- origin.origin !== this.ports.publicOrigin
- )
- throw new HttpFailure(503, 'Native host is not configured');
- if (
- !Number.isSafeInteger(deadlineAt) ||
- deadlineAt <= Date.now() ||
- deadlineAt > Date.now() + 120_000
- )
- throw new HttpFailure(400, 'Invalid native request');
- const headers = nativeRequestHeaders(tenant, request);
- const admitted = await this.context.storage.transaction(async (tx) => {
- if (await tx.get('request')) return false;
- await tx.put('request', {
- state: 'running',
- tenant,
- deadlineAt,
- children: [],
- } satisfies RequestRecord);
- await tx.setAlarm(deadlineAt);
- return true;
- });
- if (!admitted) throw new HttpFailure(409, 'Native request already used');
- const signal = AbortSignal.any([request.signal, this.stopped.signal]);
- const check = () => {
- this.check();
- if (Date.now() >= deadlineAt) throw new HttpFailure(504, 'Native request timed out');
- if (signal.aborted) throw new HttpFailure(499, 'Request cancelled');
- };
- let deadlineExpired = false;
- const timer = setTimeout(
- () => {
- deadlineExpired = true;
- this.stopped.abort();
- },
- Math.max(0, deadlineAt - Date.now()),
- );
- let response: Response | undefined;
- try {
- check();
- const body = await readBounded(request.body, 1024 * 1024, signal);
- check();
- if (container.running) throw new HttpFailure(503, 'Native host is unavailable');
- await untilAbort(
- container.interceptOutboundHttp('kiln-storage.internal', this.ports.storageInterceptor),
- signal,
- );
- check();
- await untilAbort(
- container.interceptOutboundHttp(
- 'kiln-evaluator.internal',
- this.ports.evaluationInterceptor,
- ),
- signal,
- );
- check();
- await untilAbort(
- container.interceptOutboundHttp('kiln-renderer.internal', this.ports.renderInterceptor),
- signal,
- );
- check();
- container.start({
- image,
- enableInternet: false,
- instance: 'standard-1',
- env: { KILN_PUBLIC_ORIGIN: this.ports.publicOrigin },
- });
- void container.monitor().then(
- () => this.stopped.abort(),
- () => this.stopped.abort(),
- );
- await untilAbort(container.setInactivityTimeout(120_000), signal);
- const port = container.getTcpPort(3000);
- for (;;) {
- check();
- try {
- const ready = await untilAbort(
- port.fetch(new Request('http://kiln-native.internal/_ready', { signal })),
- signal,
- );
- void ready.body?.cancel().catch(() => {});
- if (ready.status === 204) break;
- } catch {
- if (signal.aborted) throw new HttpFailure(499, 'Request cancelled');
- }
- await untilAbort(new Promise((resolve) => setTimeout(resolve, 100)), signal);
- }
- const observed = await untilAbort(container.inspect(), signal);
- check();
- if (observed?.image !== image) throw new HttpFailure(503, 'Native host is unavailable');
- const incoming = new Request('http://kiln-native.internal/mcp', {
- method: request.method,
- headers,
- body: request.body === null ? undefined : body,
- signal,
- redirect: 'manual',
- });
- const pending = port.fetch(incoming).then((result) => {
- if (signal.aborted) void result.body?.cancel().catch(() => {});
- return result;
- });
- response = await untilAbort(pending, signal);
- check();
- if (response.status >= 300 && response.status < 400)
- throw new HttpFailure(502, 'Invalid native response');
- const bytes = await readBounded(response.body, 32 * 1024 * 1024, signal);
- check();
- const outgoing = new Headers();
- for (const key of ['content-type', 'mcp-protocol-version', 'allow']) {
- const value = response.headers.get(key);
- if (value && value.length <= 512) outgoing.set(key, value);
- }
- return privateResponse(
- new Response(bytes.length ? bytes : null, { status: response.status, headers: outgoing }),
- );
- } catch (error) {
- void response?.body?.cancel().catch(() => {});
- if (deadlineExpired || Date.now() >= deadlineAt)
- throw new HttpFailure(504, 'Native request timed out');
- throw error instanceof HttpFailure
- ? error
- : new HttpFailure(503, 'Native host is unavailable');
- } finally {
- clearTimeout(timer);
- await this.cancel();
- }
- }
-
- async storageRequest(request: Request): Promise<Response> {
- const url = new URL(request.url);
- const path = url.pathname;
- const permitted =
- request.method === 'GET'
- ? path === '/internal/programs' ||
- /^\/internal\/programs\/[^/]+$/.test(path) ||
- /^\/internal\/assets\/[^/]+\/[^/]+\/[^/]+$/.test(path) ||
- /^\/internal\/materials\/[a-z][a-z0-9_-]{0,79}\/[a-f0-9]{64}$/.test(path) ||
- /^\/mcp\/artifacts\/[a-f0-9]{32}$/.test(path)
- : request.method === 'POST'
- ? [
- '/internal/programs',
- '/internal/artifacts',
- '/internal/artifacts/discard',
- '/internal/assets/list',
- '/internal/assets/commit',
- '/internal/materials/list',
- '/internal/materials/commit',
- '/internal/downloads',
- ].includes(path)
- : request.method === 'DELETE' && /^\/internal\/groups\/[a-f0-9]{32}$/.test(path);
- if (url.href !== `http://kiln-storage.internal${path}` || !permitted)
- throw new HttpFailure(400, 'Invalid storage request');
- const headers = checkHeaders(request, STORAGE_HEADERS, true);
- const record = await this.active();
- const signal = AbortSignal.any([request.signal, this.stopped.signal]);
- const incoming = new Request(request, { headers, signal, redirect: 'manual' });
- const pending = this.ports
- .storage(record.tenant, new Request(`https://tenant.internal${path}`, incoming))
- .then((result) => {
- if (signal.aborted) void result.body?.cancel().catch(() => {});
- return result;
- });
- return untilAbort(pending, signal);
- }
-
- evaluateRequest(request: Request): Promise<Response> {
- return this.executionRequest('evaluation', request);
- }
-
- renderRequest(request: Request): Promise<Response> {
- return this.executionRequest('render', request);
- }
-
- private cancelChild(kind: ExecutionKind, id: string): Promise<void> {
- return kind === 'evaluation' ? this.ports.cancelEvaluation(id) : this.ports.cancelRender(id);
- }
-
- private async executionRequest(kind: ExecutionKind, request: Request): Promise<Response> {
- const profile = EXECUTION_PROFILES[kind];
- if (request.url !== profile.url || request.method !== 'POST')
- throw new HttpFailure(400, 'Invalid execution request');
- const headers = checkHeaders(request, EVALUATION_HEADERS, true);
- const id = crypto.randomUUID();
- const record = await this.context.storage.transaction(async (tx) => {
- this.check();
- const record = await tx.get<RequestRecord>('request');
- this.check();
- if (record?.state !== 'running' || Date.now() >= record.deadlineAt)
- throw new HttpFailure(409, 'Native request is not active');
- if (record.activeChild || record.children.length >= 8)
- throw new HttpFailure(429, 'Execution limit reached');
- record.children.push({ id, kind });
- record.activeChild = id;
- await tx.put('request', record);
- return record;
- });
- let response: Response | undefined;
- const signal = AbortSignal.any([request.signal, this.stopped.signal]);
- try {
- this.check();
- const requested = Number(headers.get('x-kiln-deadline-ms'));
- if (!Number.isSafeInteger(requested) || requested < 1 || requested > profile.deadlineMs)
- throw new HttpFailure(400, 'Invalid execution limit');
- const remaining = Math.min(requested, record.deadlineAt - Date.now());
- if (remaining < 1) throw new HttpFailure(504, 'Native request timed out');
- headers.set('x-kiln-deadline-ms', String(remaining));
- const incoming = new Request(request, { headers, signal });
- const execution =
- kind === 'evaluation' ? this.ports.evaluate(id, incoming) : this.ports.render(id, incoming);
- const pending = execution.then((result) => {
- if (signal.aborted) void result.body?.cancel().catch(() => {});
- return result;
- });
- response = await untilAbort(pending, signal);
- await cleanupChild(this.cancelChild(kind, id));
- await this.context.storage.transaction(async (tx) => {
- const current = await tx.get<RequestRecord>('request');
- if (current?.activeChild === id) {
- delete current.activeChild;
- await tx.put('request', current);
- }
- });
- this.check();
- return response;
- } catch (error) {
- void response?.body?.cancel().catch(() => {});
- throw error;
- }
- }
-
- cancel(): Promise<void> {
- this.stopped.abort();
- if (this.closing) return this.closing;
- const pending = this.close();
- this.closing = pending;
- const done = () => {
- if (this.closing === pending) this.closing = undefined;
- };
- void pending.then(done, done);
- return pending;
- }
-
- private async close(): Promise<void> {
- const record = await this.context.storage.transaction(async (tx) => {
- const record = await tx.get<RequestRecord>('request');
- if (!record) {
- await tx.put('request', {
- state: 'finished',
- deadlineAt: Date.now(),
- children: [],
- } satisfies RequestRecord);
- return undefined;
- }
- if (record.state === 'finished') return undefined;
- record.state = 'closing';
- await tx.put('request', record);
- await tx.setAlarm(Date.now());
- return record;
- });
- if (!record) return;
- try {
- const container = this.context.container;
- if (!container) throw new ContainerJobFailure('CLEANUP_FAILED');
- const results = await Promise.allSettled([
- destroyContainer(container),
- ...record.children.map(({ id, kind }) => cleanupChild(this.cancelChild(kind, id))),
- ]);
- if (results.some((result) => result.status === 'rejected'))
- throw new ContainerJobFailure('CLEANUP_FAILED');
- await this.context.storage.put('request', {
- ...record,
- state: 'finished',
- activeChild: undefined,
- } satisfies RequestRecord);
- await this.context.storage.deleteAlarm();
- } catch {
- await this.context.storage.setAlarm(Date.now() + 30_000);
- throw new ContainerJobFailure('CLEANUP_FAILED');
- }
- }
-
- async alarm(): Promise<void> {
- const record = await this.context.storage.get<RequestRecord>('request');
- if (!record || record.state === 'finished') {
- await this.context.storage.deleteAlarm();
- return;
- }
- if (record.state === 'running' && Date.now() < record.deadlineAt) {
- await this.context.storage.setAlarm(record.deadlineAt);
- return;
- }
- await this.cancel();
- }
-}
diff --git a/hosting/src/request-limits.ts b/hosting/src/request-limits.ts
deleted file mode 100644
index fd0bc66f..00000000
--- a/hosting/src/request-limits.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { privateResponse, sha256 } from './http';
-
-export interface RequestLimitEnv {
- EDGE_REQUEST_LIMIT: RateLimit;
- ACCOUNT_REQUEST_LIMIT: RateLimit;
-}
-function refused(request: Request, status: 401 | 429 | 503): Response {
- if (!request.bodyUsed) void request.body?.cancel().catch(() => {});
- return privateResponse(
- new Response(
- status === 429
- ? 'Too many requests. Try again shortly.'
- : status === 401
- ? 'Invalid identity'
- : 'Service temporarily unavailable',
- {
- status,
- headers: status === 429 ? { 'retry-after': '60' } : undefined,
- },
- ),
- );
-}
-
-const usable = (binding: RateLimit | undefined) => typeof binding?.limit === 'function';
-async function check(
- request: Request,
- binding: RateLimit,
- key: string,
-): Promise<Response | undefined> {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- if (!usable(binding)) return refused(request, 503);
- const result = await Promise.race([
- binding.limit({ key }),
- new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(new Error('Limiter deadline')), 1000);
- }),
- ]);
- if (!result || typeof result.success !== 'boolean') return refused(request, 503);
- return result.success ? undefined : refused(request, 429);
- } catch {
- return refused(request, 503);
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
-}
-
-/** Fixed classes bound anonymous work without storing IPs, credentials or URLs. */
-export function routeClass(path: string): string {
- if (path === '/register') return 'registration';
- if (path.startsWith('/oauth/token')) return 'token';
- if (path === '/authorize' || path === '/account/login') return 'sign-in';
- if (path === '/oauth/google/callback' || path === '/oauth/github/callback') return 'callback';
- if (path === '/account' || path.startsWith('/account/')) return 'account';
- if (path.startsWith('/downloads/')) return 'download';
- if (path === '/mcp' || path.startsWith('/mcp/')) return 'mcp';
- if (path.startsWith('/.well-known/')) return 'discovery';
- return 'other';
-}
-
-export async function limitIngress(
- request: Request,
- env: RequestLimitEnv,
- origin: string,
-): Promise<Response | undefined> {
- if (!usable(env.EDGE_REQUEST_LIMIT) || !usable(env.ACCOUNT_REQUEST_LIMIT))
- return refused(request, 503);
- return check(
- request,
- env.EDGE_REQUEST_LIMIT,
- `kiln-ingress-v1:${origin}:${routeClass(new URL(request.url).pathname)}`,
- );
-}
-
-/** Invoke only with verified account ownership, never a token or caller selector. */
-export async function limitAccount(
- request: Request,
- env: Pick<RequestLimitEnv, 'ACCOUNT_REQUEST_LIMIT'>,
- origin: string,
- accountId: string,
-): Promise<Response | undefined> {
- if (typeof accountId !== 'string' || !/^ka_[a-f0-9]{32}(?![\s\S])/.test(accountId))
- return refused(request, 401);
- return check(
- request,
- env.ACCOUNT_REQUEST_LIMIT,
- `kiln-account-rate-v1:${await sha256(JSON.stringify([origin, accountId]))}`,
- );
-}
diff --git a/hosting/src/request-worker.ts b/hosting/src/request-worker.ts
deleted file mode 100644
index 7ae1fe04..00000000
--- a/hosting/src/request-worker.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-import type { KilnEvaluationJob } from './evaluation-worker';
-import type { KilnRenderJob } from './render-worker';
-import { NativeRequestJob } from './request-job';
-import { privateResponse, serviceFailure } from './http';
-
-interface RequestEnv {
- PUBLIC_ORIGIN: string;
- TENANTS: DurableObjectNamespace;
- REQUESTS: DurableObjectNamespace<KilnNativeRequest>;
- EVALUATIONS: DurableObjectNamespace<KilnEvaluationJob>;
- RENDERS: DurableObjectNamespace<KilnRenderJob>;
-}
-interface InterceptorProps {
- requestId: string;
-}
-
-/** Private binding only. The admission service chooses the tenant and request ID. */
-export class KilnNativeRequest extends DurableObject<RequestEnv> {
- private readonly job: NativeRequestJob;
-
- constructor(ctx: DurableObjectState, env: RequestEnv) {
- super(ctx, env);
- const loopback = ctx.exports as {
- KilnNativeStorage: LoopbackForExport<typeof KilnNativeStorage>;
- KilnNativeEvaluation: LoopbackForExport<typeof KilnNativeEvaluation>;
- KilnNativeRender: LoopbackForExport<typeof KilnNativeRender>;
- };
- const props = { requestId: ctx.id.toString() };
- this.job = new NativeRequestJob(ctx, {
- publicOrigin: env.PUBLIC_ORIGIN,
- storageInterceptor: loopback.KilnNativeStorage({ props }),
- evaluationInterceptor: loopback.KilnNativeEvaluation({ props }),
- renderInterceptor: loopback.KilnNativeRender({ props }),
- storage: (tenant, request) => env.TENANTS.getByName(tenant).fetch(request),
- evaluate: (id, request) => env.EVALUATIONS.getByName(id).fetch(request),
- cancelEvaluation: async (id) => {
- await env.EVALUATIONS.getByName(id).cancel();
- },
- render: (id, request) => env.RENDERS.getByName(id).fetch(request),
- cancelRender: async (id) => {
- await env.RENDERS.getByName(id).cancel();
- },
- });
- }
-
- async run(tenant: string, request: Request, deadlineAt: number): Promise<Response> {
- try {
- return await this.job.run(tenant, request, deadlineAt);
- } catch (error) {
- return privateResponse(serviceFailure(error));
- } finally {
- // Configuration/one-use checks can reject before the RPC body is read.
- // Close that stream so it cannot retain the caller's execution context.
- if (!request.bodyUsed) await request.body?.cancel().catch(() => {});
- }
- }
- async storage(request: Request): Promise<Response> {
- // Convert deliberate HTTP errors before RPC serializes away their prototype.
- try {
- return await this.job.storageRequest(request);
- } catch (error) {
- return privateResponse(serviceFailure(error));
- }
- }
- async evaluate(request: Request): Promise<Response> {
- try {
- return await this.job.evaluateRequest(request);
- } catch (error) {
- return privateResponse(serviceFailure(error));
- }
- }
- cancel(): Promise<void> {
- return this.job.cancel();
- }
- async render(request: Request): Promise<Response> {
- try {
- return await this.job.renderRequest(request);
- } catch (error) {
- return privateResponse(serviceFailure(error));
- }
- }
- alarm(): Promise<void> {
- return this.job.alarm();
- }
-}
-
-/** No HTTP field chooses a request object; only the host-configured binding props do. */
-export class KilnNativeStorage extends WorkerEntrypoint<RequestEnv, InterceptorProps> {
- async fetch(request: Request): Promise<Response> {
- try {
- if (!/^[a-f0-9]{64}$/.test(this.ctx.props.requestId)) throw new Error('Invalid binding');
- const id = this.env.REQUESTS.idFromString(this.ctx.props.requestId);
- return await this.env.REQUESTS.get(id).storage(request);
- } catch (error) {
- return privateResponse(serviceFailure(error));
- }
- }
-}
-
-export class KilnNativeEvaluation extends WorkerEntrypoint<RequestEnv, InterceptorProps> {
- async fetch(request: Request): Promise<Response> {
- try {
- if (!/^[a-f0-9]{64}$/.test(this.ctx.props.requestId)) throw new Error('Invalid binding');
- const id = this.env.REQUESTS.idFromString(this.ctx.props.requestId);
- return await this.env.REQUESTS.get(id).evaluate(request);
- } catch (error) {
- return privateResponse(serviceFailure(error));
- }
- }
-}
-
-export class KilnNativeRender extends WorkerEntrypoint<RequestEnv, InterceptorProps> {
- async fetch(request: Request): Promise<Response> {
- try {
- if (!/^[a-f0-9]{64}$/.test(this.ctx.props.requestId)) throw new Error('Invalid binding');
- const id = this.env.REQUESTS.idFromString(this.ctx.props.requestId);
- return await this.env.REQUESTS.get(id).render(request);
- } catch (error) {
- return privateResponse(serviceFailure(error));
- }
- }
-}
-
-export default {
- fetch(): Response {
- return new Response('Not found', { status: 404 });
- },
-};
diff --git a/hosting/src/tenant-identity.ts b/hosting/src/tenant-identity.ts
deleted file mode 100644
index 4a3cd518..00000000
--- a/hosting/src/tenant-identity.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { HttpFailure, sha256 } from './http';
-
-/** Only a verified MCP grant or current primary browser session may supply userId. */
-export function tenantForAccount(origin: string, userId: string): Promise<string> {
- if (typeof userId !== 'string' || !/^ka_[a-f0-9]{32}(?![\s\S])/.test(userId))
- throw new HttpFailure(401, 'Invalid identity');
- return sha256(JSON.stringify(['kiln-tenant-v1', origin, userId]));
-}
diff --git a/hosting/src/tenant-worker.ts b/hosting/src/tenant-worker.ts
deleted file mode 100644
index 77fda7f2..00000000
--- a/hosting/src/tenant-worker.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export { KilnTenant } from './tenant';
-
-// Tenant operations are available only through the private Durable Object binding.
-export default {
- fetch(): Response {
- return new Response('Not found', { status: 404 });
- },
-};
diff --git a/hosting/src/tenant.ts b/hosting/src/tenant.ts
deleted file mode 100644
index c66423fe..00000000
--- a/hosting/src/tenant.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-import { DurableObject } from 'cloudflare:workers';
-import { ArtifactStore } from './artifact-store';
-import { boundedRequest, HttpFailure, privateResponse, readBounded, serviceFailure } from './http';
-import { decodeProgram, HostedProgramStore } from './programs';
-import { MAX_PROGRAM_BYTES } from '../../src/program-store';
-import { AssetIndex } from './asset-index';
-import { AssetDownloadTickets } from './asset-downloads';
-import { parseDownloadPath } from './download-path';
-import { MaterialIndex } from './material-index';
-
-const retirementHeaders = new Set([
- 'content-length',
- 'accept',
- 'accept-encoding',
- 'accept-language',
- 'connection',
- 'host',
- 'user-agent',
- 'sec-fetch-mode',
-]);
-
-export interface TenantStorageEnv {
- ARTIFACTS: R2Bucket;
- STORAGE_MAX_BYTES: string;
- STORAGE_MAX_OBJECTS: string;
- STORAGE_MAX_GROUPS: string;
-}
-
-export class KilnTenant extends DurableObject<TenantStorageEnv> {
- private readonly artifacts: ArtifactStore;
- private readonly programs: HostedProgramStore;
- private readonly assets: AssetIndex;
- private readonly downloads: AssetDownloadTickets;
- private readonly materials: MaterialIndex;
-
- constructor(ctx: DurableObjectState, env: TenantStorageEnv) {
- super(ctx, env);
- this.artifacts = new ArtifactStore(ctx, env.ARTIFACTS, {
- maxBytes: Number(env.STORAGE_MAX_BYTES),
- maxObjects: Number(env.STORAGE_MAX_OBJECTS),
- maxGroups: Number(env.STORAGE_MAX_GROUPS),
- });
- this.programs = new HostedProgramStore(this.artifacts);
- this.assets = new AssetIndex(this.artifacts);
- this.materials = new MaterialIndex(this.artifacts);
- this.downloads = new AssetDownloadTickets(ctx.storage, this.artifacts, this.assets);
- }
-
- async alarm(): Promise<void> {
- if (this.artifacts.retirementStatus().state !== 'active') this.downloads.revokeAll();
- this.downloads.sweep();
- await this.artifacts.sweep();
- }
-
- async fetch(request: Request): Promise<Response> {
- try {
- const url = new URL(request.url);
- if (url.origin !== 'https://tenant.internal' || url.search)
- throw new HttpFailure(400, 'Invalid internal request');
- if (url.pathname === '/internal/account-deletion') {
- if (
- request.method !== 'POST' ||
- [...request.headers].some(
- ([name, value]) => !retirementHeaders.has(name) || value.length > 512,
- ) ||
- ![null, '0'].includes(request.headers.get('content-length'))
- )
- throw new HttpFailure(400, 'Invalid storage retirement');
- await readBounded(request.body, 0, request.signal);
- const result = await this.artifacts.retire(() => this.downloads.revokeAll());
- return privateResponse(Response.json(result));
- }
- this.artifacts.assertActive();
- if (url.pathname === '/internal/downloads' && request.method === 'POST') {
- if (request.headers.get('content-type')?.split(';')[0] !== 'application/json')
- throw new HttpFailure(415, 'Expected download selection');
- const bounded = await boundedRequest(request, 1024);
- let value: unknown;
- try {
- value = await bounded.json();
- } catch {
- throw new HttpFailure(400, 'Invalid download selection');
- }
- if (
- !value ||
- typeof value !== 'object' ||
- Array.isArray(value) ||
- Object.keys(value).some((key) => !['collection', 'assetId', 'revisionId'].includes(key))
- )
- throw new HttpFailure(400, 'Invalid download selection');
- const input = value as Record<string, unknown>;
- return privateResponse(
- Response.json(
- await this.downloads.issue(input.collection, input.assetId, input.revisionId),
- { status: 201 },
- ),
- );
- }
- if (url.pathname.startsWith('/internal/downloads/')) {
- const selected = parseDownloadPath(url.pathname.slice('/internal'.length));
- if (!selected) throw new HttpFailure(404, 'Download link unavailable; request a new link');
- if (!['GET', 'HEAD'].includes(request.method))
- return new Response('Method not allowed', { status: 405 });
- return await this.downloads.download(
- selected.token,
- selected.filename,
- request.method === 'HEAD',
- );
- }
- if (
- ['/internal/assets/commit', '/internal/assets/list'].includes(url.pathname) &&
- request.method === 'POST'
- ) {
- const bounded = await boundedRequest(request, 2048);
- let input: unknown;
- try {
- input = await bounded.json();
- } catch {
- throw new HttpFailure(400, 'Invalid saved asset');
- }
- if (url.pathname.endsWith('/list'))
- return privateResponse(Response.json(this.assets.list(input)));
- const result = this.assets.commit(input);
- return privateResponse(
- Response.json(result.record, { status: result.created ? 201 : 200 }),
- );
- }
- const asset = url.pathname.match(/^\/internal\/assets\/([^/]+)\/([^/]+)\/([^/]+)$/);
- if (asset && request.method === 'GET')
- return privateResponse(Response.json(this.assets.read(asset[1], asset[2], asset[3])));
- if (
- ['/internal/materials/commit', '/internal/materials/list'].includes(url.pathname) &&
- request.method === 'POST'
- ) {
- const bounded = await boundedRequest(request, 2048);
- let input: unknown;
- try {
- input = await bounded.json();
- } catch {
- throw new HttpFailure(400, 'Invalid saved material');
- }
- if (url.pathname.endsWith('/list'))
- return privateResponse(Response.json(this.materials.list(input)));
- const result = this.materials.commit(input);
- return privateResponse(
- Response.json(result.record, { status: result.created ? 201 : 200 }),
- );
- }
- const material = url.pathname.match(/^\/internal\/materials\/([^/]+)\/([a-f0-9]{64})$/);
- if (material && request.method === 'GET')
- return privateResponse(
- Response.json(this.materials.read(material[1], `sha256:${material[2]}`)),
- );
- if (url.pathname === '/internal/programs' && request.method === 'GET') {
- return privateResponse(
- Response.json({ ...(await this.programs.stats()), retention: this.programs.retention }),
- );
- }
- if (url.pathname === '/internal/programs' && request.method === 'POST') {
- if (request.headers.get('content-type')?.split(';')[0] !== 'application/javascript') {
- throw new HttpFailure(415, 'Program source requires application/javascript');
- }
- const code = decodeProgram(await readBounded(request.body, MAX_PROGRAM_BYTES));
- const programRef = await this.programs.put(code);
- return privateResponse(
- Response.json(
- {
- programRef,
- shortRef: await this.programs.shortRef(programRef),
- artifactId: this.programs.artifact(programRef).id,
- },
- { status: 201 },
- ),
- );
- }
- if (url.pathname.startsWith('/internal/programs/') && request.method === 'GET') {
- let ref: string;
- try {
- ref = decodeURIComponent(url.pathname.slice('/internal/programs/'.length));
- } catch {
- throw new HttpFailure(400, 'Invalid program reference');
- }
- return privateResponse(
- new Response(await this.programs.get(ref), {
- headers: {
- 'content-type': 'text/plain; charset=utf-8',
- 'content-disposition': 'attachment; filename="source.kiln.js"',
- },
- }),
- );
- }
- const download = url.pathname.match(/^\/mcp\/artifacts\/([a-f0-9]{32})$/);
- if (download) {
- if (!['GET', 'HEAD'].includes(request.method))
- return new Response('Method not allowed', { status: 405 });
- return await this.artifacts.download(download[1]!, request.method === 'HEAD');
- }
- if (url.pathname === '/internal/artifacts' && request.method === 'POST') {
- return privateResponse(
- Response.json(await this.artifacts.upload(request), { status: 201 }),
- );
- }
- if (url.pathname === '/internal/artifacts/discard' && request.method === 'POST') {
- const bounded = await boundedRequest(request, 1024);
- let ids: unknown;
- try {
- ids = await bounded.json();
- } catch {
- throw new HttpFailure(400, 'Invalid staging inventory');
- }
- await this.artifacts.discard(ids);
- return privateResponse(Response.json({ discarded: true }));
- }
- if (url.pathname === '/internal/groups' && request.method === 'POST') {
- const bounded = await boundedRequest(request, 131_072);
- let body: unknown;
- try {
- body = await bounded.json();
- } catch {
- throw new HttpFailure(400, 'Invalid saved revision');
- }
- const result = this.artifacts.save(body);
- return privateResponse(
- Response.json(result.record, { status: result.created ? 201 : 200 }),
- );
- }
- const group = url.pathname.match(/^\/internal\/groups\/([a-f0-9]{32})$/);
- if (group && request.method === 'GET')
- return privateResponse(Response.json(this.artifacts.group(group[1]!)));
- if (group && request.method === 'DELETE') {
- await this.artifacts.deleteGroup(group[1]!);
- return privateResponse(Response.json({ deleted: true }));
- }
- if (url.pathname === '/internal/usage' && request.method === 'GET')
- return privateResponse(Response.json(this.artifacts.usage()));
- if (url.pathname === '/internal/maintenance' && request.method === 'POST') {
- this.downloads.sweep();
- return privateResponse(Response.json(await this.artifacts.sweep()));
- }
- if (url.pathname === '/mcp')
- return new Response('Native engine is not configured or qualified', { status: 503 });
- return new Response('Not found', { status: 404 });
- } catch (error) {
- return privateResponse(serviceFailure(error));
- }
- }
-}
diff --git a/hosting/src/worker.ts b/hosting/src/worker.ts
deleted file mode 100644
index cb055e4a..00000000
--- a/hosting/src/worker.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import {
- OAuthAuthorizationServer,
- OAuthError,
- OAuthResourceServer,
-} from '@cloudflare/workers-oauth-provider';
-import { D1Connections } from './connections';
-import { accountPage } from './account-page';
-import { beginBrowserLogin } from './browser-login';
-import { beginAccountAction } from './account-actions';
-import { beginIdentityAction } from './identity-actions';
-import { beginDeletionAction, accountDeletionStatus } from './deletion-actions';
-import { browserDownload } from './browser-download';
-import { publicPage } from './public-pages';
-import { authorize, authorizationFailure, SCOPES, type SignInEnv } from './auth';
-import { forwardTenant, type TenantEnv } from './gateway';
-import { boundedRequest, HttpFailure, privateResponse } from './http';
-import { recoverAccountDeletions } from './deletion-recovery';
-import { limitIngress, type RequestLimitEnv } from './request-limits';
-import {
- recordResponse,
- recordHealth,
- readOperationalHealth,
- type OperationsEnv,
-} from './operations';
-
-export interface Env extends SignInEnv, TenantEnv, RequestLimitEnv, OperationsEnv {
- OAUTH_KV: KVNamespace;
- PUBLIC_ORIGIN: string;
-}
-
-function publicOrigin(env: Env): string {
- const configured = new URL(env.PUBLIC_ORIGIN);
- if (configured.protocol !== 'https:' || configured.origin !== env.PUBLIC_ORIGIN)
- throw new Error('Invalid origin configuration');
- return configured.origin;
-}
-
-function authorizationServer(origin: string) {
- return new OAuthAuthorizationServer<Env>({
- issuer: origin,
- resources: [`${origin}/mcp`],
- authorizeEndpoint: `${origin}/authorize`,
- tokenEndpoint: `${origin}/oauth/token`,
- clientRegistrationEndpoint: `${origin}/register`,
- clientIdMetadataDocumentEnabled: true,
- scopesSupported: SCOPES,
- accessTokenTTL: 900,
- refreshTokenTTL: 30 * 24 * 60 * 60,
- tokenExchangeCallback: async ({
- env: bindings,
- userId,
- props,
- clientId,
- grantId,
- grantType,
- }) => {
- if (
- !(await new D1Connections(bindings.ACCOUNTS).exchange(
- userId,
- props,
- clientId,
- grantId,
- grantType,
- ))
- )
- throw new OAuthError('invalid_grant', {
- description: 'Account authorization changed; sign in again',
- });
- },
- // Deliberately do not log request data or provider error descriptions.
- onError: () => {},
- });
-}
-
-const gateway = {
- async scheduled(_event: ScheduledController, env: Env): Promise<void> {
- const origin = publicOrigin(env);
- try {
- await recoverAccountDeletions(env, origin, authorizationServer(origin).getOAuthApi(env));
- } catch {
- throw new Error('Account deletion recovery unavailable');
- }
- },
- async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
- try {
- const origin = publicOrigin(env);
- const url = new URL(request.url);
- if (url.origin !== origin) throw new HttpFailure(421, 'Invalid request origin');
- if (url.href.length > 16_384) throw new HttpFailure(414, 'URL too long');
- const limited = await limitIngress(request, env, origin);
- if (limited) return limited;
- const information = publicPage(request, origin);
- if (information) return privateResponse(information);
- const resource = `${origin}/mcp`;
- const auth = authorizationServer(origin);
- const protectedResource = new OAuthResourceServer<Env>({
- resourceMetadata: { resource, authorization_servers: [origin] },
- requiredScopes: ['kiln:use'],
- validateToken: (bindings) => async (audience, token) => {
- const verified = await auth.validateToken(audience, token, bindings);
- if (!verified) return null;
- if (
- !(await new D1Connections(bindings.ACCOUNTS).accepts(
- verified.userId,
- verified.props,
- verified.clientId,
- ))
- )
- throw new OAuthError('invalid_token', {
- description: 'Account authorization changed; sign in again',
- });
- return verified;
- },
- handler: {
- fetch: (incoming, bindings, context) =>
- forwardTenant(incoming, bindings, context, origin),
- },
- });
- let response: Response;
- if (
- url.pathname === '/mcp' ||
- url.pathname.startsWith('/mcp/') ||
- url.pathname.startsWith('/.well-known/oauth-protected-resource')
- ) {
- const browserOrigin = request.headers.get('origin');
- if (browserOrigin !== null && browserOrigin !== origin)
- throw new HttpFailure(403, 'Origin not allowed');
- if (url.search)
- throw new HttpFailure(400, 'Query parameters are not supported on resource endpoints');
- response = await protectedResource.fetch(request, env, ctx);
- } else if (url.pathname.startsWith('/downloads/')) {
- response = await browserDownload(request, env, origin);
- } else if (url.pathname === '/account/deletion') {
- response = await accountDeletionStatus(request, env.ACCOUNTS, origin);
- } else if (url.pathname === '/account' || url.pathname === '/account/logout') {
- response = await accountPage(await boundedRequest(request, 4096), env.ACCOUNTS, origin);
- } else if (
- url.pathname === '/authorize' ||
- url.pathname === '/account/login' ||
- url.pathname === '/account/action' ||
- url.pathname === '/account/identity' ||
- url.pathname === '/account/delete' ||
- url.pathname === '/oauth/github/callback' ||
- url.pathname === '/oauth/google/callback'
- ) {
- if (
- !env.GITHUB_CLIENT_ID ||
- !env.GITHUB_CLIENT_SECRET ||
- !env.GOOGLE_CLIENT_ID ||
- !env.GOOGLE_CLIENT_SECRET ||
- !env.ACCOUNTS
- )
- throw new HttpFailure(503, 'Sign-in is not configured');
- response =
- url.pathname === '/account/delete'
- ? await beginDeletionAction(await boundedRequest(request, 4096), origin, env)
- : url.pathname === '/account/identity'
- ? await beginIdentityAction(await boundedRequest(request, 4096), origin, env)
- : url.pathname === '/account/action'
- ? await beginAccountAction(await boundedRequest(request, 4096), origin, env)
- : url.pathname === '/account/login'
- ? await beginBrowserLogin(await boundedRequest(request, 4096), origin, env)
- : await authorize(
- await boundedRequest(request, 16_384),
- auth.getOAuthApi(env),
- origin,
- env,
- ctx,
- );
- if (response.status === 303 && response.headers.get('location') === '/account/deletion')
- ctx.waitUntil(
- recoverAccountDeletions(env, origin, auth.getOAuthApi(env)).catch(() => {}),
- );
- } else if (
- url.pathname === '/register' ||
- url.pathname.startsWith('/oauth/token') ||
- url.pathname.startsWith('/.well-known/')
- ) {
- response = await auth.fetch(await boundedRequest(request, 16_384), env, ctx);
- } else {
- response = new Response('Not found', { status: 404 });
- }
- return privateResponse(response);
- } catch (error) {
- return privateResponse(authorizationFailure(error));
- }
- },
-} satisfies ExportedHandler<Env>;
-
-export default {
- async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
- const started = performance.now();
- const response = await gateway.fetch(request, env, ctx);
- recordResponse(
- env,
- new URL(request.url).pathname,
- response.status,
- performance.now() - started,
- );
- return response;
- },
- async scheduled(event: ScheduledController, env: Env): Promise<void> {
- let recovered = false;
- try {
- await gateway.scheduled(event, env);
- recovered = true;
- } catch {
- /* Emit component health without recording the underlying exception. */
- }
- const health = await readOperationalHealth(env);
- recordHealth(env, health, recovered);
- if (!recovered || !health.deletion || !health.compute)
- throw new Error('Hosted recovery or health check unavailable');
- },
-} satisfies ExportedHandler<Env>;
diff --git a/hosting/test/accounts-worker.ts b/hosting/test/accounts-worker.ts
deleted file mode 100644
index 99d80c01..00000000
--- a/hosting/test/accounts-worker.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { D1AccountDirectory } from '../src/accounts';
-import { serviceFailure } from '../src/http';
-
-// Test-only interface to the directory. Production must only accept identities
-// from verified sign-in adapters, never request bodies or caller headers.
-export default {
- async fetch(request: Request, env: { ACCOUNTS: D1Database }): Promise<Response> {
- try {
- const directory = new D1AccountDirectory(env.ACCOUNTS);
- const url = new URL(request.url);
- if (request.method === 'POST')
- return Response.json(await directory.resolveIdentity(await request.json()));
- return Response.json(await directory.getAccount(url.pathname.slice(1)));
- } catch (error) {
- return serviceFailure(error);
- }
- },
-} satisfies ExportedHandler<{ ACCOUNTS: D1Database }>;
diff --git a/hosting/test/accounts.test.mjs b/hosting/test/accounts.test.mjs
deleted file mode 100644
index 0bbde174..00000000
--- a/hosting/test/accounts.test.mjs
+++ /dev/null
@@ -1,159 +0,0 @@
-import assert from 'node:assert/strict';
-import { readFile } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-let runtime;
-let database;
-const google = 'https://accounts.google.com';
-const github = 'https://github.com';
-before(async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./accounts-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- d1Databases: ['ACCOUNTS'],
- outboundService: async () => {
- throw new Error('Accounts must not fetch');
- },
- }),
- );
- database = await runtime.getD1Database('ACCOUNTS');
- const schema = await readFile(
- new URL('../migrations/0001_accounts.sql', import.meta.url),
- 'utf8',
- );
- await database.batch(
- schema
- .split(';')
- .filter((sql) => sql.trim())
- .map((sql) => database.prepare(sql)),
- );
-});
-after(async () => runtime?.dispose());
-
-const resolve = (issuer, subject, extra = {}) =>
- runtime.dispatchFetch('https://accounts.test/', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ issuer, subject, ...extra }),
- });
-const count = async () =>
- (await database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n;
-
-test('verified identities get stable independent Kiln IDs without storing contact data or tokens', async () => {
- const response = await resolve(github, '1001', {
- email: '[email protected]',
- access_token: 'fixture-only',
- });
- assert.equal(response.status, 200);
- const account = await response.json();
- assert.match(account.id, /^ka_[a-f0-9]{32}$/);
- assert.equal(account.state, 'active');
- assert.equal(account.authorizationEpoch, 1);
- assert.deepEqual(
- await (await resolve(github, '1001', { email: '[email protected]' })).json(),
- account,
- );
- assert.deepEqual(
- await (await runtime.dispatchFetch(`https://accounts.test/${account.id}`)).json(),
- account,
- );
- const identity = await database
- .prepare('SELECT * FROM kiln_identities WHERE issuer=? AND subject=?')
- .bind(github, '1001')
- .first();
- assert.deepEqual(Object.keys(identity).sort(), ['account_id', 'created_at', 'issuer', 'subject']);
- assert.equal(identity.account_id, account.id);
-});
-
-test('the same email or subject at different issuers never automatically merges accounts', async () => {
- const a = await (await resolve(github, '2002', { email: '[email protected]' })).json();
- const b = await (await resolve(google, '2002', { email: '[email protected]' })).json();
- assert.notEqual(a.id, b.id);
-});
-
-test('concurrent first sign-ins create exactly one identity and one account with no orphan rows', async () => {
- const before = await count();
- const responses = await Promise.all(
- Array.from({ length: 24 }, () => resolve(google, 'concurrent-subject')),
- );
- const accounts = await Promise.all(
- responses.map(async (response) => {
- assert.equal(response.status, 200);
- return response.json();
- }),
- );
- assert.equal(new Set(accounts.map((account) => account.id)).size, 1);
- assert.equal(await count(), before + 1);
- const identities = await database
- .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE issuer=? AND subject=?')
- .bind(google, 'concurrent-subject')
- .first();
- assert.equal(identities.n, 1);
-});
-
-test('identity-write failure rolls back its new account as one transaction', async () => {
- await database
- .prepare(`CREATE TRIGGER reject_fixture_identity BEFORE INSERT ON kiln_identities
- WHEN NEW.subject = 'rollback-subject' BEGIN SELECT RAISE(ABORT, 'fixture rejection'); END`)
- .run();
- const before = await count();
- assert.equal((await resolve(google, 'rollback-subject')).status, 503);
- assert.equal(await count(), before);
- await database.prepare('DROP TRIGGER reject_fixture_identity').run();
- assert.equal((await resolve(google, 'rollback-subject')).status, 200);
- assert.equal(await count(), before + 1);
-});
-
-test('disabled and deleting accounts cannot sign in or acquire a replacement account', async () => {
- for (const state of ['disabled', 'deleting']) {
- const account = await (await resolve(google, `state-${state}`)).json();
- await database
- .prepare('UPDATE kiln_accounts SET state=?, authorization_epoch=2 WHERE id=?')
- .bind(state, account.id)
- .run();
- const before = await count();
- assert.equal((await resolve(google, `state-${state}`)).status, 403);
- assert.equal(await count(), before);
- assert.deepEqual(
- await (await runtime.dispatchFetch(`https://accounts.test/${account.id}`)).json(),
- { ...account, state, authorizationEpoch: 2 },
- );
- }
-});
-
-test('identity keys are bounded, exact and restricted to configured issuers', async () => {
- const before = await count();
- for (const [issuer, subject] of [
- [google, ''],
- [google, 'a'.repeat(256)],
- [google, 'bad\nsubject'],
- [google, 123],
- ['https://foreign.example', '1001'],
- [`${google}/`, '1001'],
- ]) {
- assert.equal((await resolve(issuer, subject)).status, 400);
- }
- assert.equal(await count(), before);
- const a = await (await resolve(google, 'CaseSensitive')).json();
- const b = await (await resolve(google, 'casesensitive')).json();
- assert.notEqual(a.id, b.id);
- assert.equal((await runtime.dispatchFetch('https://accounts.test/not-an-account')).status, 400);
- assert.equal(
- await (
- await runtime.dispatchFetch('https://accounts.test/ka_00000000000000000000000000000000')
- ).json(),
- null,
- );
-});
diff --git a/hosting/test/admission-worker.test.mjs b/hosting/test/admission-worker.test.mjs
deleted file mode 100644
index bf383e3c..00000000
--- a/hosting/test/admission-worker.test.mjs
+++ /dev/null
@@ -1,154 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { before, after, test } from 'node:test';
-import { build } from 'esbuild';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-
-let runtime, compute, operator, raw;
-before(async () => {
- const bundle = await build({
- stdin: {
- contents: `
- import {DurableObject} from 'cloudflare:workers';
- export * from './src/admission-worker';
- export {default} from './src/admission-worker';
- export class FakeRequest extends DurableObject {
- async run(tenant,request,deadlineAt) {
- const before=await this.env.ADMISSION.getByName('global-v1').status();
- return Response.json({tenant,body:await request.text(),headers:Object.fromEntries(request.headers),before,deadlineAt});
- }
- async cancel(){await this.ctx.storage.put('stopped',true);}
- }
- `,
- resolveDir: fileURLToPath(new URL('../', import.meta.url)),
- loader: 'ts',
- },
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- workers: [
- {
- name: 'admission',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- durableObjects: {
- ADMISSION: { className: 'KilnAdmission', useSQLite: true },
- REQUESTS: { className: 'FakeRequest', useSQLite: true },
- },
- bindings: {
- COMPUTE_MAX_CONCURRENT: '2',
- COMPUTE_TENANT_PER_MINUTE: '5',
- COMPUTE_TENANT_PER_DAY: '10',
- COMPUTE_GLOBAL_PER_DAY: '2',
- COMPUTE_GLOBAL_PER_MONTH: '3',
- COMPUTE_DEADLINE_MS: '60000',
- },
- },
- {
- name: 'unconfigured-admission',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- durableObjects: {
- ADMISSION: { className: 'KilnAdmission', useSQLite: true },
- REQUESTS: { className: 'FakeRequest', useSQLite: true },
- },
- },
- {
- name: 'gateway-fixture',
- modules: true,
- compatibilityDate: '2026-10-06',
- serviceBindings: {
- COMPUTE: { name: 'admission', entrypoint: 'KilnCompute' },
- UNCONFIGURED: { name: 'unconfigured-admission', entrypoint: 'KilnCompute' },
- },
- script: `
- export default {async fetch(request,env){
- const url=new URL(request.url);
- if(url.pathname==='/private-http')return env.COMPUTE.fetch(request);
- if(url.pathname==='/health')return Response.json(await env.COMPUTE.health());
- if(url.pathname==='/missing-policy')return env.UNCONFIGURED.dispatch('a'.repeat(43),new Request('https://tenant.internal/mcp'));
- if(url.pathname==='/try-pause') {try {await env.COMPUTE.setPaused(true);return new Response('exposed');}catch{return new Response('unavailable',{status:404});}}
- if(url.pathname==='/retire') {await env.COMPUTE.retireTenant('z'.repeat(43));return Response.json({retired:true});}
- return env.COMPUTE.dispatch(url.searchParams.get('tenant').repeat(43),new Request('https://tenant.internal/mcp',{method:'POST',headers:{'content-type':'application/json'},body:'{}'}));
- }};`,
- },
- {
- name: 'operator-fixture',
- modules: true,
- compatibilityDate: '2026-10-06',
- serviceBindings: { CONTROL: { name: 'admission', entrypoint: 'KilnComputeControl' } },
- script: `
- export default {async fetch(request,env){const url=new URL(request.url);if(url.pathname==='/pause')return Response.json(await env.CONTROL.setPaused(true));if(url.pathname==='/resume')return Response.json(await env.CONTROL.setPaused(false));return Response.json(await env.CONTROL.status());}};`,
- },
- ],
- }),
- );
- compute = await runtime.getWorker('gateway-fixture');
- operator = await runtime.getWorker('operator-fixture');
- raw = await runtime.getWorker('admission');
-});
-after(async () => runtime?.dispose());
-
-test('private entrypoint selects one global authority across accounts and exposes no public or operator API', async () => {
- assert.equal((await raw.fetch('https://test.invalid/')).status, 404);
- assert.equal((await compute.fetch('https://test.invalid/private-http')).status, 404);
- assert.equal((await compute.fetch('https://test.invalid/try-pause')).status, 404);
- for (const tenant of ['a', 'b']) {
- const response = await compute.fetch(`https://test.invalid/?tenant=${tenant}`);
- assert.equal(response.status, 200);
- const data = await response.json();
- assert.equal(data.tenant, tenant.repeat(43));
- assert.equal(data.before.activeRequests, 1);
- assert.equal(data.body, '{}');
- assert.equal(data.headers.authorization, undefined);
- assert.equal((await (await operator.fetch('https://test.invalid/')).json()).activeRequests, 0);
- }
- assert.equal((await compute.fetch('https://test.invalid/?tenant=c')).status, 429);
-});
-
-test('read-only compute health exposes aggregates without changing admission or exposing pause', async () => {
- const before = await (await operator.fetch('https://test.invalid/')).json();
- assert.deepEqual(await (await compute.fetch('https://test.invalid/health')).json(), before);
- assert.deepEqual(await (await operator.fetch('https://test.invalid/')).json(), before);
- assert.equal((await compute.fetch('https://test.invalid/try-pause')).status, 404);
- assert.equal((await raw.fetch('https://test.invalid/health')).status, 404);
-});
-
-test('separate operator binding pauses and resumes without exposing account identifiers', async () => {
- const paused = await (await operator.fetch('https://test.invalid/pause')).json();
- assert.equal(paused.paused, true);
- assert.equal(paused.activeRequests, 0);
- assert.equal((await compute.fetch('https://test.invalid/?tenant=d')).status, 503);
- const resumed = await (await operator.fetch('https://test.invalid/resume')).json();
- assert.equal(resumed.paused, false);
- assert.deepEqual(Object.keys(resumed).sort(), [
- 'activeRequests',
- 'maxConcurrent',
- 'paused',
- 'pendingCleanup',
- ]);
-});
-
-test('absent quota configuration refuses work instead of selecting implicit launch limits', async () => {
- const response = await compute.fetch('https://test.invalid/missing-policy');
- assert.equal(response.status, 503);
- assert.equal(await response.text(), 'Service temporarily unavailable');
-});
-
-test('verified gateway lifecycle RPC permanently retires a tenant without a public route', async () => {
- assert.equal((await raw.fetch('https://test.invalid/retire')).status, 404);
- assert.deepEqual(await (await compute.fetch('https://test.invalid/retire')).json(), {
- retired: true,
- });
- assert.equal((await compute.fetch('https://test.invalid/?tenant=z')).status, 410);
- assert.deepEqual(await (await compute.fetch('https://test.invalid/retire')).json(), {
- retired: true,
- });
-});
diff --git a/hosting/test/admission.test.mjs b/hosting/test/admission.test.mjs
deleted file mode 100644
index 59fe8ece..00000000
--- a/hosting/test/admission.test.mjs
+++ /dev/null
@@ -1,366 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { before, after, test } from 'node:test';
-import { build } from 'esbuild';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-
-let runtime;
-before(async () => {
- const bundle = await build({
- stdin: {
- contents: `
- import {DurableObject} from 'cloudflare:workers';
- import {ComputeAdmission, admissionFailure} from './src/admission';
- export class Fixture extends DurableObject {
- constructor(ctx,env) {
- super(ctx,env); this.pending=new Map(); this.cancelledBodies=0;
- this.admission=new ComputeAdmission(ctx.storage, {
- run: async (id,tenant,request,deadlineAt) => {
- const calls=await ctx.storage.get('calls')||[];
- calls.push({id,tenant,url:request.url,headers:Object.fromEntries(request.headers),deadlineAt});
- await ctx.storage.put('calls',calls);
- if(await ctx.storage.get('abortRace')) {
- this.requestAbort.abort();
- return new Response(new ReadableStream({cancel:()=>{this.cancelledBodies++;}}));
- }
- if(await ctx.storage.get('hold')) return new Promise(resolve=>this.pending.set(id,resolve));
- if(await ctx.storage.get('runFail')) throw Error('private diagnostic');
- return new Response('native result');
- },
- cancel: async id => {
- if(await ctx.storage.get('cancelFail')) throw Error('private cleanup diagnostic');
- const stopped=await ctx.storage.get('stopped')||[];
- stopped.push(id); await ctx.storage.put('stopped',stopped);
- this.pending.get(id)?.(new Response('cancelled',{status:499})); this.pending.delete(id);
- },
- }, {maxConcurrent:2,tenantPerMinute:3,tenantPerDay:4,globalPerDay:7,globalPerMonth:8,deadlineMs:env.FIXTURE_SHORT_DEADLINE===true?250:60000},
- ()=>ctx.storage.kv.get('now')??Date.now());
- }
- async dispatch(tenant,request) {
- this.requestAbort=new AbortController();
- try{return await this.admission.dispatch(tenant,new Request(request,{signal:this.requestAbort.signal}));}catch(e){return admissionFailure(e);}
- }
- async command(command,value) {
- if(command==='retire') {try{await this.admission.retireTenant(value);return {retired:true};}catch(e){return {retired:false,status:admissionFailure(e).status};}}
- if(command==='pause') return this.admission.setPaused(value);
- if(command==='alarm') return this.admission.alarm();
- if(command==='expire') {this.ctx.storage.sql.exec('UPDATE compute_active SET recover_at = 0');return;}
- if(command==='snapshot') return {
- active:this.ctx.storage.sql.exec('SELECT * FROM compute_active').toArray(),
- usage:this.ctx.storage.sql.exec('SELECT * FROM compute_usage').toArray(),
- calls:await this.ctx.storage.get('calls')||[], stopped:await this.ctx.storage.get('stopped')||[],
- alarm:await this.ctx.storage.getAlarm(),
- cancelledBodies:this.cancelledBodies,
- };
- await this.ctx.storage.put(command,value);
- }
- alarm(){return this.admission.alarm();}
- }
- export class ShortFixture extends Fixture {constructor(ctx,env){super(ctx,{...env,FIXTURE_SHORT_DEADLINE:true});}}
- export default {async fetch(request,env) {
- const url=new URL(request.url), stub=env[url.searchParams.has('short')?'SHORT':'FIXTURE'].getByName(url.searchParams.get('fixture'));
- if(url.pathname==='/command') {const {command,value}=await request.json();return Response.json((await stub.command(command,value))??null);}
- const headers=new Headers({'content-type':'application/json'});
- if(url.searchParams.has('hostile')) headers.set('authorization','Bearer must-never-leave');
- return stub.dispatch(url.searchParams.get('tenant'),new Request('https://tenant.internal/mcp',{method:'POST',headers,body:'{}'}));
- }};`,
- resolveDir: fileURLToPath(new URL('../', import.meta.url)),
- loader: 'ts',
- },
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- name: 'admission-fixture',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- durableObjects: {
- FIXTURE: { className: 'Fixture', useSQLite: true },
- SHORT: { className: 'ShortFixture', useSQLite: true },
- },
- outboundService: async () => {
- throw Error('No network');
- },
- }),
- unsafeInspectDurableObjects: true,
- });
-});
-after(async () => runtime?.dispose());
-
-function fixture(short = false) {
- const id = crypto.randomUUID();
- return {
- id,
- request: (tenant = 'a', hostile = false) =>
- runtime.dispatchFetch(
- `https://test.invalid/?fixture=${id}&tenant=${tenant.repeat(43)}${hostile ? '&hostile=1' : ''}${short ? '&short=1' : ''}`,
- ),
- command: async (command, value) =>
- (
- await runtime.dispatchFetch(
- `https://test.invalid/command?fixture=${id}${short ? '&short=1' : ''}`,
- { method: 'POST', body: JSON.stringify({ command, value }) },
- )
- ).json(),
- };
-}
-async function waitFor(f, predicate) {
- const deadline = Date.now() + 3000;
- do {
- const snapshot = await f.command('snapshot');
- if (predicate(snapshot)) return snapshot;
- await new Promise((r) => setTimeout(r, 10));
- } while (Date.now() < deadline);
- assert.fail('Fixture did not reach expected state');
-}
-
-test('admission reserves before dispatch, uses a fresh job ID and releases only after cancellation acknowledgement', async () => {
- const f = fixture();
- const r = await f.request();
- assert.equal(r.status, 200);
- assert.equal(await r.text(), 'native result');
- await f.request();
- const s = await f.command('snapshot');
- assert.equal(s.active.length, 0);
- assert.equal(s.calls.length, 2);
- assert.notEqual(s.calls[0].id, s.calls[1].id);
- assert.deepEqual(
- s.stopped,
- s.calls.map((c) => c.id),
- );
- assert.equal(s.calls[0].tenant, 'a'.repeat(43));
- assert.equal(s.calls[0].url, 'https://tenant.internal/mcp');
- assert.deepEqual(s.calls[0].headers, { 'content-type': 'application/json' });
- assert.ok(s.alarm > 0);
-});
-
-test('only the explicit short-deadline fixture uses the 250 ms deadline', async () => {
- const now = Date.UTC(2030, 0, 2, 12);
- for (const [short, deadlineMs] of [
- [false, 60000],
- [true, 250],
- ]) {
- const f = fixture(short);
- await f.command('now', now);
- assert.equal((await f.request()).status, 200);
- const s = await f.command('snapshot');
- assert.equal(s.calls[0].deadlineAt - now, deadlineMs);
- }
-});
-
-test('concurrent admission enforces both one job per account and total capacity', async () => {
- const f = fixture();
- await f.command('hold', true);
- const alice = f.request('a');
- await waitFor(f, (s) => s.calls.length === 1);
- const duplicate = await f.request('a');
- assert.equal(duplicate.status, 429);
- assert.ok(duplicate.headers.get('retry-after'));
- const bob = f.request('b');
- await waitFor(f, (s) => s.calls.length === 2);
- assert.equal((await f.request('c')).status, 429);
- await f.command('pause', true);
- await Promise.all([alice, bob]);
- const s = await f.command('snapshot');
- assert.equal(s.calls.length, 2);
- assert.equal(s.active.length, 0);
- assert.equal((await f.request('c')).status, 503);
-});
-
-test('unknown cleanup suppresses output and retains capacity across object eviction until recovery confirms stop', async () => {
- const f = fixture();
- await f.command('cancelFail', true);
- const r = await f.request();
- assert.equal(r.status, 503);
- assert.equal((await r.text()).includes('diagnostic'), false);
- const first = await f.command('snapshot');
- assert.equal(first.active.length, 1);
- assert.equal(first.active[0].state, 'closing');
- assert.equal((await f.request()).status, 429);
- const ns = await runtime.getDurableObjectNamespace('FIXTURE');
- await runtime.unsafeEvictDurableObject('admission-fixture', 'Fixture', {
- id: ns.idFromName(f.id).toString(),
- });
- assert.equal((await f.command('snapshot')).active.length, 1);
- await f.command('cancelFail', false);
- await f.command('expire');
- await f.command('alarm');
- const recovered = await f.command('snapshot');
- assert.equal(recovered.active.length, 0);
- assert.deepEqual(recovered.stopped, [first.calls[0].id]);
- assert.equal((await f.request()).status, 200);
-});
-
-test('admitted failed work still consumes minute and daily quotas, with independent UTC windows', async () => {
- const f = fixture();
- const now = Date.UTC(2030, 0, 2, 12);
- await f.command('now', now);
- await f.command('runFail', true);
- for (let i = 0; i < 3; i++) assert.equal((await f.request()).status, 503);
- assert.equal((await f.request()).status, 429);
- await f.command('now', now + 60000);
- assert.equal((await f.request()).status, 503);
- assert.equal((await f.request()).status, 429);
- await f.command('now', now + 86400000);
- assert.equal((await f.request()).status, 503);
- assert.equal((await f.command('snapshot')).calls.length, 5);
-});
-
-test('global day and month counters apply across accounts and survive day rollover', async () => {
- const f = fixture(),
- now = Date.UTC(2030, 0, 2, 12);
- await f.command('now', now);
- for (const tenant of ['a', 'b', 'c', 'd', 'e', 'f', 'g'])
- assert.equal((await f.request(tenant)).status, 200);
- assert.equal((await f.request('h')).status, 429);
- await f.command('now', now + 86400000);
- assert.equal((await f.request('h')).status, 200);
- assert.equal((await f.request('i')).status, 429);
- await f.command('now', Date.UTC(2030, 1, 1));
- assert.equal((await f.request('i')).status, 200);
-});
-
-test('invalid identity and authority headers fail before consuming quota or starting work', async () => {
- const f = fixture();
- assert.equal((await f.request('invalid')).status, 400);
- assert.equal((await f.request('a', true)).status, 400);
- const s = await f.command('snapshot');
- assert.equal(s.calls.length, 0);
- assert.equal(s.active.length, 0);
- assert.equal(s.usage.length, 0);
-});
-
-test('operator pause is durable and cannot release unconfirmed cleanup', async () => {
- const f = fixture();
- await f.command('cancelFail', true);
- await f.request();
- await f.command('pause', true);
- assert.equal((await f.request('b')).status, 503);
- const ns = await runtime.getDurableObjectNamespace('FIXTURE');
- await runtime.unsafeEvictDurableObject('admission-fixture', 'Fixture', {
- id: ns.idFromName(f.id).toString(),
- });
- assert.equal((await f.request('b')).status, 503);
- assert.equal((await f.command('snapshot')).active.length, 1);
- await f.command('pause', false);
- assert.equal((await f.request('a')).status, 429);
-});
-
-test('a concurrent burst cannot overbook capacity or charge rejected attempts', async () => {
- const f = fixture();
- await f.command('hold', true);
- const requests = ['a', 'b', 'c', 'd', 'e'].map((tenant) => f.request(tenant));
- await waitFor(f, (s) => s.calls.length === 2);
- await f.command('pause', true);
- const responses = await Promise.all(requests);
- assert.equal(responses.filter((r) => r.status === 429).length, 3);
- const s = await f.command('snapshot');
- assert.equal(s.active.length, 0);
- assert.equal(s.calls.length, 2);
- assert.equal(s.usage.find((row) => row.owner === 'global' && row.period === 'month').used, 2);
-});
-
-test('an RPC that does not return is bounded by deadline and out-of-band cancellation', async () => {
- const f = fixture(true);
- await f.command('hold', true);
- assert.equal((await f.request()).status, 504);
- const s = await f.command('snapshot');
- assert.equal(s.active.length, 0);
- assert.equal(s.calls.length, 1);
- assert.deepEqual(s.stopped, [s.calls[0].id]);
-});
-
-test('maintenance retires expired usage counters and its alarm after an idle month', async () => {
- const f = fixture();
- await f.command('now', Date.UTC(2030, 0, 2));
- await f.request();
- assert.equal((await f.command('snapshot')).usage.length, 4);
- await f.command('now', Date.UTC(2030, 1, 1));
- await f.command('alarm');
- const s = await f.command('snapshot');
- assert.equal(s.usage.length, 0);
- assert.equal(s.alarm, null);
-});
-
-test('a response arriving in the same turn as cancellation has its discarded body closed', async () => {
- const f = fixture();
- await f.command('abortRace', true);
- assert.equal((await f.request()).status, 499);
- const s = await f.command('snapshot');
- assert.equal(s.active.length, 0);
- assert.equal(s.cancelledBodies, 1);
-});
-
-test('retired tenants cannot start work or consume quotas, including after eviction and resume', async () => {
- const f = fixture(),
- owner = 'a'.repeat(43);
- assert.deepEqual(await f.command('retire', owner), { retired: true });
- assert.equal((await f.request('a')).status, 410);
- assert.deepEqual((await f.command('snapshot')).usage, []);
- const ns = await runtime.getDurableObjectNamespace('FIXTURE');
- await runtime.unsafeEvictDurableObject('admission-fixture', 'Fixture', {
- id: ns.idFromName(f.id).toString(),
- });
- await f.command('pause', true);
- await f.command('pause', false);
- assert.equal((await f.request('a')).status, 410);
- assert.equal((await f.request('b')).status, 200);
- assert.deepEqual(await f.command('retire', owner), { retired: true });
- assert.equal((await f.command('snapshot')).calls.length, 1);
-});
-
-test('retirement cancels only the selected tenant and preserves global usage charges', async () => {
- const f = fixture();
- await f.command('hold', true);
- const a = f.request('a'),
- b = f.request('b');
- await waitFor(f, (s) => s.calls.length === 2);
- const results = await Promise.all([
- f.command('retire', 'a'.repeat(43)),
- f.command('retire', 'a'.repeat(43)),
- ]);
- assert.deepEqual(results, [{ retired: true }, { retired: true }]);
- assert.equal((await a).status, 410);
- const current = await f.command('snapshot');
- assert.equal(current.active.length, 1);
- assert.equal(current.active[0].tenant, 'b'.repeat(43));
- assert.equal(current.stopped.length, 1);
- assert.ok(current.usage.every((row) => row.owner !== 'a'.repeat(43)));
- assert.equal(
- current.usage.find((row) => row.owner === 'global' && row.period === 'month').used,
- 2,
- );
- await f.command('pause', true);
- await b;
-});
-
-test('unknown retirement cleanup retains capacity and the permanent deny until confirmed recovery', async () => {
- const f = fixture();
- await f.command('cancelFail', true);
- assert.equal((await f.request()).status, 503);
- assert.deepEqual(await f.command('retire', 'a'.repeat(43)), { retired: false, status: 503 });
- assert.equal((await f.request()).status, 410);
- assert.equal((await f.command('snapshot')).active.length, 1);
- const ns = await runtime.getDurableObjectNamespace('FIXTURE');
- await runtime.unsafeEvictDurableObject('admission-fixture', 'Fixture', {
- id: ns.idFromName(f.id).toString(),
- });
- await f.command('cancelFail', false);
- await f.command('expire');
- await f.command('alarm');
- assert.deepEqual(await f.command('retire', 'a'.repeat(43)), { retired: true });
- assert.equal((await f.command('snapshot')).active.length, 0);
- assert.equal((await f.request()).status, 410);
-});
-
-test('retirement validates exact tenant identity before mutating admission', async () => {
- const f = fixture();
- for (const owner of ['', 'a'.repeat(42), 'a'.repeat(44), `${'a'.repeat(43)}\n`, null, 123])
- assert.deepEqual(await f.command('retire', owner), { retired: false, status: 400 });
- assert.equal((await f.request()).status, 200);
-});
diff --git a/hosting/test/asset-downloads.test.mjs b/hosting/test/asset-downloads.test.mjs
deleted file mode 100644
index a93804af..00000000
--- a/hosting/test/asset-downloads.test.mjs
+++ /dev/null
@@ -1,218 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-
-let runtime, namespace;
-before(async () => {
- const bundle = await build({
- stdin: {
- contents: String.raw`
- import {DurableObject} from 'cloudflare:workers';
- import {ArtifactStore} from './src/artifact-store';
- import {AssetIndex} from './src/asset-index';
- import {AssetDownloadTickets} from './src/asset-downloads';
- import {serviceFailure} from './src/http';
- export class Fixture extends DurableObject {
- constructor(ctx,env) {
- super(ctx,env);
- const now=()=>ctx.storage.kv.get('fixtureTime')??Date.now();
- this.store=new ArtifactStore(ctx,env.ARTIFACTS,{maxBytes:1048576,maxObjects:32,maxGroups:8},now);
- this.assets=new AssetIndex(this.store);
- this.downloads=new AssetDownloadTickets(ctx.storage,{
- group:id=>this.store.group(id),
- download:async(id,head)=>{
- const response=await this.store.download(id,head);
- const race=await ctx.storage.get('readRace');
- if(race?.group) await this.store.deleteGroup(race.group);
- if(race?.time) await ctx.storage.put('fixtureTime',race.time);
- return response;
- }
- },this.assets,now);
- }
- async fetch(request){
- try{
- const path=new URL(request.url).pathname;
- if(path==='/upload') return Response.json(await this.store.upload(request));
- if(path==='/commit') return Response.json(this.assets.commit(await request.json()).record);
- if(path==='/issue') {const a=await request.json();return Response.json(await this.downloads.issue(a.collection,a.assetId,a.revisionId));}
- if(path==='/delete') {await this.store.deleteGroup(await request.text());return new Response('deleted');}
- if(path==='/command') {const {key,value}=await request.json();await this.ctx.storage.put(key,value);return new Response('set');}
- if(path==='/snapshot') return Response.json(this.ctx.storage.sql.exec('SELECT * FROM asset_download_tickets').toArray());
- if(path==='/cleanup') {this.downloads.sweep();return new Response('swept');}
- const file=path.match(/^\/file\/([^/]+)\/([^/]+)$/);
- if(file)return await this.downloads.download(file[1],decodeURIComponent(file[2]),request.method==='HEAD');
- return new Response('not found',{status:404});
- }catch(error){return serviceFailure(error);}
- }
- alarm(){return this.store.sweep();}
- }
- export default {fetch(){return new Response('private',{status:404});}};`,
- resolveDir: fileURLToPath(new URL('../', import.meta.url)),
- loader: 'ts',
- },
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- name: 'download-fixture',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- durableObjects: { TENANTS: { className: 'Fixture', useSQLite: true } },
- r2Buckets: ['ARTIFACTS'],
- outboundService: async () => {
- throw Error('No network');
- },
- }),
- unsafeInspectDurableObjects: true,
- });
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
-});
-after(async () => runtime?.dispose());
-
-const send = (owner, path, init) =>
- namespace.getByName(owner).fetch(`https://fixture.invalid${path}`, init);
-const post = (owner, path, value) =>
- send(owner, path, { method: 'POST', body: JSON.stringify(value) });
-const command = (owner, key, value) => post(owner, '/command', { key, value });
-const selector = { collection: 'project', assetId: 'a_box', revisionId: 'r_one' };
-const issue = (owner, extra = {}) => post(owner, '/issue', { ...selector, ...extra });
-const file = (owner, token, name = 'asset.glb', method = 'GET') =>
- send(owner, `/file/${encodeURIComponent(token)}/${encodeURIComponent(name)}`, { method });
-async function seed(owner) {
- const files = {};
- for (const [name, data] of [
- ['asset.glb', 'glTFfixture'],
- ['source.kiln.js', 'function build(){}'],
- ['manifest.json', '{}'],
- ]) {
- const bytes = Buffer.from(data);
- const response = await send(owner, '/upload', {
- method: 'POST',
- body: bytes,
- headers: {
- 'content-type': 'application/octet-stream',
- 'content-length': String(bytes.length),
- 'x-artifact-name': name,
- 'x-artifact-sha256': createHash('sha256').update(bytes).digest('hex'),
- },
- });
- assert.equal(response.status, 200);
- files[name] = (await response.json()).id;
- }
- const response = await post(owner, '/commit', { ...selector, files, mode: 'save' });
- assert.equal(response.status, 200);
- return { group: await response.json(), files };
-}
-
-test('download tickets select exact private saved bytes and survive object eviction without retaining raw tokens', async () => {
- await seed('alice');
- const now = Date.UTC(2030, 0, 1);
- await command('alice', 'fixtureTime', now);
- const issued = await (await issue('alice')).json();
- assert.match(issued.ticket, /^[a-f0-9]{64}$/);
- assert.equal(issued.expiresAt, now + 600000);
- assert.deepEqual(issued.files, ['asset.glb', 'manifest.json', 'source.kiln.js']);
- const rows = await (await send('alice', '/snapshot')).json();
- assert.equal(rows.length, 1);
- assert(!JSON.stringify(rows).includes(issued.ticket));
- const result = await file('alice', issued.ticket);
- assert.equal(result.status, 200);
- assert.equal(await result.text(), 'glTFfixture');
- assert.equal(result.headers.get('cache-control'), 'private, no-store');
- assert.match(result.headers.get('content-disposition'), /attachment; filename="asset.glb"/);
- assert.equal((await file('bob', issued.ticket)).status, 404);
- await runtime.unsafeEvictDurableObject('download-fixture', 'Fixture', {
- id: namespace.idFromName('alice').toString(),
- });
- assert.equal(
- await (await file('alice', issued.ticket, 'source.kiln.js')).text(),
- 'function build(){}',
- );
-});
-
-test('unknown revisions and unsafe filenames fail without issuing or spending a ticket', async () => {
- await seed('invalid');
- assert.equal((await issue('invalid', { revisionId: 'r_missing' })).status, 404);
- assert.equal((await issue('invalid', { collection: '../project' })).status, 400);
- assert.deepEqual(await (await send('invalid', '/snapshot')).json(), []);
- const { ticket } = await (await issue('invalid')).json();
- for (const name of ['../source.kiln.js', 'not-saved.txt', 'preview.png', 'asset.glb\n']) {
- assert.equal((await file('invalid', ticket, name)).status, 404);
- }
- assert.equal((await file('invalid', `${ticket}\n`)).status, 404);
- assert.equal((await (await send('invalid', '/snapshot')).json())[0].uses, 0);
-});
-
-test('ticket expiry is independent of saved retention and is rechecked after reading storage', async () => {
- await seed('expiry');
- const now = Date.UTC(2030, 0, 2);
- await command('expiry', 'fixtureTime', now);
- const { ticket } = await (await issue('expiry')).json();
- await command('expiry', 'readRace', { time: now + 600000 });
- assert.equal((await file('expiry', ticket)).status, 404);
- await command('expiry', 'readRace', null);
- const renewed = await (await issue('expiry')).json();
- assert.notEqual(renewed.ticket, ticket);
- assert.equal(await (await file('expiry', renewed.ticket)).text(), 'glTFfixture');
- assert.equal((await (await send('expiry', '/snapshot')).json()).length, 1);
-});
-
-test('deleting the selected revision revokes its ticket even when another revision keeps the same bytes', async () => {
- const { group, files } = await seed('deleted');
- assert.equal(
- (await post('deleted', '/commit', { ...selector, revisionId: 'r_two', files, mode: 'import' }))
- .status,
- 200,
- );
- const { ticket } = await (await issue('deleted')).json();
- await command('deleted', 'readRace', { group: group.id });
- assert.equal((await file('deleted', ticket)).status, 404);
- await command('deleted', 'readRace', null);
- const next = await (await issue('deleted', { revisionId: 'r_two' })).json();
- assert.equal(await (await file('deleted', next.ticket)).text(), 'glTFfixture');
-});
-
-test('concurrent redemption cannot exceed the per-ticket transfer limit and HEAD returns no bytes', async () => {
- await seed('uses');
- const { ticket } = await (await issue('uses')).json();
- const head = await file('uses', ticket, 'asset.glb', 'HEAD');
- assert.equal(head.status, 200);
- assert.equal(await head.text(), '');
- const results = await Promise.all(
- Array.from({ length: 40 }, async () => {
- const r = await file('uses', ticket);
- await r.arrayBuffer();
- return r.status;
- }),
- );
- assert.equal(results.filter((status) => status === 200).length, 31);
- assert.equal(results.filter((status) => status === 429).length, 9);
- assert.equal((await (await send('uses', '/snapshot')).json())[0].uses, 32);
-});
-
-test('issuance has a bounded persistent count and expired rows can be reclaimed', async () => {
- await seed('capacity');
- const now = Date.UTC(2030, 0, 3);
- await command('capacity', 'fixtureTime', now);
- const results = await Promise.all(
- Array.from({ length: 135 }, async () => {
- const r = await issue('capacity');
- await r.text();
- return r.status;
- }),
- );
- assert.equal(results.filter((s) => s === 200).length, 128);
- assert.equal(results.filter((s) => s === 429).length, 7);
- await command('capacity', 'fixtureTime', now + 600000);
- assert.equal((await send('capacity', '/cleanup', { method: 'POST' })).status, 200);
- assert.deepEqual(await (await send('capacity', '/snapshot')).json(), []);
- assert.equal((await issue('capacity')).status, 200);
-});
diff --git a/hosting/test/asset-index.test.mjs b/hosting/test/asset-index.test.mjs
deleted file mode 100644
index fcabcd49..00000000
--- a/hosting/test/asset-index.test.mjs
+++ /dev/null
@@ -1,181 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-let runtime;
-let namespace;
-before(async () => {
- const result = await build({
- entryPoints: [fileURLToPath(new URL('../src/tenant-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: result.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- r2Buckets: ['ARTIFACTS'],
- durableObjects: { TENANTS: { className: 'KilnTenant', useSQLite: true } },
- bindings: {
- STORAGE_MAX_BYTES: '4194304',
- STORAGE_MAX_OBJECTS: '256',
- STORAGE_MAX_GROUPS: '128',
- },
- outboundService: async () => {
- throw new Error('No external requests');
- },
- }),
- );
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
-});
-after(async () => runtime?.dispose());
-const call = (owner, path, init) =>
- namespace.get(namespace.idFromName(owner)).fetch(`https://tenant.internal${path}`, init);
-const post = (owner, path, body) =>
- call(owner, path, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify(body),
- });
-async function files(owner) {
- const result = {};
- for (const [name, media] of [
- ['asset.glb', 'model/gltf-binary'],
- ['manifest.json', 'application/json'],
- ]) {
- const bytes = Buffer.from(name);
- const response = await call(owner, '/internal/artifacts', {
- method: 'POST',
- body: bytes,
- headers: {
- 'content-type': media,
- 'content-length': String(bytes.length),
- 'x-artifact-name': name,
- 'x-artifact-sha256': createHash('sha256').update(bytes).digest('hex'),
- },
- });
- assert.equal(response.status, 201);
- result[name] = (await response.json()).id;
- }
- return result;
-}
-const commit = (owner, input) =>
- post(owner, '/internal/assets/commit', {
- collection: 'project',
- assetId: 'post',
- revisionId: 'r_one',
- mode: 'save',
- ...input,
- });
-const lookup = (owner, collection, asset, revision) =>
- call(owner, `/internal/assets/${collection}/${asset}/${revision}`);
-
-test('saved asset index binds exact files to collection and revision and denies other tenants', async () => {
- const inventory = await files('index');
- const saved = await commit('index', { files: inventory });
- assert.equal(saved.status, 201);
- const group = await saved.json();
- assert.equal(group.key, 'assets/project/post/r_one');
- assert.deepEqual(group.files, inventory);
- assert.deepEqual(
- (await (await lookup('index', 'project', 'post', 'r_one')).json()).files,
- inventory,
- );
- assert.equal((await lookup('other', 'project', 'post', 'r_one')).status, 404);
- assert.equal((await lookup('index', 'library', 'post', 'r_one')).status, 404);
- assert.equal((await commit('other', { files: inventory })).status, 404);
- assert.equal((await commit('index', { files: inventory })).status, 200);
-});
-
-test('new-asset creation and parent checks are atomic across concurrent saves', async () => {
- const inventory = await files('parents');
- const results = await Promise.all(
- ['r_a', 'r_b'].map((revisionId) => commit('parents', { files: inventory, revisionId })),
- );
- assert.deepEqual(results.map((response) => response.status).sort(), [201, 409]);
- const accepted = await results.find((response) => response.status === 201).json();
- const parentRevision = accepted.key.split('/').at(-1);
- assert.equal(
- (await commit('parents', { files: inventory, revisionId: 'r_child', parentRevision })).status,
- 201,
- );
- assert.equal(
- (
- await commit('parents', {
- files: inventory,
- revisionId: 'r_missing',
- parentRevision: 'r_unknown',
- })
- ).status,
- 404,
- );
- assert.equal(
- (await commit('parents', { files: inventory, assetId: 'other', parentRevision })).status,
- 404,
- );
- const changed = await files('parents');
- assert.equal(
- (await commit('parents', { files: changed, revisionId: 'r_child', parentRevision })).status,
- 409,
- );
-});
-
-test('asset catalogue pages have stable bounded cursors and independent collection scope', async () => {
- const inventory = await files('pages');
- for (let i = 0; i < 35; i++) {
- const response = await commit('pages', {
- files: inventory,
- mode: 'import',
- assetId: `a_${String(i).padStart(2, '0')}`,
- });
- assert.equal(response.status, 201);
- }
- assert.equal((await commit('pages', { files: inventory, collection: 'library' })).status, 201);
- const page = async (input) => {
- const response = await post('pages', '/internal/assets/list', {
- collection: 'project',
- ...input,
- });
- assert.equal(response.status, 200);
- return response.json();
- };
- const first = await page({});
- assert.equal(first.records.length, 32);
- assert.equal(first.next, first.records.at(-1).key);
- const second = await page({ after: first.next });
- assert.equal(second.records.length, 3);
- assert.equal(second.next, null);
- assert.equal(new Set([...first.records, ...second.records].map((record) => record.key)).size, 35);
- assert.equal(
- (
- await post('pages', '/internal/assets/list', {
- collection: 'project',
- after: 'assets/library/post/r_one',
- })
- ).status,
- 400,
- );
-});
-
-test('asset commits require safe identities and matching filenames and never pin an invalid inventory', async () => {
- const inventory = await files('invalid');
- for (const bad of [
- { collection: 'elsewhere' },
- { assetId: 'x/y' },
- { revisionId: 'r_a\n' },
- { files: { 'asset.glb': inventory['manifest.json'], 'manifest.json': inventory['asset.glb'] } },
- { files: { 'asset.glb': inventory['asset.glb'] } },
- { parentRevision: 'r_one' },
- { mode: 'unknown' },
- ]) {
- assert.equal((await commit('invalid', { files: inventory, ...bad })).status, 400);
- }
- assert.equal((await (await call('invalid', '/internal/usage')).json()).groups, 0);
-});
diff --git a/hosting/test/auth.test.mjs b/hosting/test/auth.test.mjs
deleted file mode 100644
index 28c70099..00000000
--- a/hosting/test/auth.test.mjs
+++ /dev/null
@@ -1,2388 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash, generateKeyPairSync, randomBytes, sign } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { after, before, beforeEach, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-import { migrateAccounts } from './database.mjs';
-import { rateLimitBindings } from './rate-limit-bindings.mjs';
-
-const origin = 'https://kiln.example.com';
-let runtime;
-let database;
-let outboundCalls = 0;
-let beforeProviderReply;
-const googleIssuer = 'https://accounts.google.com';
-const googleKeys = generateKeyPairSync('rsa', { modulusLength: 2048 });
-const googleCodes = new Map();
-const subjectIds = new Map([
- ['alice', '1001'],
- ['bob', '1002'],
-]);
-function subjectId(user) {
- if (!subjectIds.has(user)) subjectIds.set(user, String(1001 + subjectIds.size));
- return subjectIds.get(user);
-}
-const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
-const digest = (value) => createHash('sha256').update(value).digest('base64url');
-const cookies = (response) =>
- response.headers
- .getSetCookie()
- .map((value) => value.split(';')[0])
- .join('; ');
-before(async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- name: 'auth-fixture',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['global_fetch_strictly_public'],
- kvNamespaces: ['OAUTH_KV'],
- ratelimits: rateLimitBindings,
- d1Databases: ['ACCOUNTS'],
- durableObjects: { TENANTS: 'TestTenant' },
- serviceBindings: { NATIVE_COMPUTE: { name: 'auth-fixture', entrypoint: 'TestCompute' } },
- bindings: {
- PUBLIC_ORIGIN: origin,
- GITHUB_CLIENT_ID: 'fixture-client',
- GITHUB_CLIENT_SECRET: 'fixture-secret-not-a-real-credential',
- GOOGLE_CLIENT_ID: 'fixture-google-client',
- GOOGLE_CLIENT_SECRET: 'fixture-google-secret',
- },
- outboundService: async (request) => {
- outboundCalls++;
- if (request.url === `${googleIssuer}/.well-known/openid-configuration`) {
- return Response.json({
- issuer: googleIssuer,
- authorization_endpoint: `${googleIssuer}/o/oauth2/v2/auth`,
- token_endpoint: 'https://oauth2.googleapis.com/token',
- jwks_uri: 'https://www.googleapis.com/oauth2/v3/certs',
- id_token_signing_alg_values_supported: ['RS256'],
- code_challenge_methods_supported: ['S256'],
- });
- }
- if (request.url === 'https://www.googleapis.com/oauth2/v3/certs') {
- return Response.json({
- keys: [
- {
- ...googleKeys.publicKey.export({ format: 'jwk' }),
- kid: 'test',
- alg: 'RS256',
- use: 'sig',
- },
- ],
- });
- }
- if (request.url === 'https://oauth2.googleapis.com/token') {
- if (beforeProviderReply) await beforeProviderReply();
- const form = new URLSearchParams(await request.text());
- const flow = googleCodes.get(form.get('code'));
- assert.ok(flow);
- assert.equal(digest(form.get('code_verifier')), flow.challenge);
- assert.equal(form.get('client_id'), 'fixture-google-client');
- assert.equal(form.get('client_secret'), 'fixture-google-secret');
- assert.equal(form.get('redirect_uri'), `${origin}/oauth/google/callback`);
- const now = Math.floor(Date.now() / 1000);
- const input = `${encode({ alg: 'RS256', kid: 'test' })}.${encode({ iss: googleIssuer, sub: subjectId(flow.user), aud: 'fixture-google-client', exp: now + 300, iat: now, nonce: flow.nonce })}`;
- return Response.json({
- access_token: 'fixture-google-token',
- token_type: 'Bearer',
- expires_in: 300,
- id_token: `${input}.${sign('RSA-SHA256', Buffer.from(input), googleKeys.privateKey).toString('base64url')}`,
- });
- }
- if (
- [
- 'https://client.example/metadata.json',
- 'https://client.example/choices.json',
- 'https://client.example/signed-only.json',
- ].includes(request.url)
- ) {
- const choice = request.url.endsWith('/choices.json');
- const signedOnly = request.url.endsWith('/signed-only.json');
- return Response.json({
- client_id: request.url,
- client_name: 'Metadata fixture client',
- redirect_uris: ['https://client.example/callback'],
- token_endpoint_auth_method: choice || signedOnly ? 'private_key_jwt' : 'none',
- ...(choice || signedOnly
- ? {
- token_endpoint_auth_methods_supported: signedOnly
- ? ['private_key_jwt']
- : ['none', 'private_key_jwt'],
- jwks_uri: 'https://client.example/jwks.json',
- }
- : {}),
- grant_types: ['authorization_code', 'refresh_token'],
- response_types: ['code'],
- });
- }
- if (request.url === 'https://github.com/login/oauth/access_token') {
- const form = new URLSearchParams(await request.text());
- assert.equal(form.get('client_id'), 'fixture-client');
- assert.equal(form.get('client_secret'), 'fixture-secret-not-a-real-credential');
- assert.equal(form.get('redirect_uri'), `${origin}/oauth/github/callback`);
- assert.match(form.get('code_verifier'), /^[A-Za-z0-9_-]{43,128}$/);
- return Response.json({
- access_token: `fixture-${form.get('code')}`,
- token_type: 'bearer',
- });
- }
- if (request.url === 'https://api.github.com/user') {
- if (beforeProviderReply) await beforeProviderReply();
- const token = request.headers.get('authorization');
- assert.match(token, /^Bearer fixture-[a-zA-Z0-9_-]+$/);
- return Response.json({
- id: Number(subjectId(token.slice('Bearer fixture-'.length))),
- login: 'not-used-as-identity',
- });
- }
- throw new Error(`Unexpected outbound URL ${new URL(request.url).origin}`);
- },
- }),
- );
- database = await runtime.getD1Database('ACCOUNTS');
- await migrateAccounts(database);
-});
-after(async () => runtime?.dispose());
-// Each scenario owns its connections; prior scenarios must not consume its quota.
-beforeEach(async () => {
- await database.prepare('DELETE FROM kiln_connections').run();
-});
-
-test('unauthenticated MCP is challenged with canonical resource metadata', async () => {
- const response = await runtime.dispatchFetch(`${origin}/mcp`, { redirect: 'manual' });
- assert.equal(response.status, 401);
- assert.match(
- response.headers.get('www-authenticate'),
- /resource_metadata="https:\/\/kiln\.example\.com\/\.well-known\/oauth-protected-resource\/mcp"/,
- );
-});
-
-async function register(name = 'Fixture client', server = runtime) {
- const response = await server.dispatchFetch(`${origin}/register`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- client_name: name,
- redirect_uris: ['https://client.example/callback'],
- token_endpoint_auth_method: 'none',
- grant_types: ['authorization_code', 'refresh_token'],
- response_types: ['code'],
- }),
- });
- assert.equal(response.status, 201);
- return (await response.json()).client_id;
-}
-
-async function consent({
- clientId,
- scope = 'kiln:use offline_access',
- patch = {},
- server = runtime,
-} = {}) {
- clientId ??= await register('Fixture client', server);
- const verifier = randomBytes(32).toString('base64url');
- const params = new URLSearchParams({
- client_id: clientId,
- redirect_uri: 'https://client.example/callback',
- response_type: 'code',
- resource: `${origin}/mcp`,
- scope,
- state: 'client-state',
- code_challenge: digest(verifier),
- code_challenge_method: 'S256',
- ...patch,
- });
- const response = await server.dispatchFetch(`${origin}/authorize?${params}`, {
- redirect: 'manual',
- });
- const page = await response.text();
- return {
- server,
- response,
- page,
- verifier,
- clientId,
- handle: page.match(/name="handle" value="([^"]+)"/)?.[1],
- cookie: cookies(response),
- };
-}
-
-async function approve(start, { cookie = start.cookie, decision = 'github' } = {}) {
- return start.server.dispatchFetch(`${origin}/authorize`, {
- method: 'POST',
- redirect: 'manual',
- headers: { 'content-type': 'application/x-www-form-urlencoded', origin, cookie },
- body: new URLSearchParams({ handle: start.handle, decision }),
- });
-}
-
-async function grant(user = 'alice', options = {}) {
- const start = await consent(options);
- assert.equal(start.response.status, 200);
- const provider = options.provider ?? 'github';
- const approved = await approve(start, { decision: provider });
- assert.equal(approved.status, 302);
- const upstream = new URL(approved.headers.get('location'));
- assert.equal(upstream.origin, provider === 'github' ? 'https://github.com' : googleIssuer);
- assert.equal(upstream.searchParams.get('code_challenge_method'), 'S256');
- assert.equal(upstream.searchParams.get('scope'), provider === 'github' ? '' : 'openid profile');
- const code = provider === 'github' ? user : randomBytes(24).toString('base64url');
- if (provider === 'google')
- googleCodes.set(code, {
- user,
- nonce: upstream.searchParams.get('nonce'),
- challenge: upstream.searchParams.get('code_challenge'),
- });
- const callback = `${origin}/oauth/${provider}/callback?${new URLSearchParams({ state: upstream.searchParams.get('state'), code })}`;
- const response = await start.server.dispatchFetch(callback, {
- headers: { cookie: cookies(approved) },
- redirect: 'manual',
- });
- assert.equal(response.status, 302);
- const redirect = new URL(response.headers.get('location'));
- assert.equal(redirect.origin, 'https://client.example');
- assert.equal(redirect.searchParams.get('state'), 'client-state');
- assert.equal(redirect.searchParams.get('iss'), origin);
- return {
- ...start,
- code: redirect.searchParams.get('code'),
- callback,
- upstreamCookie: cookies(approved),
- browserCookie: cookies(response),
- callbackHeaders: response.headers,
- };
-}
-
-async function exchange(authorization, patch = {}) {
- return authorization.server.dispatchFetch(`${origin}/oauth/token`, {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- grant_type: 'authorization_code',
- code: authorization.code,
- client_id: authorization.clientId,
- redirect_uri: 'https://client.example/callback',
- code_verifier: authorization.verifier,
- resource: `${origin}/mcp`,
- ...patch,
- }),
- });
-}
-
-async function token(user, options) {
- const authorization = await grant(user, options);
- const response = await exchange(authorization);
- assert.equal(response.status, 200);
- return { ...(await response.json()), clientId: authorization.clientId };
-}
-
-async function mcp(credential, options = {}) {
- return runtime.dispatchFetch(`${origin}/mcp`, {
- method: 'POST',
- ...options,
- headers: {
- authorization: `Bearer ${credential.access_token}`,
- 'content-type': 'application/json',
- ...options.headers,
- },
- body:
- options.body ??
- JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method: 'tools/call',
- params: { name: 'kiln_validate', arguments: { code: 'function build(){}' } },
- }),
- });
-}
-
-test('browser account sign-in establishes a private session for either verified provider', async () => {
- for (const provider of ['google', 'github']) {
- const authorization = await grant('alice', { provider });
- assert.match(authorization.browserCookie, /__Host-kiln-session=[a-f0-9]{64}/);
- const page = await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- });
- assert.equal(page.status, 200);
- assert.equal(page.headers.get('cache-control'), 'no-store');
- assert.equal(page.headers.get('referrer-policy'), 'no-referrer');
- assert.match(page.headers.get('content-security-policy'), /frame-ancestors 'none'/);
- const html = await page.text();
- assert.match(html, /Your Kiln account/);
- assert.match(html, provider === 'google' ? /Google/ : /GitHub/);
- assert.match(html, /name="csrf" value="[a-f0-9]{64}"/);
- assert.ok(!html.includes(authorization.browserCookie));
- assert.ok(!html.includes('fixture-secret'));
- const sessionCookie = authorization.callbackHeaders
- .getSetCookie()
- .find((value) => value.startsWith('__Host-kiln-session='));
- for (const attribute of ['Secure', 'HttpOnly', 'SameSite=Lax', 'Path=/'])
- assert.ok(sessionCookie.includes(attribute));
- }
-});
-
-test('browser account logout is CSRF protected and leaves MCP connections authorized', async () => {
- const authorization = await grant();
- const credential = await (await exchange(authorization)).json();
- const headers = { cookie: authorization.browserCookie };
- const page = await (await runtime.dispatchFetch(`${origin}/account`, { headers })).text();
- const csrf = page.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];
- assert.ok(csrf);
- const post = (body, extra = {}) =>
- runtime.dispatchFetch(`${origin}/account/logout`, {
- method: 'POST',
- redirect: 'manual',
- headers: {
- ...headers,
- origin,
- 'content-type': 'application/x-www-form-urlencoded',
- ...extra,
- },
- body,
- });
- assert.equal((await runtime.dispatchFetch(`${origin}/account/logout`, { headers })).status, 405);
- for (const body of ['', `csrf=${'0'.repeat(64)}`, `csrf=${csrf}&csrf=${csrf}`])
- assert.equal((await post(body)).status, 403);
- for (const badOrigin of ['', 'https://evil.example', 'https://sibling.kiln.example.com'])
- assert.equal((await post(`csrf=${csrf}`, { origin: badOrigin })).status, 403);
- assert.equal(
- (await post(JSON.stringify({ csrf }), { 'content-type': 'application/json' })).status,
- 415,
- );
- assert.equal((await runtime.dispatchFetch(`${origin}/account`, { headers })).status, 200);
- const loggedOut = await post(`csrf=${csrf}`);
- assert.equal(loggedOut.status, 303);
- assert.equal(loggedOut.headers.get('location'), '/account');
- assert.match(loggedOut.headers.get('set-cookie'), /Max-Age=0/);
- assert.equal((await runtime.dispatchFetch(`${origin}/account`, { headers })).status, 401);
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('browser account sessions cannot substitute for MCP tokens or another browser CSRF', async () => {
- const alice = await grant('alice');
- const bob = await grant('bob');
- const alicePage = await (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: alice.browserCookie },
- })
- ).text();
- const csrf = alicePage.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];
- assert.ok(csrf);
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/account/logout`, {
- method: 'POST',
- headers: {
- cookie: bob.browserCookie,
- origin,
- 'content-type': 'application/x-www-form-urlencoded',
- },
- body: `csrf=${csrf}`,
- redirect: 'manual',
- })
- ).status,
- 403,
- );
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/mcp`, {
- method: 'POST',
- headers: { cookie: alice.browserCookie },
- body: '{}',
- })
- ).status,
- 401,
- );
- const credential = await (await exchange(alice)).json();
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { authorization: `Bearer ${credential.access_token}` },
- })
- ).status,
- 401,
- );
- assert.equal(
- (
- await runtime.dispatchFetch(
- `${origin}/account?cookie=${encodeURIComponent(alice.browserCookie)}`,
- )
- ).status,
- 400,
- );
-});
-
-async function browserLogin(
- provider = 'github',
- user = 'alice',
- server = runtime,
- cookie = '',
- returnTo,
-) {
- const start = await server.dispatchFetch(`${origin}/account/login`, {
- method: 'POST',
- redirect: 'manual',
- headers: { origin, cookie, 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({ provider, ...(returnTo === undefined ? {} : { returnTo }) }),
- });
- assert.equal(start.status, 302);
- const upstream = new URL(start.headers.get('location'));
- assert.equal(upstream.origin, provider === 'github' ? 'https://github.com' : googleIssuer);
- assert.equal(upstream.searchParams.get('code_challenge_method'), 'S256');
- assert.equal(upstream.searchParams.get('scope'), provider === 'github' ? '' : 'openid profile');
- const code = provider === 'github' ? user : randomBytes(24).toString('base64url');
- if (provider === 'google')
- googleCodes.set(code, {
- user,
- nonce: upstream.searchParams.get('nonce'),
- challenge: upstream.searchParams.get('code_challenge'),
- });
- return {
- start,
- callback: `${origin}/oauth/${provider}/callback?${new URLSearchParams({ state: upstream.searchParams.get('state'), code })}`,
- cookie: cookies(start),
- };
-}
-
-test('direct browser login uses either provider, no MCP client and no upstream token in cookies', async () => {
- const signedOut = await runtime.dispatchFetch(`${origin}/account`);
- assert.equal(signedOut.status, 401);
- const html = await signedOut.text();
- assert.match(html, /action="\/account\/login"/);
- for (const provider of ['google', 'github']) {
- const flow = await browserLogin(provider);
- assert.match(flow.cookie, /__Host-kiln-login=[a-f0-9]{64}/);
- const callback = await runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- });
- assert.equal(callback.status, 303);
- assert.equal(callback.headers.get('location'), '/account');
- assert.match(callback.headers.get('set-cookie'), /__Host-kiln-session=[a-f0-9]{64}/);
- assert.ok(!callback.headers.get('set-cookie').includes('fixture-'));
- assert.ok(
- callback.headers
- .getSetCookie()
- .some((value) => value.startsWith('__Host-kiln-login=;') && value.includes('Max-Age=0')),
- );
- assert.equal(
- (await runtime.dispatchFetch(`${origin}/account`, { headers: { cookie: cookies(callback) } }))
- .status,
- 200,
- );
- }
-});
-
-test('direct browser login requires its browser, exact provider and one-time state before contacting a provider', async () => {
- const flow = await browserLogin();
- const count = outboundCalls;
- for (const [url, cookie] of [
- [flow.callback, ''],
- [flow.callback, `${flow.cookie}; ${flow.cookie}`],
- [flow.callback.replace('/github/', '/google/'), flow.cookie],
- [`${flow.callback}&state=kb1_invalid`, flow.cookie],
- [flow.callback.replace(/state=[^&]+/, `state=kb1_${'0'.repeat(64)}`), flow.cookie],
- ]) {
- const denied = await runtime.dispatchFetch(url, { headers: { cookie }, redirect: 'manual' });
- assert.equal(denied.status, 400);
- assert.ok(!denied.headers.get('set-cookie')?.includes('__Host-kiln-session='));
- }
- assert.equal(outboundCalls, count);
- const results = await Promise.all(
- Array.from({ length: 5 }, () =>
- runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- }),
- ),
- );
- assert.deepEqual(results.map((r) => r.status).sort(), [303, 400, 400, 400, 400]);
- assert.equal(outboundCalls - count, 2);
-});
-
-test('direct browser login rejects forged forms and arbitrary return URLs before outbound calls', async () => {
- const count = outboundCalls;
- const post = (body, extra = {}, method = 'POST') =>
- runtime.dispatchFetch(`${origin}/account/login`, {
- method,
- redirect: 'manual',
- headers: { origin, 'content-type': 'application/x-www-form-urlencoded', ...extra },
- ...(method === 'POST' ? { body } : {}),
- });
- assert.equal((await post('', {}, 'GET')).status, 405);
- assert.equal((await post('provider=github', { origin: 'https://evil.example' })).status, 403);
- assert.equal((await post('provider=github', { origin: '' })).status, 403);
- for (const body of [
- 'provider=unknown',
- 'provider=github&provider=google',
- 'provider=github&returnTo=https://evil.example',
- `provider=github&returnTo=${encodeURIComponent('//evil.example')}`,
- `provider=github&returnTo=${encodeURIComponent(`/downloads/${'a'.repeat(64)}/asset.glb?redirect=https://evil.example`)}`,
- `provider=github&returnTo=${encodeURIComponent(`/downloads/${'a'.repeat(64)}/asset.glb\n`)}`,
- 'provider=github&returnTo=/account&returnTo=/account',
- '',
- ])
- assert.equal((await post(body)).status, 400);
- assert.equal((await post('{}', { 'content-type': 'application/json' })).status, 415);
- assert.equal(outboundCalls, count);
-});
-
-test('both browser providers resume only the server-retained download path after sign-in', async () => {
- const returnTo = `/downloads/${'a'.repeat(64)}/source.kiln.js`;
- for (const provider of ['google', 'github']) {
- const flow = await browserLogin(provider, 'alice', runtime, '', returnTo);
- const upstream = new URL(flow.start.headers.get('location'));
- assert.ok(!upstream.href.includes(encodeURIComponent(returnTo)));
- const callback = await runtime.dispatchFetch(`${flow.callback}&returnTo=https://evil.example`, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- });
- assert.equal(callback.status, 303);
- assert.equal(callback.headers.get('location'), returnTo);
- assert.match(callback.headers.get('set-cookie'), /__Host-kiln-session=/);
- assert.equal(
- (
- await runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- })
- ).status,
- 400,
- );
- }
-});
-
-test('invalid server-retained download continuation fails before provider exchange or session creation', async () => {
- const flow = await browserLogin(
- 'github',
- 'alice',
- runtime,
- '',
- `/downloads/${'b'.repeat(64)}/asset.glb`,
- );
- await database
- .prepare('UPDATE kiln_browser_logins SET return_to=? WHERE state_hash=?')
- .bind(
- '//evil.example',
- digest(
- JSON.stringify([
- 'kiln-browser-login-v1',
- origin,
- 'state',
- new URL(flow.callback).searchParams.get('state'),
- ]),
- ),
- )
- .run();
- const count = outboundCalls;
- const response = await runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- });
- assert.equal(response.status, 400);
- assert.equal(response.headers.get('location'), null);
- assert.equal(response.headers.get('set-cookie'), null);
- assert.equal(outboundCalls, count);
-});
-
-test('direct browser login cancellation consumes its state and returns a safe retry page', async () => {
- const flow = await browserLogin();
- const cancellation = new URL(flow.callback);
- cancellation.searchParams.delete('code');
- cancellation.searchParams.set('error', 'access_denied');
- cancellation.searchParams.set('error_description', '<script>provider-detail</script>');
- const count = outboundCalls;
- const response = await runtime.dispatchFetch(cancellation, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- });
- assert.equal(response.status, 400);
- assert.ok(!(await response.text()).includes('provider-detail'));
- assert.equal(
- (
- await runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- })
- ).status,
- 400,
- );
- assert.equal(outboundCalls, count);
-});
-
-test('direct browser login stores hashed state and binding and rejects expiry without provider calls', async () => {
- const flow = await browserLogin();
- const rows = await database.prepare('SELECT * FROM kiln_browser_logins').all();
- const serialized = JSON.stringify(rows.results);
- assert.ok(!serialized.includes(new URL(flow.callback).searchParams.get('state')));
- assert.ok(!serialized.includes(flow.cookie.split('=')[1]));
- await database.prepare('UPDATE kiln_browser_logins SET expires_at=0').run();
- const count = outboundCalls;
- assert.equal(
- (
- await runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- })
- ).status,
- 400,
- );
- assert.equal(outboundCalls, count);
-});
-
-test('restarting direct browser login retires the old intent and database failure rolls back that retirement', async () => {
- const first = await browserLogin();
- const second = await browserLogin('github', 'alice', runtime, first.cookie);
- const count = outboundCalls;
- assert.equal(
- (
- await runtime.dispatchFetch(first.callback, {
- headers: { cookie: first.cookie },
- redirect: 'manual',
- })
- ).status,
- 400,
- );
- assert.equal(outboundCalls, count);
- await database
- .prepare(`CREATE TRIGGER reject_browser_login BEFORE INSERT ON kiln_browser_logins
- BEGIN SELECT RAISE(ABORT, 'fixture rejection'); END`)
- .run();
- try {
- const rejected = await runtime.dispatchFetch(`${origin}/account/login`, {
- method: 'POST',
- headers: {
- origin,
- cookie: second.cookie,
- 'content-type': 'application/x-www-form-urlencoded',
- },
- body: 'provider=github',
- redirect: 'manual',
- });
- assert.equal(rejected.status, 503);
- assert.equal(rejected.headers.get('set-cookie'), null);
- assert.equal(await rejected.text(), 'Service temporarily unavailable');
- } finally {
- await database.prepare('DROP TRIGGER reject_browser_login').run();
- }
- assert.equal(
- (
- await runtime.dispatchFetch(second.callback, {
- headers: { cookie: second.cookie },
- redirect: 'manual',
- })
- ).status,
- 303,
- );
-});
-
-test('direct browser login has a bounded global intent table and cleans expired reservations', async () => {
- await database
- .prepare(`WITH RECURSIVE numbers(n) AS (
- SELECT 1 UNION ALL SELECT n+1 FROM numbers WHERE n<4096)
- INSERT INTO kiln_browser_logins(state_hash,binding_hash,provider,verifier,nonce,expires_at)
- SELECT 'fixture-cap-'||n,'fixture-cap-'||n,'github','fixture','fixture',? FROM numbers
- LIMIT MAX(0, 4096-(SELECT COUNT(*) FROM kiln_browser_logins))`)
- .bind(Date.now() + 600_000)
- .run();
- try {
- const count = outboundCalls;
- const replies = await Promise.all(
- Array.from({ length: 3 }, () =>
- runtime.dispatchFetch(`${origin}/account/login`, {
- method: 'POST',
- headers: { origin, 'content-type': 'application/x-www-form-urlencoded' },
- body: 'provider=github',
- redirect: 'manual',
- }),
- ),
- );
- assert.deepEqual(
- replies.map((r) => r.status),
- [429, 429, 429],
- );
- assert.equal(
- (await database.prepare('SELECT COUNT(*) AS n FROM kiln_browser_logins').first()).n,
- 4096,
- );
- assert.equal(outboundCalls, count);
- await database
- .prepare("UPDATE kiln_browser_logins SET expires_at=0 WHERE state_hash LIKE 'fixture-cap-%'")
- .run();
- await browserLogin();
- assert.ok(
- (await database.prepare('SELECT COUNT(*) AS n FROM kiln_browser_logins').first()).n < 4096,
- );
- } finally {
- await database
- .prepare("DELETE FROM kiln_browser_logins WHERE state_hash LIKE 'fixture-cap-%'")
- .run();
- }
-});
-
-test('metadata advertises the configured audience, scopes, issuer and S256', async () => {
- const resource = await (
- await runtime.dispatchFetch(`${origin}/.well-known/oauth-protected-resource/mcp`)
- ).json();
- assert.equal(resource.resource, `${origin}/mcp`);
- assert.deepEqual(resource.authorization_servers, [origin]);
- assert.deepEqual(resource.scopes_supported, ['kiln:use']);
- const auth = await (
- await runtime.dispatchFetch(`${origin}/.well-known/oauth-authorization-server`)
- ).json();
- assert.equal(auth.issuer, origin);
- assert.ok(auth.code_challenge_methods_supported.includes('S256'));
-});
-
-test('MCP authorization creates a durable connection and activates it only on code exchange', async () => {
- const authorization = await grant();
- const pending = await database
- .prepare('SELECT * FROM kiln_connections WHERE client_id=?')
- .bind(authorization.clientId)
- .first();
- assert.ok(pending);
- assert.match(pending.id, /^kc_[a-f0-9]{32}$/);
- assert.equal(pending.state, 'pending');
- assert.equal(pending.grant_id, null);
- const credential = await (await exchange(authorization)).json();
- const active = await database
- .prepare('SELECT * FROM kiln_connections WHERE id=?')
- .bind(pending.id)
- .first();
- assert.equal(active.state, 'active');
- assert.ok(active.grant_id);
- assert.ok(!JSON.stringify(active).includes(credential.access_token));
- assert.ok(!JSON.stringify(active).includes(credential.refresh_token));
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('edge discovery requires a scoped active connection and rejects revoked cached credentials', async () => {
- const credential = await token('alice');
- const noScope = await token('alice', { scope: 'offline_access' });
- for (const [method, params] of [
- ['tools/list', {}],
- ['tools/call', { name: 'kiln_discover', arguments: { query: 'wheel' } }],
- ]) {
- const options = {
- headers: { accept: 'application/json, text/event-stream' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
- };
- assert.equal((await mcp({ access_token: 'invalid' }, options)).status, 401);
- assert.equal((await mcp(noScope, options)).status, 403);
- const response = await mcp(credential, options);
- assert.equal(response.status, 200);
- assert.equal(response.headers.get('cache-control'), 'no-store');
- assert.ok(
- (await response.text()).includes(method === 'tools/list' ? '"tools":' : '"content":'),
- );
- }
- await database
- .prepare("UPDATE kiln_connections SET state='revoked' WHERE client_id=?")
- .bind(credential.clientId)
- .run();
- assert.equal(
- (
- await mcp(credential, {
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
- })
- ).status,
- 401,
- );
-});
-
-test('primary connection revocation denies cached access and refresh while preserving another connection', async () => {
- const first = await token('alice');
- const second = await token('alice');
- const own = await database
- .prepare('SELECT id FROM kiln_connections WHERE client_id=?')
- .bind(first.clientId)
- .first();
- assert.ok(own);
- // Leave every provider KV record intact: this models a remote cache seeing stale data.
- await database
- .prepare("UPDATE kiln_connections SET state='revoked' WHERE id=?")
- .bind(own.id)
- .run();
- assert.equal((await mcp(first)).status, 401);
- assert.equal((await mcp(second)).status, 200);
- const refresh = await runtime.dispatchFetch(`${origin}/oauth/token`, {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- grant_type: 'refresh_token',
- refresh_token: first.refresh_token,
- client_id: first.clientId,
- resource: `${origin}/mcp`,
- }),
- });
- assert.equal(refresh.status, 400);
- assert.equal((await refresh.json()).error, 'invalid_grant');
-});
-
-test('stale provider KV cannot exchange an already consumed authorization code again', async () => {
- const authorization = await grant();
- const kv = await runtime.getKVNamespace('OAUTH_KV');
- const saved = await Promise.all(
- (await kv.list({ prefix: 'grant:' })).keys.map(async ({ name }) => [name, await kv.get(name)]),
- );
- assert.equal((await exchange(authorization)).status, 200);
- for (const [name, value] of saved) await kv.put(name, value);
- const again = await exchange(authorization);
- assert.equal(again.status, 400);
- assert.equal((await again.json()).error, 'invalid_grant');
-});
-
-async function connectionFor(authorization) {
- return database
- .prepare('SELECT * FROM kiln_connections WHERE client_id=?')
- .bind(authorization.clientId)
- .first();
-}
-
-async function startDisconnect(authorization, connectionId, provider = 'github', extra = {}) {
- const page = await (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- })
- ).text();
- const csrf = page.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];
- assert.ok(csrf);
- return runtime.dispatchFetch(`${origin}/account/action`, {
- method: 'POST',
- redirect: 'manual',
- headers: {
- origin,
- cookie: authorization.browserCookie,
- 'content-type': 'application/x-www-form-urlencoded',
- ...extra.headers,
- },
- body: new URLSearchParams({
- csrf,
- action: 'disconnect',
- connectionId,
- provider,
- ...extra.form,
- }),
- });
-}
-
-async function actionCallback(start, authorization, user = 'alice') {
- assert.equal(start.status, 302);
- const upstream = new URL(start.headers.get('location'));
- assert.equal(upstream.searchParams.get('prompt'), 'select_account');
- const provider = upstream.origin === googleIssuer ? 'google' : 'github';
- const code = provider === 'github' ? user : randomBytes(24).toString('base64url');
- if (provider === 'google')
- googleCodes.set(code, {
- user,
- nonce: upstream.searchParams.get('nonce'),
- challenge: upstream.searchParams.get('code_challenge'),
- });
- return {
- callback: `${origin}/oauth/${provider}/callback?${new URLSearchParams({ state: upstream.searchParams.get('state'), code })}`,
- cookie: `${authorization.browserCookie}; ${cookies(start)}`,
- };
-}
-
-test('disconnect requires fresh verification of an existing provider and preserves other connections', async () => {
- for (const provider of ['github', 'google']) {
- const second = await token('alice', { provider });
- const authorization = await grant('alice', { provider });
- const credential = await (await exchange(authorization)).json();
- const connection = await connectionFor(authorization);
- const page = await (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- })
- ).text();
- assert.match(page, /Connected apps/);
- assert.ok(page.includes(connection.id));
- const start = await startDisconnect(authorization, connection.id, provider);
- const flow = await actionCallback(start, authorization);
- // Initiating confirmation alone must not revoke the connection.
- assert.equal((await mcp(credential)).status, 200);
- const response = await runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- });
- assert.equal(response.status, 303);
- assert.equal(response.headers.get('location'), '/account');
- assert.match(response.headers.get('set-cookie'), /__Host-kiln-session=/);
- assert.equal((await mcp(credential)).status, 401);
- assert.equal((await mcp(second)).status, 200);
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- })
- ).status,
- 401,
- );
- assert.equal(
- (await runtime.dispatchFetch(`${origin}/account`, { headers: { cookie: cookies(response) } }))
- .status,
- 200,
- );
- assert.equal(
- (
- await runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- })
- ).status,
- 400,
- );
- }
-});
-
-test('disconnect refuses another account, unlinked provider, forged CSRF and cross-origin actions', async () => {
- const bob = await grant('bob');
- await exchange(bob);
- const alice = await grant('alice');
- const credential = await (await exchange(alice)).json();
- const aliceConnection = await connectionFor(alice);
- const bobConnection = await connectionFor(bob);
- const count = outboundCalls;
- for (const [id, provider, extra] of [
- [bobConnection.id, 'github', {}],
- [aliceConnection.id, 'google', {}],
- [aliceConnection.id, 'github', { form: { csrf: '0'.repeat(64) } }],
- [aliceConnection.id, 'github', { headers: { origin: 'https://evil.example' } }],
- [aliceConnection.id, 'github', { form: { accountId: bobConnection.account_id } }],
- ])
- assert.equal((await startDisconnect(alice, id, provider, extra)).status, 403);
- assert.equal(outboundCalls, count);
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('disconnect rejects a different provider identity and a copied action without its session', async () => {
- const authorization = await grant();
- const credential = await (await exchange(authorization)).json();
- const connection = await connectionFor(authorization);
- const start = await startDisconnect(authorization, connection.id);
- const wrong = await actionCallback(start, authorization, 'bob');
- assert.equal(
- (
- await runtime.dispatchFetch(wrong.callback, {
- headers: { cookie: cookies(start) },
- redirect: 'manual',
- })
- ).status,
- 400,
- );
- assert.equal(
- (
- await runtime.dispatchFetch(wrong.callback, {
- headers: { cookie: wrong.cookie },
- redirect: 'manual',
- })
- ).status,
- 403,
- );
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('disconnect cancellation and expiry cannot revoke access or replay provider confirmation', async () => {
- const authorization = await grant();
- const credential = await (await exchange(authorization)).json();
- const connection = await connectionFor(authorization);
- const start = await startDisconnect(authorization, connection.id);
- const flow = await actionCallback(start, authorization);
- const cancelled = new URL(flow.callback);
- cancelled.searchParams.delete('code');
- cancelled.searchParams.set('error', 'access_denied');
- const beforeCalls = outboundCalls;
- const options = { headers: { cookie: flow.cookie }, redirect: 'manual' };
- assert.equal((await runtime.dispatchFetch(cancelled.href, options)).status, 400);
- assert.equal((await runtime.dispatchFetch(flow.callback, options)).status, 400);
- assert.equal(outboundCalls, beforeCalls);
- assert.equal((await mcp(credential)).status, 200);
- const next = await actionCallback(
- await startDisconnect(authorization, connection.id),
- authorization,
- );
- await database.prepare('UPDATE kiln_account_actions SET expires_at=0').run();
- assert.equal(
- (
- await runtime.dispatchFetch(next.callback, {
- headers: { cookie: next.cookie },
- redirect: 'manual',
- })
- ).status,
- 400,
- );
- assert.equal(outboundCalls, beforeCalls);
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('concurrent disconnect callbacks consume one confirmation and perform one provider exchange', async () => {
- const authorization = await grant();
- const credential = await (await exchange(authorization)).json();
- const connection = await connectionFor(authorization);
- const flow = await actionCallback(
- await startDisconnect(authorization, connection.id),
- authorization,
- );
- const beforeCalls = outboundCalls;
- const results = await Promise.all(
- [0, 1].map(() =>
- runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- }),
- ),
- );
- assert.deepEqual(results.map((result) => result.status).sort(), [303, 400]);
- assert.equal(outboundCalls - beforeCalls, 2); // One token exchange and one GitHub identity read.
- assert.equal((await mcp(credential)).status, 401);
-});
-
-test('a revoked browser session cannot finish its pending disconnect', async () => {
- const authorization = await grant();
- const credential = await (await exchange(authorization)).json();
- const connection = await connectionFor(authorization);
- const flow = await actionCallback(
- await startDisconnect(authorization, connection.id),
- authorization,
- );
- await database
- .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=?')
- .bind(connection.account_id)
- .run();
- const beforeCalls = outboundCalls;
- assert.equal(
- (
- await runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- })
- ).status,
- 400,
- );
- assert.equal(outboundCalls, beforeCalls);
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('connected app display escapes registered names and oversized action forms never contact a provider', async () => {
- const clientId = await register('<img src=x onerror="alert(1)">');
- const authorization = await grant('alice', { clientId });
- const credential = await (await exchange(authorization)).json();
- const page = await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- });
- const html = await page.text();
- assert.ok(!html.includes('<img src=x'));
- assert.ok(html.includes('&#60;img src=x'));
- assert.match(page.headers.get('content-security-policy'), /default-src 'none'/);
- const beforeCalls = outboundCalls;
- const rejected = await runtime.dispatchFetch(`${origin}/account/action`, {
- method: 'POST',
- headers: {
- origin,
- cookie: authorization.browserCookie,
- 'content-type': 'application/x-www-form-urlencoded',
- },
- body: `csrf=${'a'.repeat(4096)}`,
- });
- assert.equal(rejected.status, 413);
- assert.equal(outboundCalls, beforeCalls);
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('consent escapes client content and binds approval to its browser', async () => {
- const start = await consent({ clientId: await register('<script>bad()</script>') });
- assert.equal(start.response.status, 200);
- assert.ok(!start.page.includes('<script>bad()'));
- assert.match(start.page, /client\.example/);
- assert.match(start.response.headers.get('content-security-policy'), /frame-ancestors 'none'/);
- assert.match(start.response.headers.get('set-cookie'), /HttpOnly/);
- for (const link of ['/privacy', '/support', '/terms', '/account'])
- assert.ok(start.page.includes(`href="${link}"`));
- const nonce = start.page.match(/<style nonce="([a-f0-9]+)">/)?.[1];
- assert.ok(nonce);
- assert.ok(
- start.response.headers.get('content-security-policy').includes(`style-src 'nonce-${nonce}'`),
- );
- assert.match(start.page, /by Instrukt Labs/);
- const count = outboundCalls;
- assert.equal((await approve(start, { cookie: '' })).status, 400);
- assert.equal(outboundCalls, count);
-});
-
-test('cross-origin consent and a stolen upstream callback cannot reach GitHub', async () => {
- const start = await consent();
- const forged = await runtime.dispatchFetch(`${origin}/authorize`, {
- method: 'POST',
- headers: {
- origin: 'https://evil.example',
- cookie: start.cookie,
- 'content-type': 'application/x-www-form-urlencoded',
- },
- body: new URLSearchParams({ handle: start.handle, decision: 'approve' }),
- redirect: 'manual',
- });
- assert.equal(forged.status, 403);
- const approved = await approve(start);
- const state = new URL(approved.headers.get('location')).searchParams.get('state');
- const count = outboundCalls;
- const callback = await runtime.dispatchFetch(
- `${origin}/oauth/github/callback?${new URLSearchParams({ state, code: 'alice' })}`,
- { redirect: 'manual' },
- );
- assert.equal(callback.status, 400);
- assert.equal(outboundCalls, count);
-});
-
-test('denial returns validated state and issuer without a GitHub redirect', async () => {
- const start = await consent();
- const denied = await approve(start, { decision: 'deny' });
- assert.equal(denied.status, 302);
- const target = new URL(denied.headers.get('location'));
- assert.equal(target.origin, 'https://client.example');
- assert.equal(target.searchParams.get('error'), 'access_denied');
- assert.equal(target.searchParams.get('state'), 'client-state');
- assert.equal(target.searchParams.get('iss'), origin);
-});
-
-test('authorization rejects unknown scopes, missing audience and missing S256', async () => {
- for (const patch of [{ scope: 'admin' }, { resource: '' }, { code_challenge_method: 'plain' }]) {
- const result = await consent({ patch });
- assert.equal(result.response.status, 400);
- assert.equal(result.handle, undefined);
- }
-});
-
-test('authorization codes and upstream browser state cannot be replayed or retargeted', async () => {
- const authorization = await grant();
- assert.equal(
- (await exchange(authorization, { resource: 'https://other.example/mcp' })).status,
- 400,
- );
- assert.equal((await exchange(authorization)).status, 200);
- assert.equal((await exchange(authorization)).status, 400);
- const replay = await runtime.dispatchFetch(authorization.callback, {
- headers: { cookie: authorization.upstreamCookie },
- redirect: 'manual',
- });
- assert.equal(replay.status, 400);
-});
-
-test('wrong PKCE verifier cannot exchange a valid authorization code', async () => {
- const authorization = await grant();
- const response = await exchange(authorization, {
- code_verifier: randomBytes(32).toString('base64url'),
- });
- assert.equal(response.status, 400);
- assert.equal((await response.json()).access_token, undefined);
-});
-
-test('same user reconnects to one tenant; another user and forged headers cannot select it', async () => {
- const alice = await token('alice');
- const aliceAgain = await token('alice');
- const bob = await token('bob');
- const first = await (await mcp(alice)).json();
- const reconnected = await (await mcp(aliceAgain)).json();
- const other = await (
- await mcp(bob, {
- headers: {
- 'x-kiln-tenant': first.tenant,
- 'x-user-id': 'github:1001',
- cookie: 'session=forged',
- 'cf-access-jwt-assertion': 'forged',
- 'mcp-session-id': 'session-alice',
- 'mcp-protocol-version': '2026-07-28',
- 'mcp-method': 'tools/call',
- 'mcp-name': 'kiln_validate',
- },
- })
- ).json();
- assert.equal(first.tenant, reconnected.tenant);
- assert.notEqual(first.tenant, other.tenant);
- for (const header of [
- 'authorization',
- 'cookie',
- 'x-kiln-tenant',
- 'x-user-id',
- 'cf-access-jwt-assertion',
- ]) {
- assert.equal(other.headers[header], undefined);
- }
- assert.equal(other.headers['mcp-protocol-version'], '2026-07-28');
- assert.equal(other.headers['mcp-method'], 'tools/call');
- assert.equal(other.headers['mcp-name'], 'kiln_validate');
- assert.equal(other.headers['mcp-session-id'], 'session-alice'); // Session IDs never route a tenant.
-});
-
-test('both sign-in choices resolve permanent Kiln accounts, with no cross-provider auto-link', async () => {
- const page = (await consent()).page;
- assert.match(page, /Continue with Google/);
- assert.match(page, /Continue with GitHub/);
- const first = await token('alice', { provider: 'google' });
- const again = await token('alice', { provider: 'google' });
- const github = await token('alice');
- const googleTenant = (await (await mcp(first)).json()).tenant;
- assert.equal((await (await mcp(again)).json()).tenant, googleTenant);
- assert.notEqual((await (await mcp(github)).json()).tenant, googleTenant);
- const rows = await database
- .prepare('SELECT issuer, account_id FROM kiln_identities WHERE subject=?')
- .bind('1001')
- .all();
- assert.equal(rows.results.length, 2);
- for (const row of rows.results) assert.match(row.account_id, /^ka_[a-f0-9]{32}$/);
-});
-
-const refreshToken = (credential) =>
- runtime.dispatchFetch(`${origin}/oauth/token`, {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- grant_type: 'refresh_token',
- refresh_token: credential.refresh_token,
- client_id: credential.clientId,
- resource: `${origin}/mcp`,
- }),
- });
-
-test('current account state and epoch gate tools, downloads, code exchange and refresh', async () => {
- for (const mutation of ['disable', 'delete', 'epoch']) {
- const credential = await token('bob');
- const pendingCode = await grant('bob');
- const identity = await database
- .prepare('SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=?')
- .bind('https://github.com', '1002')
- .first();
- const state =
- mutation === 'disable' ? 'disabled' : mutation === 'delete' ? 'deleting' : 'active';
- await database
- .prepare(
- 'UPDATE kiln_accounts SET state=?, authorization_epoch=authorization_epoch+? WHERE id=?',
- )
- .bind(state, mutation === 'epoch' ? 1 : 0, identity.account_id)
- .run();
- assert.equal((await mcp(credential)).status, 401);
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/mcp/artifacts/${'a'.repeat(32)}`, {
- headers: { authorization: `Bearer ${credential.access_token}` },
- })
- ).status,
- 401,
- );
- assert.equal((await exchange(pendingCode)).status, 400);
- const refused = await refreshToken(credential);
- assert.equal(refused.status, 400);
- assert.equal((await refused.json()).error, 'invalid_grant');
- await database
- .prepare(
- 'UPDATE kiln_accounts SET state=?, authorization_epoch=authorization_epoch+1 WHERE id=?',
- )
- .bind('active', identity.account_id)
- .run();
- // Re-enabling never revives old credentials; an explicit new login is required.
- assert.equal((await mcp(credential)).status, 401);
- assert.equal((await mcp(await token('bob'))).status, 200);
- }
-});
-
-test('an unavailable account authority fails closed for access and refresh', async () => {
- const credential = await token('alice');
- await database.prepare('ALTER TABLE kiln_accounts RENAME TO fixture_unavailable_accounts').run();
- try {
- const access = await mcp(credential);
- assert.equal(access.status, 503);
- assert.ok(!(await access.text()).includes('kiln_accounts'));
- assert.equal((await refreshToken(credential)).status, 503);
- } finally {
- await database
- .prepare('ALTER TABLE fixture_unavailable_accounts RENAME TO kiln_accounts')
- .run();
- }
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('a provider callback cannot be swapped onto the other provider route', async () => {
- for (const provider of ['github', 'google']) {
- const start = await consent();
- const approved = await approve(start, { decision: provider });
- assert.equal(approved.status, 302);
- const state = new URL(approved.headers.get('location')).searchParams.get('state');
- const count = outboundCalls;
- const other = provider === 'google' ? 'github' : 'google';
- const response = await runtime.dispatchFetch(
- `${origin}/oauth/${other}/callback?${new URLSearchParams({ state, code: 'alice' })}`,
- { headers: { cookie: cookies(approved) }, redirect: 'manual' },
- );
- assert.equal(response.status, 400);
- assert.equal(outboundCalls, count);
- }
-});
-
-test('stale upstream KV cannot replay consent or a completed sign-in', async () => {
- const kv = await runtime.getKVNamespace('OAUTH_KV');
- const snapshot = async () => {
- const { keys } = await kv.list();
- return Promise.all(keys.map(async ({ name }) => [name, await kv.get(name)]));
- };
- const restore = async (records) => {
- for (const [name, value] of records) if (value !== null) await kv.put(name, value);
- };
- const start = await consent();
- const beforeConsent = await snapshot();
- const approved = await approve(start);
- assert.equal(approved.status, 302);
- await restore(beforeConsent);
- const count = outboundCalls;
- assert.equal((await approve(start)).status, 400);
- assert.equal(outboundCalls, count);
- const beforeCallback = await snapshot();
- const state = new URL(approved.headers.get('location')).searchParams.get('state');
- const callback = () =>
- runtime.dispatchFetch(
- `${origin}/oauth/github/callback?${new URLSearchParams({ state, code: 'alice' })}`,
- { headers: { cookie: cookies(approved) }, redirect: 'manual' },
- );
- assert.equal((await callback()).status, 302);
- await restore(beforeCallback);
- const afterFirst = outboundCalls;
- assert.equal((await callback()).status, 400);
- assert.equal(outboundCalls, afterFirst);
-});
-
-test('MCP refuses a foreign browser Origin even with a valid token', async () => {
- const credential = await token('alice');
- assert.equal(
- (await mcp(credential, { headers: { origin: 'https://foreign.example' } })).status,
- 403,
- );
- assert.equal((await mcp(credential, { headers: { origin } })).status, 200);
- assert.equal((await mcp(credential, { headers: { 'mcp-name': 'x'.repeat(4097) } })).status, 431);
-});
-
-test('a token without the tool scope cannot reach a tenant', async () => {
- const credential = await token('alice', { scope: 'offline_access' });
- const response = await mcp(credential);
- assert.equal(response.status, 403);
- assert.match(response.headers.get('www-authenticate'), /insufficient_scope/);
-});
-
-test('a client metadata document can authorize without dynamic registration', async () => {
- const clientId = 'https://client.example/metadata.json';
- const start = await consent({ clientId });
- assert.equal(start.response.status, 200);
- assert.match(start.page, /Client domain: <strong>client\.example<\/strong>/);
- const credential = await token('alice', { clientId });
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('CIMD negotiates the supported public method from current OpenAI-style choices and still requires PKCE', async () => {
- // Public metadata observed 2026-10-06: a plural offer plus a legacy signed-method
- // preference. Fixed local metadata proves negotiation, not a live OpenAI login.
- const clientId = 'https://client.example/choices.json';
- const credential = await token('alice', { clientId });
- assert.equal((await mcp(credential)).status, 200);
- const authorization = await grant('alice', { clientId });
- const missingVerifier = await exchange(authorization, { code_verifier: '' });
- assert.equal(missingVerifier.status, 400);
- assert.equal((await missingVerifier.json()).access_token, undefined);
-});
-
-test('CIMD cannot silently downgrade a client that requires signed assertions only', async () => {
- const start = await consent({ clientId: 'https://client.example/signed-only.json' });
- assert.ok([400, 503].includes(start.response.status));
- assert.equal(start.response.headers.get('location'), null);
- assert.ok(!start.page.includes('Continue with GitHub'));
-});
-
-test('refresh stays bound to its resource and revocation denies subsequent requests', async () => {
- const credential = await token('alice');
- const refresh = (resource) =>
- runtime.dispatchFetch(`${origin}/oauth/token`, {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- grant_type: 'refresh_token',
- refresh_token: credential.refresh_token,
- client_id: credential.clientId,
- resource,
- }),
- });
- assert.equal((await refresh('https://other.example/mcp')).status, 400);
- const renewed = await refresh(`${origin}/mcp`);
- assert.equal(renewed.status, 200);
- const refreshed = await renewed.json();
- assert.equal((await mcp(refreshed)).status, 200);
- const metadata = await (
- await runtime.dispatchFetch(`${origin}/.well-known/oauth-authorization-server`)
- ).json();
- const revoke = await runtime.dispatchFetch(metadata.revocation_endpoint, {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- token: refreshed.access_token,
- token_type_hint: 'access_token',
- client_id: credential.clientId,
- }),
- });
- assert.equal(revoke.status, 200);
- assert.equal((await mcp(refreshed)).status, 401);
-});
-
-test('gateway rejects wrong origins, credential queries, unsupported paths and oversized bodies', async () => {
- assert.equal((await runtime.dispatchFetch('https://evil.example/mcp')).status, 421);
- assert.equal((await runtime.dispatchFetch(`${origin}/mcp?access_token=forged`)).status, 400);
- const credential = await token('alice');
- assert.equal((await mcp(credential, { body: 'a'.repeat(1024 * 1024 + 1) })).status, 413);
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/mcp/unknown`, {
- headers: { authorization: `Bearer ${credential.access_token}` },
- })
- ).status,
- 404,
- );
-});
-
-test('upstream tokens and MCP bearer values are absent from persisted OAuth records', async () => {
- const credential = await token('alice');
- const kv = await runtime.getKVNamespace('OAUTH_KV');
- const { keys } = await kv.list();
- for (const { name } of keys) {
- const record = await kv.get(name);
- for (const secret of [
- credential.access_token,
- credential.refresh_token,
- 'fixture-alice',
- 'fixture-secret-not-a-real-credential',
- ]) {
- assert.ok(
- !name.includes(secret) && !record?.includes(secret),
- 'OAuth record exposes a raw credential',
- );
- }
- }
-});
-
-test('a chunked MCP body is bounded without relying on Content-Length', async () => {
- const credential = await token('alice');
- const body = new ReadableStream({
- start(controller) {
- controller.enqueue(new Uint8Array(600_000));
- controller.enqueue(new Uint8Array(600_000));
- controller.close();
- },
- });
- const response = await mcp(credential, { body, duplex: 'half' });
- assert.equal(response.status, 413);
-});
-
-test('real OAuth gateway authorizes downloads and completes deletion through private tenant storage', async () => {
- const [gateway, storage] = await Promise.all(
- ['worker', 'tenant-worker'].map((entry) =>
- build({
- entryPoints: [
- fileURLToPath(
- new URL(
- entry === 'worker' ? './deletion-integration-worker.ts' : `../src/${entry}.ts`,
- import.meta.url,
- ),
- ),
- ],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- }),
- ),
- );
- const server = new Miniflare(
- convertV4MiniflareOptions({
- workers: [
- {
- name: 'gateway',
- modules: true,
- script: gateway.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['global_fetch_strictly_public'],
- kvNamespaces: ['OAUTH_KV'],
- ratelimits: rateLimitBindings,
- d1Databases: ['ACCOUNTS'],
- serviceBindings: { NATIVE_COMPUTE: { name: 'gateway', entrypoint: 'EmptyCompute' } },
- durableObjects: {
- TENANTS: { className: 'KilnTenant', scriptName: 'tenant', useSQLite: true },
- },
- bindings: {
- PUBLIC_ORIGIN: origin,
- GITHUB_CLIENT_ID: 'fixture-client',
- GITHUB_CLIENT_SECRET: 'fixture-only-secret',
- GOOGLE_CLIENT_ID: 'fixture-google-client',
- GOOGLE_CLIENT_SECRET: 'fixture-google-secret',
- },
- outboundService: async (request) => {
- if (request.url === 'https://github.com/login/oauth/access_token') {
- const form = new URLSearchParams(await request.text());
- return Response.json({
- access_token: `fixture-${form.get('code')}`,
- token_type: 'bearer',
- });
- }
- if (request.url === 'https://api.github.com/user') {
- const credential = request.headers.get('authorization');
- assert.match(credential, /^Bearer fixture-(alice|bob)$/);
- return Response.json({ id: credential.endsWith('alice') ? 1001 : 1002 });
- }
- throw new Error('Unexpected network access');
- },
- },
- {
- name: 'tenant',
- modules: true,
- script: storage.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- r2Buckets: ['ARTIFACTS'],
- durableObjects: { TENANTS: { className: 'KilnTenant', useSQLite: true } },
- bindings: {
- STORAGE_MAX_BYTES: '1048576',
- STORAGE_MAX_OBJECTS: '32',
- STORAGE_MAX_GROUPS: '8',
- },
- outboundService: async () => {
- throw new Error('Tenant has no external network role');
- },
- },
- ],
- }),
- );
- try {
- const accounts = await server.getD1Database('ACCOUNTS', 'gateway');
- await migrateAccounts(accounts);
- const alice = await token('alice', { server });
- const bob = await token('bob', { server });
- const reconnected = await token('alice', { server });
- const namespace = await server.getDurableObjectNamespace('TENANTS', 'tenant');
- const identity = await accounts
- .prepare('SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=?')
- .bind('https://github.com', '1001')
- .first();
- const name = digest(JSON.stringify(['kiln-tenant-v1', origin, identity.account_id]));
- const tenant = namespace.get(namespace.idFromName(name));
- // Seed bytes through the same private binding used by the future native host.
- const bytes = Buffer.from('private retained source');
- const uploaded = await tenant.fetch('https://tenant.internal/internal/artifacts', {
- method: 'POST',
- body: bytes,
- headers: {
- 'content-type': 'application/javascript',
- 'content-length': String(bytes.length),
- 'x-artifact-name': 'source.kiln.js',
- 'x-artifact-sha256': createHash('sha256').update(bytes).digest('hex'),
- },
- });
- assert.equal(uploaded.status, 201);
- const artifact = await uploaded.json();
- const url = `${origin}/mcp/artifacts/${artifact.id}`;
- assert.equal((await server.dispatchFetch(url)).status, 401);
- for (const credential of [alice, reconnected]) {
- const result = await server.dispatchFetch(url, {
- headers: { authorization: `Bearer ${credential.access_token}` },
- });
- assert.equal(result.status, 200);
- assert.deepEqual(Buffer.from(await result.arrayBuffer()), bytes);
- assert.equal(result.headers.get('cache-control'), 'no-store');
- }
- const denied = await server.dispatchFetch(url, {
- headers: {
- authorization: `Bearer ${bob.access_token}`,
- 'x-tenant-id': name,
- 'mcp-session-id': name,
- cookie: `tenant=${name}`,
- },
- });
- assert.equal(denied.status, 404);
- const headers = { authorization: `Bearer ${alice.access_token}` };
- assert.equal(
- (
- await server.dispatchFetch(`${origin}/internal/artifacts`, {
- method: 'POST',
- body: bytes,
- headers,
- })
- ).status,
- 404,
- );
- assert.equal(
- (
- await server.dispatchFetch(`${origin}/mcp/internal/artifacts`, {
- method: 'POST',
- body: '{}',
- headers,
- })
- ).status,
- 404,
- );
- assert.equal((await server.dispatchFetch(`${origin}/mcp`, { headers })).status, 405);
- assert.equal(
- (
- await server.dispatchFetch(`${origin}/mcp`, {
- method: 'POST',
- headers: { ...headers, 'content-type': 'application/json' },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method: 'tools/call',
- params: { name: 'kiln_validate', arguments: { code: 'function build(){}' } },
- }),
- })
- ).status,
- 503,
- );
- const privateWorker = await server.getWorker('tenant');
- assert.equal(
- (
- await privateWorker.fetch('https://tenant.internal/internal/artifacts', {
- method: 'POST',
- body: bytes,
- })
- ).status,
- 404,
- );
- // Pin the source as a saved revision so deletion must remove retained work.
- assert.equal(
- (
- await tenant.fetch('https://tenant.internal/internal/groups', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- key: 'library/saved/revision',
- files: { 'source.kiln.js': artifact.id },
- metadata: { title: 'Private saved work' },
- }),
- })
- ).status,
- 201,
- );
- const authorization = await grant('alice', { server });
- const flow = await actionCallback(await startDeletion(authorization), authorization, 'alice');
- const confirmed = await server.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- });
- assert.equal(confirmed.status, 303);
- const receiptCookie = cookies(confirmed);
- for (let i = 0; i < 12; i++) {
- const progress = await accounts.prepare('SELECT phase FROM kiln_deletions').first();
- if (progress?.phase === 'complete') break;
- // Advance retry eligibility only, never steal the live recovery lease.
- await accounts.prepare('UPDATE kiln_deletions SET retry_at=0').run();
- assert.equal((await server.dispatchFetch(`${origin}/fixture/recover`)).status, 200);
- }
- const receipt = await server.dispatchFetch(`${origin}/account/deletion`, {
- headers: { cookie: receiptCookie },
- });
- assert.match(await receipt.text(), /Account deleted/);
- assert.equal(
- await accounts
- .prepare('SELECT 1 FROM kiln_accounts WHERE id=?')
- .bind(identity.account_id)
- .first(),
- null,
- );
- assert.equal(
- (await accounts.prepare('SELECT tenant FROM fixture_retired').first()).tenant,
- name,
- );
- assert.equal((await tenant.fetch('https://tenant.internal/internal/usage')).status, 410);
- const bucket = await server.getR2Bucket('ARTIFACTS', 'tenant');
- assert.equal(
- (await bucket.list({ prefix: `tenants/${namespace.idFromName(name)}/` })).objects.length,
- 0,
- );
- for (const credential of [alice, reconnected])
- assert.equal(
- (
- await server.dispatchFetch(url, {
- headers: { authorization: `Bearer ${credential.access_token}` },
- })
- ).status,
- 401,
- );
- assert.equal(
- (
- await server.dispatchFetch(url, {
- headers: { authorization: `Bearer ${bob.access_token}` },
- })
- ).status,
- 404,
- );
- const fresh = await grant('alice', { server });
- const freshIdentity = await accounts
- .prepare('SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=?')
- .bind('https://github.com', '1001')
- .first();
- assert.notEqual(freshIdentity.account_id, identity.account_id);
- assert.equal(
- (
- await server.dispatchFetch(`${origin}/account`, {
- headers: { cookie: fresh.browserCookie },
- })
- ).status,
- 200,
- );
- } finally {
- await server.dispose();
- }
-});
-
-async function startDeletion(authorization, provider = 'github', extra = {}) {
- const server = authorization.server ?? runtime;
- const page = await (
- await server.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- })
- ).text();
- const csrf = page.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];
- assert.ok(csrf);
- return server.dispatchFetch(`${origin}/account/delete`, {
- method: 'POST',
- redirect: 'manual',
- headers: {
- origin,
- cookie: authorization.browserCookie,
- 'content-type': 'application/x-www-form-urlencoded',
- ...extra.headers,
- },
- body: new URLSearchParams({ csrf, provider, confirmation: 'delete-my-account', ...extra.form }),
- });
-}
-
-test('account deletion confirms either linked provider then revokes browsers and MCP before background cleanup', async () => {
- for (const provider of ['github', 'google']) {
- const user = `delete-${provider}`,
- authorization = await grant(user, { provider });
- const credential = await (await exchange(authorization)).json();
- const account = (await connectionFor(authorization)).account_id;
- const start = await startDeletion(authorization, provider);
- const flow = await actionCallback(start, authorization, user);
- assert.match(new URL(flow.callback).searchParams.get('state'), /^kd1_/);
- assert.equal((await mcp(credential)).status, 200);
- const response = await finishIdentity(flow);
- assert.equal(response.status, 303);
- assert.equal(response.headers.get('location'), '/account/deletion');
- assert.match(cookies(response), /__Host-kiln-deletion-receipt=[a-f0-9]{64}/);
- assert.equal((await mcp(credential)).status, 401);
- assert.equal(
- (await refreshToken({ ...credential, clientId: authorization.clientId })).status,
- 400,
- );
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- })
- ).status,
- 401,
- );
- const current = await database
- .prepare('SELECT state,authorization_epoch FROM kiln_accounts WHERE id=?')
- .bind(account)
- .first();
- assert.equal(current.state, 'deleting');
- assert.equal(current.authorization_epoch, 2);
- const receipt = await runtime.dispatchFetch(`${origin}/account/deletion`, {
- headers: { cookie: cookies(response) },
- });
- assert.equal(receipt.status, 200);
- assert.match(await receipt.text(), /Deletion in progress/);
- assert.equal((await runtime.dispatchFetch(`${origin}/account/deletion`)).status, 404);
- assert.equal((await finishIdentity(flow)).status, 400);
- }
-});
-
-test('deletion forms and wrong upstream identities cannot select or destroy another account', async () => {
- const user = 'delete-invalid',
- authorization = await grant(user);
- const credential = await (await exchange(authorization)).json();
- for (const extra of [
- { form: { csrf: '0'.repeat(64) } },
- { form: { confirmation: 'no' } },
- { form: { accountId: 'victim' } },
- { headers: { origin: 'https://foreign.example' } },
- ])
- assert.equal((await startDeletion(authorization, 'github', extra)).status, 403);
- assert.equal((await startDeletion(authorization, 'google')).status, 403);
- const flow = await actionCallback(
- await startDeletion(authorization),
- authorization,
- 'foreign-person',
- );
- assert.equal((await finishIdentity(flow)).status, 403);
- assert.equal((await finishIdentity(flow)).status, 400);
- assert.equal((await mcp(credential)).status, 200);
-});
-
-test('deletion confirmations reject cancellation, expiry, copied cookies and cross-provider replay', async () => {
- for (const mode of ['cancel', 'expired', 'cookie', 'provider']) {
- const user = `deletion-${mode}`,
- authorization = await grant(user);
- const credential = await (await exchange(authorization)).json();
- const flow = await actionCallback(await startDeletion(authorization), authorization, user);
- const count = outboundCalls;
- if (mode === 'cancel') flow.callback += '&error=access_denied';
- if (mode === 'expired')
- await database.prepare('UPDATE kiln_deletion_actions SET expires_at=0').run();
- if (mode === 'cookie') flow.cookie = authorization.browserCookie;
- if (mode === 'provider') flow.callback = flow.callback.replace('/github/', '/google/');
- assert.equal((await finishIdentity(flow)).status, 400);
- assert.equal(outboundCalls, count);
- assert.equal((await mcp(credential)).status, 200);
- }
-});
-
-test('deletion rechecks session, epoch and confirmed identity after upstream I/O', async () => {
- for (const mode of ['session', 'epoch', 'identity']) {
- const user = `deletion-inflight-${mode}`,
- authorization = await grant(user);
- const account = (await connectionFor(authorization)).account_id;
- const flow = await actionCallback(await startDeletion(authorization), authorization, user);
- beforeProviderReply = async () => {
- beforeProviderReply = undefined;
- const query =
- mode === 'session'
- ? 'DELETE FROM kiln_browser_sessions WHERE account_id=?'
- : mode === 'epoch'
- ? 'UPDATE kiln_accounts SET authorization_epoch=authorization_epoch+1 WHERE id=?'
- : 'DELETE FROM kiln_identities WHERE account_id=?';
- await database.prepare(query).bind(account).run();
- };
- try {
- assert.equal((await finishIdentity(flow)).status, 403);
- } finally {
- beforeProviderReply = undefined;
- }
- assert.equal(
- await database
- .prepare('SELECT 1 FROM kiln_deletions WHERE account_id=?')
- .bind(account)
- .first(),
- null,
- );
- assert.equal(
- (await database.prepare('SELECT state FROM kiln_accounts WHERE id=?').bind(account).first())
- .state,
- 'active',
- );
- }
-});
-
-test('deletion callback races enqueue one job and a failed enqueue leaves account access unchanged', async () => {
- const authorization = await grant('deletion-race');
- const account = (await connectionFor(authorization)).account_id;
- const flow = await actionCallback(
- await startDeletion(authorization),
- authorization,
- 'deletion-race',
- );
- const results = await Promise.all([finishIdentity(flow), finishIdentity(flow)]);
- assert.deepEqual(results.map((value) => value.status).sort(), [303, 400]);
- assert.equal(
- (
- await database
- .prepare('SELECT COUNT(*) AS n FROM kiln_deletions WHERE account_id=?')
- .bind(account)
- .first()
- ).n,
- 1,
- );
-
- const other = await grant('deletion-enqueue-failure');
- const credential = await (await exchange(other)).json();
- const confirmation = await actionCallback(
- await startDeletion(other),
- other,
- 'deletion-enqueue-failure',
- );
- await database.exec(
- "CREATE TRIGGER deletion_failure BEFORE INSERT ON kiln_deletions BEGIN SELECT RAISE(ABORT,'fixture'); END",
- );
- try {
- assert.equal((await finishIdentity(confirmation)).status, 503);
- } finally {
- await database.exec('DROP TRIGGER deletion_failure');
- }
- assert.equal((await mcp(credential)).status, 200);
- assert.equal((await finishIdentity(confirmation)).status, 400);
-});
-
-test('deletion intents are bounded and hashed, and receipt reads reject caller-selected targets', async () => {
- const authorization = await grant('deletion-bounds');
- const account = (await connectionFor(authorization)).account_id;
- for (let i = 0; i < 4; i++) {
- const response = await startDeletion(authorization);
- assert.equal(response.status, 302);
- const state = new URL(response.headers.get('location')).searchParams.get('state');
- const binding = cookies(response).split('=')[1];
- const stored = JSON.stringify(
- (
- await database
- .prepare('SELECT * FROM kiln_deletion_actions WHERE account_id=?')
- .bind(account)
- .all()
- ).results,
- );
- assert(!stored.includes(state));
- assert(!stored.includes(binding));
- }
- const count = outboundCalls;
- assert.equal((await startDeletion(authorization)).status, 403);
- for (const body of [
- 'x'.repeat(4097),
- 'csrf=bad&provider=github&confirmation=delete-my-account&confirmation=delete-my-account',
- ]) {
- const result = await runtime.dispatchFetch(`${origin}/account/delete`, {
- method: 'POST',
- headers: {
- origin,
- cookie: authorization.browserCookie,
- 'content-type': 'application/x-www-form-urlencoded',
- },
- body,
- });
- assert.equal(result.status, body.length > 4096 ? 413 : 403);
- }
- assert.equal(outboundCalls, count);
- assert.equal(
- (await runtime.dispatchFetch(`${origin}/account/deletion?accountId=${account}`)).status,
- 400,
- );
- assert.equal(
- (await runtime.dispatchFetch(`${origin}/account/deletion`, { method: 'POST' })).status,
- 405,
- );
- assert.equal((await runtime.dispatchFetch(`${origin}/account/delete`)).status, 405);
-});
-
-async function startIdentity(authorization, action, target, provider, extra = {}) {
- const page = await (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- })
- ).text();
- const csrf = page.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];
- assert.ok(csrf);
- return runtime.dispatchFetch(`${origin}/account/identity`, {
- method: 'POST',
- redirect: 'manual',
- headers: {
- origin,
- cookie: authorization.browserCookie,
- 'content-type': 'application/x-www-form-urlencoded',
- ...extra.headers,
- },
- body: new URLSearchParams({ csrf, action, target, provider, ...extra.form }),
- });
-}
-const finishIdentity = (flow) =>
- runtime.dispatchFetch(flow.callback, {
- headers: { cookie: flow.cookie },
- redirect: 'manual',
- });
-async function linkIdentity(authorization, user, provider = 'github', target = 'google') {
- const first = await actionCallback(
- await startIdentity(authorization, 'link', target, provider),
- authorization,
- user,
- );
- const next = await finishIdentity(first);
- const second = await actionCallback(next, authorization, user);
- return { first, second, response: await finishIdentity(second) };
-}
-
-test('explicit linking preserves the account and invalidates old browser and MCP access', async () => {
- for (const provider of ['github', 'google']) {
- const user = `link-${provider}`,
- target = provider === 'github' ? 'google' : 'github';
- const authorization = await grant(user, { provider });
- const credential = await (await exchange(authorization)).json();
- const account = (await connectionFor(authorization)).account_id;
- const linked = await linkIdentity(authorization, user, provider, target);
- assert.equal(linked.response.status, 200);
- assert.match(await linked.response.text(), /Sign-in method added/);
- assert.match(linked.response.headers.get('set-cookie'), /Max-Age=0/);
- assert.equal((await mcp(credential)).status, 401);
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- })
- ).status,
- 401,
- );
- assert.equal((await finishIdentity(linked.second)).status, 400);
- const returning = await grant(user, { provider: target });
- assert.equal((await connectionFor(returning)).account_id, account);
- const html = await (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: returning.browserCookie },
- })
- ).text();
- assert.match(html, /Recent security activity/);
- assert.match(html, /Sign-in method added/);
- assert.match(html, /Remove Google|Remove GitHub/);
- }
-});
-
-test('identity linking requires both identities, same-session proof and an unused target', async () => {
- const authorization = await grant('link-denials');
- const credential = await (await exchange(authorization)).json();
- const before = outboundCalls;
- for (const extra of [
- { form: { csrf: '0'.repeat(64) } },
- { headers: { origin: 'https://evil.example' } },
- { form: { accountId: `ka_${'0'.repeat(32)}` } },
- ])
- assert.equal(
- (await startIdentity(authorization, 'link', 'google', 'github', extra)).status,
- 403,
- );
- assert.equal(outboundCalls, before);
- const wrong = await actionCallback(
- await startIdentity(authorization, 'link', 'google', 'github'),
- authorization,
- 'bob',
- );
- assert.equal((await finishIdentity(wrong)).status, 403);
- const first = await actionCallback(
- await startIdentity(authorization, 'link', 'google', 'github'),
- authorization,
- 'link-denials',
- );
- const next = await finishIdentity(first);
- assert.equal(next.status, 302);
- // A Google identity already owned by another Kiln account must not merge libraries.
- const other = await grant('link-other', { provider: 'google' });
- const second = await actionCallback(next, authorization, 'link-other');
- const calls = outboundCalls;
- assert.equal(
- (
- await runtime.dispatchFetch(second.callback, {
- headers: { cookie: cookies(next) },
- redirect: 'manual',
- })
- ).status,
- 400,
- );
- assert.equal(outboundCalls, calls);
- assert.equal((await finishIdentity(second)).status, 403);
- assert.equal((await mcp(credential)).status, 200);
- assert.notEqual(
- (await connectionFor(other)).account_id,
- (await connectionFor(authorization)).account_id,
- );
-});
-
-test('unlink confirms the retained method, never removes the last login and revokes prior access', async () => {
- const user = 'unlink-user';
- const first = await grant(user);
- assert.equal((await startIdentity(first, 'unlink', 'github', 'github')).status, 403);
- assert.equal((await linkIdentity(first, user)).response.status, 200);
- const authorization = await grant(user, { provider: 'google' });
- const credential = await (await exchange(authorization)).json();
- const account = (await connectionFor(authorization)).account_id;
- assert.equal((await startIdentity(authorization, 'unlink', 'github', 'github')).status, 403);
- const flow = await actionCallback(
- await startIdentity(authorization, 'unlink', 'github', 'google'),
- authorization,
- user,
- );
- const response = await finishIdentity(flow);
- assert.equal(response.status, 200);
- assert.match(await response.text(), /Sign-in method removed/);
- assert.equal((await mcp(credential)).status, 401);
- const retained = await grant(user, { provider: 'google' });
- assert.equal((await connectionFor(retained)).account_id, account);
- const removed = await grant(user);
- assert.notEqual((await connectionFor(removed)).account_id, account);
- assert.equal((await startIdentity(retained, 'unlink', 'google', 'github')).status, 403);
-});
-
-test('link callbacks are one-use across races and cannot cross provider or phase', async () => {
- const user = 'link-races',
- authorization = await grant(user);
- const first = await actionCallback(
- await startIdentity(authorization, 'link', 'google', 'github'),
- authorization,
- user,
- );
- const before = outboundCalls;
- const responses = await Promise.all([finishIdentity(first), finishIdentity(first)]);
- assert.deepEqual(responses.map((r) => r.status).sort(), [302, 400]);
- // One GitHub exchange and identity read, plus discovery for the second phase.
- assert.equal(outboundCalls - before, 3);
- const next = responses.find((r) => r.status === 302);
- const second = await actionCallback(next, authorization, user);
- const wrongProvider = second.callback.replace('/oauth/google/', '/oauth/github/');
- const count = outboundCalls;
- assert.equal((await finishIdentity({ ...second, callback: wrongProvider })).status, 400);
- assert.equal(outboundCalls, count);
- const done = await Promise.all([finishIdentity(second), finishIdentity(second)]);
- assert.deepEqual(done.map((r) => r.status).sort(), [200, 400]);
- const account = (await connectionFor(authorization)).account_id;
- const row = await database
- .prepare('SELECT COUNT(*) AS n FROM kiln_account_events WHERE account_id=?')
- .bind(account)
- .first();
- assert.equal(row.n, 1);
-});
-
-test('cancelled, expired and revoked link confirmations cannot change sign-in methods', async () => {
- for (const mode of ['cancel', 'expiry', 'epoch', 'session']) {
- const user = `link-state-${mode}`,
- authorization = await grant(user);
- const account = (await connectionFor(authorization)).account_id;
- const first = await actionCallback(
- await startIdentity(authorization, 'link', 'google', 'github'),
- authorization,
- user,
- );
- const next = await finishIdentity(first);
- const second = await actionCallback(next, authorization, user);
- const before = outboundCalls;
- if (mode === 'cancel') {
- const url = new URL(second.callback);
- url.searchParams.delete('code');
- url.searchParams.set('error', 'access_denied');
- assert.equal((await finishIdentity({ ...second, callback: url.href })).status, 400);
- } else if (mode === 'expiry')
- await database
- .prepare('UPDATE kiln_identity_actions SET expires_at=0 WHERE account_id=?')
- .bind(account)
- .run();
- else if (mode === 'epoch')
- await database
- .prepare('UPDATE kiln_accounts SET authorization_epoch=2 WHERE id=?')
- .bind(account)
- .run();
- else
- await database
- .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=?')
- .bind(account)
- .run();
- assert.equal((await finishIdentity(second)).status, 400);
- assert.equal(outboundCalls, before);
- assert.equal(
- (
- await database
- .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE account_id=?')
- .bind(account)
- .first()
- ).n,
- 1,
- );
- }
-});
-
-test('failed security-event writes roll back identity changes, epochs and sessions', async () => {
- const user = 'link-rollback',
- authorization = await grant(user);
- const credential = await (await exchange(authorization)).json();
- const account = (await connectionFor(authorization)).account_id;
- await database
- .prepare(`CREATE TRIGGER reject_security_event BEFORE INSERT ON kiln_account_events
- BEGIN SELECT RAISE(ABORT, 'fixture rejection'); END`)
- .run();
- try {
- const linked = await linkIdentity(authorization, user);
- assert.equal(linked.response.status, 503);
- assert.equal(
- (
- await database
- .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE account_id=?')
- .bind(account)
- .first()
- ).n,
- 1,
- );
- assert.equal(
- (
- await database
- .prepare('SELECT authorization_epoch AS n FROM kiln_accounts WHERE id=?')
- .bind(account)
- .first()
- ).n,
- 1,
- );
- assert.equal((await mcp(credential)).status, 200);
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/account`, {
- headers: { cookie: authorization.browserCookie },
- })
- ).status,
- 200,
- );
- // The consumed provider callback cannot be replayed, even though mutation rolled back.
- assert.equal((await finishIdentity(linked.second)).status, 400);
- } finally {
- await database.prepare('DROP TRIGGER reject_security_event').run();
- }
- assert.equal((await linkIdentity(authorization, user)).response.status, 200);
-});
-
-test('unlink races preserve a usable identity and primary revocation rejects stale refresh tokens', async () => {
- const user = 'unlink-race',
- first = await grant(user);
- assert.equal((await linkIdentity(first, user)).response.status, 200);
- const a = await grant(user),
- b = await grant(user, { provider: 'google' });
- const credential = await (await exchange(a)).json();
- const removeGoogle = await actionCallback(
- await startIdentity(a, 'unlink', 'google', 'github'),
- a,
- user,
- );
- const removeGithub = await actionCallback(
- await startIdentity(b, 'unlink', 'github', 'google'),
- b,
- user,
- );
- const results = await Promise.all([finishIdentity(removeGoogle), finishIdentity(removeGithub)]);
- assert.equal(results.filter((r) => r.status === 200).length, 1);
- assert.ok(
- results.filter((r) => r.status !== 200).every((r) => r.status === 400 || r.status === 403),
- );
- const account = (await connectionFor(a)).account_id;
- assert.equal(
- (
- await database
- .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE account_id=?')
- .bind(account)
- .first()
- ).n,
- 1,
- );
- const refreshed = await runtime.dispatchFetch(`${origin}/oauth/token`, {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- grant_type: 'refresh_token',
- refresh_token: credential.refresh_token,
- client_id: a.clientId,
- resource: `${origin}/mcp`,
- }),
- });
- assert.equal(refreshed.status, 400);
- assert.equal((await refreshed.json()).error, 'invalid_grant');
-});
-
-test('state changes during the upstream exchange are rechecked before linking', async () => {
- for (const mutation of ['disabled', 'epoch', 'session', 'confirmer']) {
- const user = `link-inflight-${mutation}`,
- authorization = await grant(user);
- const account = (await connectionFor(authorization)).account_id;
- const first = await actionCallback(
- await startIdentity(authorization, 'link', 'google', 'github'),
- authorization,
- user,
- );
- const second = await actionCallback(await finishIdentity(first), authorization, user);
- beforeProviderReply = async () => {
- beforeProviderReply = undefined;
- if (mutation === 'disabled')
- await database
- .prepare("UPDATE kiln_accounts SET state='disabled' WHERE id=?")
- .bind(account)
- .run();
- else if (mutation === 'epoch')
- await database
- .prepare('UPDATE kiln_accounts SET authorization_epoch=2 WHERE id=?')
- .bind(account)
- .run();
- else if (mutation === 'session')
- await database
- .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=?')
- .bind(account)
- .run();
- else
- await database
- .prepare('DELETE FROM kiln_identities WHERE account_id=?')
- .bind(account)
- .run();
- };
- try {
- assert.equal((await finishIdentity(second)).status, 403);
- } finally {
- beforeProviderReply = undefined;
- }
- assert.equal(
- (
- await database
- .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE account_id=? AND issuer=?')
- .bind(account, googleIssuer)
- .first()
- ).n,
- 0,
- );
- assert.equal(
- (
- await database
- .prepare('SELECT COUNT(*) AS n FROM kiln_account_events WHERE account_id=?')
- .bind(account)
- .first()
- ).n,
- 0,
- );
- }
-});
-
-test('identity intents are bounded, store hashes and reject oversized or duplicate forms before provider I/O', async () => {
- const user = 'link-bounds',
- authorization = await grant(user);
- const account = (await connectionFor(authorization)).account_id;
- for (let i = 0; i < 4; i++) {
- const start = await startIdentity(authorization, 'link', 'google', 'github');
- assert.equal(start.status, 302);
- const state = new URL(start.headers.get('location')).searchParams.get('state');
- const binding = cookies(start).split('=')[1];
- const stored = JSON.stringify(
- (
- await database
- .prepare('SELECT * FROM kiln_identity_actions WHERE account_id=?')
- .bind(account)
- .all()
- ).results,
- );
- assert.ok(!stored.includes(state));
- assert.ok(!stored.includes(binding));
- }
- const count = outboundCalls;
- assert.equal((await startIdentity(authorization, 'link', 'google', 'github')).status, 403);
- for (const body of [
- 'x'.repeat(4097),
- 'csrf=bad&csrf=bad&action=link&target=google&provider=github',
- ]) {
- const response = await runtime.dispatchFetch(`${origin}/account/identity`, {
- method: 'POST',
- headers: {
- origin,
- cookie: authorization.browserCookie,
- 'content-type': 'application/x-www-form-urlencoded',
- },
- body,
- });
- assert.equal(response.status, body.length > 4096 ? 413 : 403);
- }
- assert.equal(outboundCalls, count);
-});
diff --git a/hosting/test/browser-download-worker.ts b/hosting/test/browser-download-worker.ts
deleted file mode 100644
index c19f1e05..00000000
--- a/hosting/test/browser-download-worker.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import gateway from '../src/worker';
-import { KilnTenant } from '../src/tenant';
-import { D1BrowserSessions } from '../src/browser-sessions';
-
-// Test-only session issuer and delayed-revocation fixture, excluded from production.
-export class DownloadTenant extends KilnTenant {
- override async fetch(request: Request): Promise<Response> {
- const path = new URL(request.url).pathname;
- if (path === '/fixture/revoke') {
- await this.ctx.storage.put('revoke', true);
- return new Response('set');
- }
- if (path === '/fixture/headers')
- return Response.json((await this.ctx.storage.get('headers')) ?? {});
- if (path.startsWith('/internal/downloads/')) {
- await this.ctx.storage.put('headers', Object.fromEntries(request.headers));
- const response = await super.fetch(request);
- if (await this.ctx.storage.get('revoke')) {
- // Simulate account access changing while the tenant awaits object storage.
- const env = this.env as typeof this.env & { ACCOUNTS: D1Database };
- await env.ACCOUNTS.prepare('DELETE FROM kiln_browser_sessions').run();
- }
- return response;
- }
- return super.fetch(request);
- }
-}
-
-export default {
- async fetch(request: Request, env: Parameters<typeof gateway.fetch>[1], ctx: ExecutionContext) {
- // Node's fetch overwrites Sec-Fetch-Mode with cors; reproduce browser metadata here.
- if (request.headers.has('x-fixture-fetch-mode')) {
- const headers = new Headers(request.headers);
- headers.set('sec-fetch-mode', headers.get('x-fixture-fetch-mode')!);
- headers.delete('x-fixture-fetch-mode');
- request = new Request(request, { headers });
- }
- if (new URL(request.url).pathname === '/fixture/session') {
- const { subject } = (await request.json()) as { subject: string };
- const session = await new D1BrowserSessions(env.ACCOUNTS, env.PUBLIC_ORIGIN).issue({
- issuer: 'https://github.com',
- subject,
- });
- return Response.json(
- { accountId: session.account.id },
- { headers: { 'set-cookie': session.cookie } },
- );
- }
- return gateway.fetch(request, env, ctx);
- },
-};
diff --git a/hosting/test/browser-downloads.test.mjs b/hosting/test/browser-downloads.test.mjs
deleted file mode 100644
index 1975d19d..00000000
--- a/hosting/test/browser-downloads.test.mjs
+++ /dev/null
@@ -1,322 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { before, after, test } from 'node:test';
-import { build } from 'esbuild';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-import { migrateAccounts } from './database.mjs';
-import { rateLimitBindings } from './rate-limit-bindings.mjs';
-import { mkdir } from 'node:fs/promises';
-import { createKilnMcpServer } from '../../dist/mcp-engine.mjs';
-import { renderGLB } from '../../lib/render.js';
-
-const origin = 'https://kiln.example.com';
-let runtime, namespace, database, createNativeMcpHandler;
-const digest = (s) => createHash('sha256').update(s).digest('hex');
-before(async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./browser-download-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- name: 'browser-downloads',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['global_fetch_strictly_public'],
- kvNamespaces: ['OAUTH_KV'],
- ratelimits: rateLimitBindings,
- d1Databases: ['ACCOUNTS'],
- durableObjects: { TENANTS: { className: 'DownloadTenant', useSQLite: true } },
- r2Buckets: ['ARTIFACTS'],
- bindings: {
- PUBLIC_ORIGIN: origin,
- STORAGE_MAX_BYTES: '1048576',
- STORAGE_MAX_OBJECTS: '32',
- STORAGE_MAX_GROUPS: '8',
- },
- outboundService: async () => {
- throw Error('No network or compute permitted');
- },
- }),
- );
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
- database = await runtime.getD1Database('ACCOUNTS');
- await migrateAccounts(database);
- const output = new URL('../../.cache/browser-download-test/native-mcp.mjs', import.meta.url);
- await mkdir(fileURLToPath(new URL('./', output)), { recursive: true });
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-mcp.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- packages: 'external',
- alias: Object.fromEntries(
- [
- ['assets', 'assets'],
- ['assets/node', 'assets-node'],
- ['material-library/node', 'material-library-node'],
- ['material-library', 'material-library'],
- ['workspace', 'workspace'],
- ['evaluator', 'evaluator/index'],
- ['composer', 'composer/index'],
- ].map(([name, path]) => [
- `@instruktlabs/kiln/${name}`,
- fileURLToPath(new URL(`../../lib/${path}.js`, import.meta.url)),
- ]),
- ),
- });
- ({ createNativeMcpHandler } = await import(output));
-});
-after(async () => runtime?.dispose());
-const selector = { collection: 'project', assetId: 'a_box', revisionId: 'r_one' };
-async function session(subject) {
- const response = await runtime.dispatchFetch(`${origin}/fixture/session`, {
- method: 'POST',
- body: JSON.stringify({ subject }),
- });
- assert.equal(response.status, 200);
- const { accountId } = await response.json();
- const tenant = createHash('sha256')
- .update(JSON.stringify(['kiln-tenant-v1', origin, accountId]))
- .digest('base64url');
- const stub = namespace.getByName(tenant);
- return { accountId, cookie: response.headers.get('set-cookie').split(';')[0], stub };
-}
-async function seed(user) {
- const files = {};
- for (const [name, data] of [
- ['asset.glb', 'glTFfixture'],
- ['source.kiln.js', 'function build(){}'],
- ['manifest.json', '{}'],
- ]) {
- const response = await user.stub.fetch('https://tenant.internal/internal/artifacts', {
- method: 'POST',
- body: data,
- headers: {
- 'content-type':
- name === 'asset.glb'
- ? 'model/gltf-binary'
- : name.endsWith('.js')
- ? 'application/javascript'
- : 'application/json',
- 'x-artifact-name': name,
- 'x-artifact-sha256': digest(data),
- 'content-length': String(Buffer.byteLength(data)),
- },
- });
- assert.equal(response.status, 201);
- files[name] = (await response.json()).id;
- }
- const commit = await user.stub.fetch('https://tenant.internal/internal/assets/commit', {
- method: 'POST',
- body: JSON.stringify({ ...selector, files, mode: 'save' }),
- });
- assert.equal(commit.status, 201);
- const group = await commit.json();
- const response = await user.stub.fetch('https://tenant.internal/internal/downloads', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify(selector),
- });
- assert.equal(response.status, 201);
- const ticket = await response.json();
- return { path: `/downloads/${ticket.ticket}/asset.glb`, group };
-}
-const get = (path, cookie = '', extra = {}) =>
- runtime.dispatchFetch(`${origin}${path}`, {
- redirect: 'manual',
- ...extra,
- headers: {
- cookie,
- ...extra.headers,
- ...(extra.headers?.['sec-fetch-mode']
- ? { 'x-fixture-fetch-mode': extra.headers['sec-fetch-mode'] }
- : {}),
- },
- });
-
-test('saved bytes require the current owning browser account, with no compute or credential forwarding', async () => {
- const alice = await session('2101'),
- bob = await session('2102');
- const { path } = await seed(alice);
- const anonymous = await get(path);
- assert.equal(anonymous.status, 401);
- assert.match(
- await anonymous.text(),
- new RegExp(`name="returnTo" value="${path.replaceAll('.', '\\.')}"`),
- );
- assert.match(anonymous.headers.get('content-security-policy'), /frame-ancestors 'none'/);
- assert.equal((await get(path, bob.cookie)).status, 404);
- assert.equal(
- (
- await get(path, '', {
- headers: { authorization: 'Bearer fixture', 'x-tenant': alice.accountId },
- })
- ).status,
- 401,
- );
- const response = await get(path, alice.cookie, {
- headers: { authorization: 'Bearer fixture', 'x-tenant': bob.accountId },
- });
- assert.equal(response.status, 200);
- assert.equal(await response.text(), 'glTFfixture');
- assert.equal(response.headers.get('cache-control'), 'no-store');
- assert.equal(response.headers.get('referrer-policy'), 'no-referrer');
- assert.match(response.headers.get('content-disposition'), /attachment; filename="asset.glb"/);
- assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
- const headers = await (await alice.stub.fetch('https://tenant.internal/fixture/headers')).json();
- for (const key of ['authorization', 'cookie', 'x-tenant', 'range'])
- assert.equal(headers[key], undefined);
- const head = await get(path, alice.cookie, { method: 'HEAD' });
- assert.equal(head.status, 200);
- assert.equal(await head.text(), '');
- assert.equal(head.headers.get('content-length'), String('glTFfixture'.length));
-});
-
-test('download navigation accepts ordinary external links but denies cross-origin embedding and hostile routes', async () => {
- const alice = await session('2103');
- const { path } = await seed(alice);
- const navigate = await get(path, alice.cookie, {
- headers: {
- 'sec-fetch-site': 'cross-site',
- 'sec-fetch-mode': 'navigate',
- 'sec-fetch-dest': 'document',
- },
- });
- assert.equal(navigate.status, 200);
- await navigate.arrayBuffer();
- for (const headers of [
- { origin: 'https://evil.example' },
- { 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'no-cors', 'sec-fetch-dest': 'image' },
- { 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'navigate', 'sec-fetch-dest': 'iframe' },
- ])
- assert.equal((await get(path, alice.cookie, { headers })).status, 403);
- assert.equal((await get(path, alice.cookie, { method: 'POST', body: '{}' })).status, 405);
- for (const bad of [
- `${path}?tenant=other`,
- `${path}/extra`,
- path.replace('asset.glb', '%61sset.glb'),
- path.replace('asset.glb', 'secret.txt'),
- path.replace('asset.glb', 'asset.glb%0a'),
- ])
- assert.ok([400, 404].includes((await get(bad, alice.cookie)).status), bad);
- assert.equal((await get(path, '', { method: 'HEAD' })).status, 401);
-});
-
-test('browser revocation while storage is being read suppresses bytes, and deleting a saved revision revokes its links', async () => {
- const alice = await session('2104');
- const { path, group } = await seed(alice);
- await alice.stub.fetch('https://tenant.internal/fixture/revoke');
- const revoked = await get(path, alice.cookie);
- assert.equal(revoked.status, 401);
- assert.ok(!(await revoked.text()).includes('glTFfixture'));
- assert.equal((await get(path, alice.cookie)).status, 401);
- const fresh = await session('2104');
- const removed = await alice.stub.fetch(`https://tenant.internal/internal/groups/${group.id}`, {
- method: 'DELETE',
- });
- assert.equal(removed.status, 200);
- // The fixture revokes on every read; storage independently reports 404 first.
- const direct = await alice.stub.fetch(`https://tenant.internal/internal${path}`);
- assert.equal(direct.status, 404);
- assert.ok(fresh.cookie);
-});
-
-test('real MCP save and reopen links deliver exact bytes through the actual authenticated browser gateway', async () => {
- const alice = await session('2105'),
- bob = await session('2106');
- const code =
- "function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#aaaaaa'),{parent:r});return r;}";
- const host = () =>
- createNativeMcpHandler(
- {
- createServer: createKilnMcpServer,
- evaluatorPort: {
- render: async (source, options) => {
- assert.equal(source, code);
- return renderGLB(source, options);
- },
- },
- },
- {
- publicOrigin: origin,
- storage: {
- fetch: (request) =>
- alice.stub.fetch(
- new Request(`https://tenant.internal${new URL(request.url).pathname}`, request),
- ),
- },
- },
- );
- const call = async (name, args) => {
- const handler = host();
- try {
- const response = await handler.fetch(
- new Request('http://kiln-native.internal/mcp', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- 'mcp-protocol-version': '2025-11-25',
- },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method: 'tools/call',
- params: { name, arguments: args },
- }),
- }),
- );
- assert.equal(response.status, 200);
- const raw = await response.text();
- const result = response.headers.get('content-type')?.includes('text/event-stream')
- ? raw
- .split('\n')
- .filter((line) => line.startsWith('data:'))
- .map((line) => JSON.parse(line.slice(5)))
- .findLast((event) => event.id === 1)
- : JSON.parse(raw);
- assert.equal(result.error, undefined);
- assert.notEqual(result.result.isError, true, JSON.stringify(result));
- return JSON.parse(result.result.content.find((item) => item.type === 'text').text);
- } finally {
- await handler.close();
- }
- };
- const rendered = await call('kiln_render', { code, capture: { preset: '1x1' } });
- const saved = await call('kiln_save', {
- programRef: rendered.programRef,
- collection: 'project',
- name: 'Browser delivery box',
- });
- const request = {
- collection: 'project',
- assetId: saved.asset.assetId,
- revisionId: saved.asset.revisionId,
- };
- const reopened = await call('kiln_assets', { ...request, action: 'get' });
- assert.notEqual(saved.downloadUrls['asset.glb'], reopened.downloadUrls['asset.glb']);
- for (const name of ['asset.glb', 'source.kiln.js', 'manifest.json', 'preview.png']) {
- const path = new URL(reopened.downloadUrls[name]).pathname;
- assert.equal((await get(path, bob.cookie)).status, 404);
- const response = await get(path, alice.cookie);
- assert.equal(response.status, 200);
- const bytes = Buffer.from(await response.arrayBuffer());
- if (name === 'source.kiln.js') assert.equal(bytes.toString(), code);
- if (name === 'manifest.json') assert.equal(JSON.parse(bytes).revisionId, request.revisionId);
- if (name === 'asset.glb') {
- assert.equal(bytes.subarray(0, 4).toString(), 'glTF');
- assert.equal(`sha256:${digest(bytes)}`, reopened.asset.files[name].sha256);
- }
- if (name === 'preview.png')
- assert.deepEqual(bytes.subarray(0, 8), Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
- }
-});
diff --git a/hosting/test/browser-sessions-worker.ts b/hosting/test/browser-sessions-worker.ts
deleted file mode 100644
index f7b634b6..00000000
--- a/hosting/test/browser-sessions-worker.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { D1BrowserSessions } from '../src/browser-sessions';
-import { serviceFailure } from '../src/http';
-
-// Fixture only: production identity inputs come exclusively from provider proofs.
-export default {
- async fetch(request: Request, env: { ACCOUNTS: D1Database }) {
- try {
- const sessions = new D1BrowserSessions(env.ACCOUNTS, 'https://kiln.test');
- const path = new URL(request.url).pathname;
- if (path === '/issue')
- return Response.json(await sessions.issue(await request.json(), request));
- if (path === '/logout') {
- const body =
- request.method === 'POST' ? ((await request.json()) as { csrf: string }) : { csrf: '' };
- return new Response(null, {
- headers: { 'set-cookie': await sessions.logout(request, body.csrf) },
- });
- }
- return Response.json(await sessions.read(request));
- } catch (error) {
- return serviceFailure(error);
- }
- },
-} satisfies ExportedHandler<{ ACCOUNTS: D1Database }>;
diff --git a/hosting/test/browser-sessions.test.mjs b/hosting/test/browser-sessions.test.mjs
deleted file mode 100644
index 54ea0b1c..00000000
--- a/hosting/test/browser-sessions.test.mjs
+++ /dev/null
@@ -1,201 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-import { migrateAccounts } from './database.mjs';
-
-let runtime;
-let database;
-before(async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./browser-sessions-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- d1Databases: ['ACCOUNTS'],
- outboundService: async () => {
- throw new Error('Session storage must not fetch');
- },
- }),
- );
- database = await runtime.getD1Database('ACCOUNTS');
- await migrateAccounts(database);
-});
-after(async () => runtime?.dispose());
-
-const cookie = (issued) => issued.cookie.split(';')[0];
-const issue = async (subject, previous) => {
- const response = await runtime.dispatchFetch('https://kiln.test/issue', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- ...(previous ? { cookie: cookie(previous) } : {}),
- },
- body: JSON.stringify({ issuer: 'https://github.com', subject }),
- });
- assert.equal(response.status, 200);
- return response.json();
-};
-const read = (issued, headers = {}, url = 'https://kiln.test/account') =>
- runtime.dispatchFetch(url, { headers: { cookie: cookie(issued), ...headers } });
-const logout = (issued, csrf = issued.csrf, origin = 'https://kiln.test', method = 'POST') =>
- runtime.dispatchFetch('https://kiln.test/logout', {
- method,
- headers: { cookie: cookie(issued), origin, 'content-type': 'application/json' },
- body: method === 'GET' ? undefined : JSON.stringify({ csrf }),
- });
-
-test('browser sessions use fresh protected cookies and store only bearer-token hashes', async () => {
- const issued = await issue('browser-storage');
- assert.match(issued.cookie, /^__Host-kiln-session=[a-f0-9]{64};/);
- for (const attribute of ['Secure', 'HttpOnly', 'SameSite=Lax', 'Path=/', 'Max-Age=86400'])
- assert.ok(issued.cookie.includes(attribute));
- assert.ok(!issued.cookie.includes('Domain='));
- assert.match(issued.csrf, /^[a-f0-9]{64}$/);
- const session = await (await read(issued)).json();
- assert.equal(session.accountId, issued.account.id);
- assert.equal(session.accountEpoch, 1);
- const rows = await database.prepare('SELECT * FROM kiln_browser_sessions').all();
- const raw = cookie(issued).split('=')[1];
- assert.ok(!JSON.stringify(rows.results).includes(raw));
- const again = await issue('browser-storage');
- assert.equal(again.account.id, issued.account.id);
- assert.notEqual(cookie(again), cookie(issued));
-});
-
-test('a session cannot authenticate with a header, URL token, duplicate cookie, foreign origin or a stored hash', async () => {
- const issued = await issue('browser-cookie-admission');
- const raw = cookie(issued).split('=')[1];
- const stored = await database
- .prepare('SELECT token_hash FROM kiln_browser_sessions WHERE account_id=?')
- .bind(issued.account.id)
- .first();
- for (const headers of [
- { cookie: '', authorization: `Bearer ${raw}` },
- { cookie: `${cookie(issued)}; ${cookie(issued)}` },
- { cookie: `__Host-kiln-session=${stored.token_hash}` },
- { cookie: '__Host-kiln-session=invalid' },
- { cookie: `${cookie(issued)}; padding=${'x'.repeat(8192)}` },
- ])
- assert.equal((await read(issued, headers)).status, 401);
- assert.equal(
- (await read(issued, { cookie: '' }, `https://kiln.test/account?session=${raw}`)).status,
- 401,
- );
- assert.equal((await read(issued, {}, 'https://foreign.test/account')).status, 401);
-});
-
-test('expired sessions and changed account state or epoch fail closed', async () => {
- for (const mutation of ['expired', 'epoch', 'disabled', 'deleting']) {
- const issued = await issue(`browser-${mutation}`);
- if (mutation === 'expired')
- await database
- .prepare('UPDATE kiln_browser_sessions SET expires_at=0 WHERE account_id=?')
- .bind(issued.account.id)
- .run();
- else if (mutation === 'epoch')
- await database
- .prepare('UPDATE kiln_accounts SET authorization_epoch=2 WHERE id=?')
- .bind(issued.account.id)
- .run();
- else
- await database
- .prepare('UPDATE kiln_accounts SET state=? WHERE id=?')
- .bind(mutation, issued.account.id)
- .run();
- assert.equal((await read(issued)).status, 401);
- }
-});
-
-test('logout requires a same-origin POST and matching session CSRF proof', async () => {
- const issued = await issue('browser-logout');
- const other = await issue('browser-other');
- assert.equal((await logout(issued, issued.csrf, 'https://foreign.test')).status, 403);
- assert.equal((await logout(issued, other.csrf)).status, 403);
- assert.equal((await logout(issued, issued.csrf, 'https://kiln.test', 'GET')).status, 403);
- assert.equal((await read(issued)).status, 200);
- const result = await logout(issued);
- assert.equal(result.status, 200);
- assert.match(result.headers.get('set-cookie'), /Max-Age=0/);
- assert.equal((await read(issued)).status, 401);
- assert.equal((await read(other)).status, 200);
-});
-
-test('each account retains at most eight sessions without revoking other accounts', async () => {
- const other = await issue('browser-limit-other');
- const issued = await Promise.all(
- Array.from({ length: 20 }, () => issue('browser-session-limit')),
- );
- const accountId = issued[0].account.id;
- assert.equal(new Set(issued.map((value) => value.account.id)).size, 1);
- const row = await database
- .prepare('SELECT COUNT(*) AS n FROM kiln_browser_sessions WHERE account_id=?')
- .bind(accountId)
- .first();
- assert.equal(row.n, 8);
- assert.equal((await read(other)).status, 200);
-});
-
-test('session-write failure rolls back pruning and leaves existing sessions intact', async () => {
- const issued = await issue('browser-rollback');
- await database
- .prepare(`CREATE TRIGGER reject_session BEFORE INSERT ON kiln_browser_sessions
- BEGIN SELECT RAISE(ABORT, 'fixture rejection'); END`)
- .run();
- const response = await runtime.dispatchFetch('https://kiln.test/issue', {
- method: 'POST',
- body: JSON.stringify({ issuer: 'https://github.com', subject: 'browser-rollback' }),
- });
- assert.equal(response.status, 503);
- assert.equal((await read(issued)).status, 200);
- await database.prepare('DROP TRIGGER reject_session').run();
-});
-
-test('idle sessions expire and active requests cannot extend the absolute lifetime', async () => {
- const idle = await issue('browser-idle');
- await database
- .prepare('UPDATE kiln_browser_sessions SET idle_expires_at=0 WHERE account_id=?')
- .bind(idle.account.id)
- .run();
- assert.equal((await read(idle)).status, 401);
- assert.equal((await logout(idle)).status, 403);
- const active = await issue('browser-active');
- const absolute = Date.now() + 60_000;
- await database
- .prepare('UPDATE kiln_browser_sessions SET expires_at=? WHERE account_id=?')
- .bind(absolute, active.account.id)
- .run();
- assert.equal((await read(active)).status, 200);
- const stored = await database
- .prepare('SELECT expires_at, idle_expires_at FROM kiln_browser_sessions WHERE account_id=?')
- .bind(active.account.id)
- .first();
- assert.equal(stored.expires_at, absolute);
- assert.equal(stored.idle_expires_at, absolute);
-});
-
-test('fresh browser sign-in replaces that browser session without affecting another device', async () => {
- const previous = await issue('browser-rotation');
- const other = await issue('browser-rotation');
- const current = await issue('browser-rotation', previous);
- assert.equal((await read(previous)).status, 401);
- assert.equal((await read(current)).status, 200);
- assert.equal((await read(other)).status, 200);
-});
-
-test('rotating a browser at the session limit retains the other seven devices', async () => {
- const devices = [];
- for (let index = 0; index < 8; index++) devices.push(await issue('browser-rotation-limit'));
- const current = await issue('browser-rotation-limit', devices[7]);
- assert.equal((await read(current)).status, 200);
- assert.equal((await read(devices[7])).status, 401);
- for (const device of devices.slice(0, 7)) assert.equal((await read(device)).status, 200);
-});
diff --git a/hosting/test/build-boundary.test.mjs b/hosting/test/build-boundary.test.mjs
deleted file mode 100644
index fe1e2e7f..00000000
--- a/hosting/test/build-boundary.test.mjs
+++ /dev/null
@@ -1,49 +0,0 @@
-import assert from 'node:assert/strict';
-import { test } from 'node:test';
-import { fileURLToPath } from 'node:url';
-import { build } from 'esbuild';
-import { assertProductionBoundary } from '../scripts/build-boundary.mjs';
-
-for (const module of [
- 'github',
- 'account-page',
- 'account-actions',
- 'connections',
- 'browser-download',
-]) {
- test(`the actual ${module} dependency graph is gateway-only`, async () => {
- const result = await build({
- entryPoints: [fileURLToPath(new URL(`../src/${module}.ts`, import.meta.url))],
- bundle: true,
- write: false,
- metafile: true,
- format: 'esm',
- platform: 'browser',
- });
- const inputs = Object.keys(result.metafile.inputs);
- assert.doesNotThrow(() => assertProductionBoundary('worker', inputs));
- for (const entry of [
- 'tenant-worker',
- 'evaluation-worker',
- 'render-worker',
- 'request-worker',
- 'native-programs',
- 'native-assets',
- 'native-materials',
- 'native-mcp',
- 'native-host',
- 'native-evaluator',
- 'native-render',
- ]) {
- assert.throws(() => assertProductionBoundary(entry, inputs), /authorization-server/);
- assert.throws(
- () =>
- assertProductionBoundary(
- entry,
- inputs.map((name) => name.replaceAll('/', '\\')),
- ),
- /authorization-server/,
- );
- }
- });
-}
diff --git a/hosting/test/container-entry.test.mjs b/hosting/test/container-entry.test.mjs
deleted file mode 100644
index 189ac131..00000000
--- a/hosting/test/container-entry.test.mjs
+++ /dev/null
@@ -1,81 +0,0 @@
-import assert from 'node:assert/strict';
-import { spawn } from 'node:child_process';
-import { copyFile, mkdir } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { createEvaluatorRequestV2, decodeEvaluatorResultV2 } from '../../lib/evaluator/index.js';
-
-const output = new URL('../../.cache/hosted-container-test/', import.meta.url);
-const entry = fileURLToPath(new URL('evaluate.mjs', output));
-const limits = { maxGlbBytes: 2 * 1024 * 1024, maxResponseBytes: 8 * 1024 * 1024 };
-
-before(async () => {
- // Resolve the engine package's compiled exports outside hosting's private scope.
- await mkdir(output, { recursive: true });
- await copyFile(new URL('../container/evaluate.mjs', import.meta.url), entry);
-});
-
-// Only trusted fixed fixtures run on the test host. These are protocol checks,
-// not evidence that the child process can contain hostile source.
-function run(input) {
- return new Promise((resolve, reject) => {
- const child = spawn(process.execPath, [entry], {
- env: { ...process.env, KILN_RENDER: 'cpu' },
- stdio: ['pipe', 'pipe', 'pipe'],
- timeout: 20_000,
- });
- const stdout = [];
- const stderr = [];
- child.stdout.on('data', (chunk) => stdout.push(chunk));
- child.stderr.on('data', (chunk) => stderr.push(chunk));
- child.stdin.on('error', (error) => {
- if (!['EPIPE', 'ECONNRESET', 'EOF'].includes(error.code)) reject(error);
- });
- child.on('error', reject);
- child.on('close', (code, signal) =>
- resolve({
- code,
- signal,
- stdout: Buffer.concat(stdout).toString('utf8'),
- stderr: Buffer.concat(stderr).toString('utf8'),
- }),
- );
- child.stdin.end(input);
- });
-}
-
-test('container entry produces a canonical deterministic GLB from the compiled package', async () => {
- const { json } = createEvaluatorRequestV2({
- requestId: 'container-entry',
- code: 'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}',
- maxGlbBytes: limits.maxGlbBytes,
- });
- let previous;
- for (let i = 0; i < 2; i++) {
- const result = await run(json);
- assert.equal(result.signal, null);
- assert.equal(result.code, 0, result.stderr);
- const decoded = decodeEvaluatorResultV2(result.stdout, limits.maxGlbBytes, 'container-entry');
- assert.equal(decoded.ok, true);
- assert.equal(decoded.render.glb.subarray(0, 4).toString(), 'glTF');
- assert.ok(Buffer.byteLength(result.stdout) <= limits.maxResponseBytes);
- if (previous) assert.deepEqual(decoded.render.glb, previous);
- previous = decoded.render.glb;
- }
-});
-
-test('container entry returns only the canonical rejection for malformed envelopes', async () => {
- const result = await run('{"private":"FIXTURE_SOURCE_DO_NOT_ECHO"}');
- assert.equal(result.code, 0, result.stderr);
- assert.equal(JSON.parse(result.stdout).error.code, 'INPUT_INVALID');
- assert.equal(`${result.stdout}${result.stderr}`.includes('FIXTURE_SOURCE_DO_NOT_ECHO'), false);
-});
-
-test('container entry refuses oversized input and invalid UTF-8 without evaluation', async () => {
- for (const input of [Buffer.alloc(4 * 1024 * 1024 + 1, 32), Buffer.from([0xc3, 0x28])]) {
- const result = await run(input);
- assert.equal(result.code, 1);
- assert.equal(result.stdout, '');
- assert.equal(result.stderr, 'Kiln evaluator input or execution failed.\n');
- }
-});
diff --git a/hosting/test/container-job.test.mjs b/hosting/test/container-job.test.mjs
deleted file mode 100644
index 72b3915e..00000000
--- a/hosting/test/container-job.test.mjs
+++ /dev/null
@@ -1,489 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-
-let ContainerEvaluationJob, ContainerRenderJob;
-const image = `registry.cloudflare.com/fixture/kiln@sha256:${'a'.repeat(64)}`;
-const encoder = new TextEncoder();
-const input = encoder.encode('{"version":"kiln.evaluator.request.v2"}');
-const response = encoder.encode('{"version":"kiln.evaluator.result.v2"}');
-const controls = { deadlineMs: 2_000, maxResponseBytes: 1024 };
-const code = (expected) => (error) => error.code === expected;
-
-before(async () => {
- const output = new URL('../../.cache/hosted-container-test/job.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/container-job.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ ContainerEvaluationJob, ContainerRenderJob } = await import(output));
-});
-
-function fixture(options = {}) {
- const values = new Map();
- const events = [];
- let alarmAt;
- let transactionTail = Promise.resolve();
- let stopped;
- const monitor = new Promise((resolve) => {
- stopped = resolve;
- });
- let releaseExec;
- const pendingExec = new Promise((resolve) => {
- releaseExec = resolve;
- });
- let failCleanup = options.failCleanup ?? false;
- let unconfirmedCleanup = options.unconfirmedCleanup;
- const received = [];
- const stream = (bytes, hanging = false) =>
- new ReadableStream({
- start(controller) {
- if (bytes) controller.enqueue(bytes);
- if (!hanging) controller.close();
- },
- });
- const process = {
- stdin: new WritableStream({
- write(bytes) {
- events.push('input');
- received.push(bytes);
- },
- }),
- stdout: stream(options.output ?? response, options.hanging),
- stderr: stream(options.stderr ?? new Uint8Array()),
- exitCode: options.hanging ? new Promise(() => {}) : Promise.resolve(options.exitCode ?? 0),
- };
- const container = {
- images: { kiln: options.image ?? image, renderer: options.image ?? image },
- running: false,
- start(settings) {
- events.push('start');
- this.settings = settings;
- this.running = true;
- if (options.startFailure) throw new Error('private provider diagnostic');
- },
- async exec(command, settings) {
- events.push('exec');
- this.command = command;
- this.execSettings = settings;
- // The native API rejects named Linux identities. The image uses USER node.
- if (options.requireNumericUser && settings.user !== '1000:1000')
- throw new Error('internal error; fixture requires numeric uid:gid');
- return options.pendingExec ? pendingExec : process;
- },
- monitor() {
- return monitor;
- },
- async inspect() {
- events.push('inspect');
- if (events.includes('destroy')) {
- if (unconfirmedCleanup === 'inspect-error') throw new Error('private inspection failure');
- if (unconfirmedCleanup === 'inspect-pending') return new Promise(() => {});
- if (unconfirmedCleanup === 'inspect-live') return { image };
- }
- return this.running ? { image: options.observedImage ?? image } : null;
- },
- async setInactivityTimeout() {},
- async destroy() {
- events.push('destroy');
- if (failCleanup) throw new Error('private cleanup diagnostic');
- if (unconfirmedCleanup === 'running') return;
- this.running = false;
- stopped();
- },
- };
- const storage = {
- async get(key) {
- return values.get(key);
- },
- async put(key, value) {
- values.set(key, structuredClone(value));
- },
- async setAlarm(value) {
- events.push('alarm');
- alarmAt = Number(value);
- },
- async deleteAlarm() {
- alarmAt = undefined;
- },
- async transaction(callback) {
- const operation = transactionTail.then(() => callback(storage));
- transactionTail = operation.catch(() => {});
- return operation;
- },
- };
- return {
- context: { container, storage },
- values,
- events,
- received,
- get alarmAt() {
- return alarmAt;
- },
- finishStartup() {
- releaseExec(process);
- },
- repairCleanup() {
- failCleanup = false;
- unconfirmedCleanup = undefined;
- },
- };
-}
-
-test('render jobs use a fixed software image and entry with the same cleanup fence', async () => {
- const f = fixture();
- const result = await new ContainerRenderJob(f.context).run(input, controls);
- assert.deepEqual(result, response);
- assert.deepEqual(f.context.container.command, ['/usr/local/bin/node', '/opt/kiln/render.mjs']);
- assert.deepEqual(f.context.container.execSettings.env, {});
- assert.equal(f.context.container.settings.enableInternet, false);
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('job').state, 'finished');
- for (const limits of [
- { ...controls, deadlineMs: 30001 },
- { ...controls, maxResponseBytes: 20 * 1024 * 1024 + 1 },
- ]) {
- const rejected = fixture();
- await assert.rejects(
- new ContainerRenderJob(rejected.context).run(input, limits),
- code('INPUT_INVALID'),
- );
- assert.equal(rejected.events.includes('start'), false);
- }
- const wrongImage = fixture();
- delete wrongImage.context.container.images.renderer;
- await assert.rejects(
- new ContainerRenderJob(wrongImage.context).run(input, controls),
- code('INPUT_INVALID'),
- );
- assert.equal(wrongImage.events.includes('start'), false);
-});
-
-test('render cancellation survives eviction and unconfirmed cleanup suppresses output', async () => {
- const cancelled = fixture();
- await new ContainerRenderJob(cancelled.context).cancel();
- await assert.rejects(
- new ContainerRenderJob(cancelled.context).run(input, controls),
- code('JOB_ALREADY_USED'),
- );
- assert.equal(cancelled.events.includes('start'), false);
- const f = fixture({ failCleanup: true });
- await assert.rejects(
- new ContainerRenderJob(f.context).run(input, controls),
- code('CLEANUP_FAILED'),
- );
- assert.equal(f.values.get('job').state, 'running');
- f.repairCleanup();
- await new ContainerRenderJob(f.context).cancel();
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('job').state, 'finished');
-});
-
-test('starts one pinned, offline VM and destroys it before returning any output', async () => {
- const f = fixture();
- const job = new ContainerEvaluationJob(f.context);
- const result = await job.run(input, controls);
- assert.equal(job.executionImage(result), image);
- assert.equal(job.executionImage(Uint8Array.from(result)), undefined);
- assert.deepEqual(result, response);
- assert.equal(f.context.container.running, false);
- assert.deepEqual(f.received, [input]);
- assert.equal(f.context.container.settings.enableInternet, false);
- assert.equal(f.context.container.settings.image, image);
- assert.equal(f.context.container.settings.containerSnapshot, undefined);
- assert.deepEqual(f.context.container.command, ['/usr/local/bin/node', '/opt/kiln/evaluate.mjs']);
- assert.deepEqual(f.context.container.execSettings.env, { KILN_RENDER: 'cpu' });
- assert.ok(f.events.indexOf('alarm') < f.events.indexOf('start'));
- assert.ok(f.events.indexOf('inspect') < f.events.indexOf('input'));
- assert.equal(f.values.get('job').state, 'finished');
- assert.equal(f.alarmAt, undefined);
-});
-
-test('execution identity is unavailable for failed isolation or unconfirmed cleanup', async () => {
- for (const options of [{ observedImage: 'wrong-image' }, { failCleanup: true }]) {
- const f = fixture(options);
- const job = new ContainerEvaluationJob(f.context);
- await assert.rejects(job.run(input, controls));
- assert.equal(job.executionImage(response), undefined);
- }
-});
-
-test('rejects concurrent and subsequent attempts on the same durable job', async () => {
- const f = fixture();
- const first = new ContainerEvaluationJob(f.context);
- const second = new ContainerEvaluationJob(f.context);
- const results = await Promise.allSettled([
- first.run(input, controls),
- second.run(input, controls),
- ]);
- assert.equal(results.filter((result) => result.status === 'fulfilled').length, 1);
- assert.equal(
- results.find((result) => result.status === 'rejected').reason.code,
- 'JOB_ALREADY_USED',
- );
- assert.equal(f.events.filter((event) => event === 'start').length, 1);
- assert.equal(f.events.filter((event) => event === 'destroy').length, 1);
- await assert.rejects(second.run(input, controls), code('JOB_ALREADY_USED'));
-});
-
-test('exec explicitly selects the image user by numeric uid and gid', async () => {
- const f = fixture({ requireNumericUser: true });
- assert.deepEqual(await new ContainerEvaluationJob(f.context).run(input, controls), response);
- assert.equal(f.context.container.execSettings.user, '1000:1000');
- assert.equal(f.context.container.running, false);
-});
-
-test('rejects unpinned images, excessive requests and invalid limits before starting', async () => {
- for (const [options, request, limits] of [
- [{ image: 'registry.example/kiln:latest' }, input, controls],
- [{}, new Uint8Array(4 * 1024 * 1024 + 1), controls],
- [{}, input, { ...controls, deadlineMs: 60_001 }],
- [{}, input, { ...controls, maxResponseBytes: 8 * 1024 * 1024 + 1 }],
- ]) {
- const f = fixture(options);
- await assert.rejects(
- new ContainerEvaluationJob(f.context).run(request, limits),
- code('INPUT_INVALID'),
- );
- assert.equal(f.events.includes('start'), false);
- }
-});
-
-test('does not send source to an image whose observed identity differs', async () => {
- const f = fixture({ observedImage: `registry.example/other@sha256:${'b'.repeat(64)}` });
- await assert.rejects(
- new ContainerEvaluationJob(f.context).run(input, controls),
- code('ISOLATION_UNAVAILABLE'),
- );
- assert.deepEqual(f.received, []);
- assert.equal(f.context.container.running, false);
-});
-
-test('output and stderr floods destroy the VM and cannot return a success', async () => {
- for (const options of [
- { output: new Uint8Array(1025), hanging: true },
- { stderr: new Uint8Array(16_385) },
- ]) {
- const f = fixture(options);
- await assert.rejects(
- new ContainerEvaluationJob(f.context).run(input, controls),
- code('OUTPUT_LIMIT_EXCEEDED'),
- );
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('job').outcome, 'OUTPUT_LIMIT_EXCEEDED');
- }
-});
-
-test('the external deadline destroys a hung evaluation including when startup is pending', async () => {
- for (const options of [{ hanging: true }, { pendingExec: true }]) {
- const f = fixture(options);
- await assert.rejects(
- new ContainerEvaluationJob(f.context).run(input, { ...controls, deadlineMs: 30 }),
- code('DEADLINE_EXCEEDED'),
- );
- assert.equal(f.context.container.running, false);
- if (options.pendingExec) {
- f.finishStartup();
- await new Promise((resolve) => setImmediate(resolve));
- assert.deepEqual(f.received, []);
- }
- }
-});
-
-test('caller cancellation destroys the whole VM; pre-cancellation starts nothing', async () => {
- const f = fixture({ pendingExec: true });
- const controller = new AbortController();
- const pending = new ContainerEvaluationJob(f.context).run(input, {
- ...controls,
- signal: controller.signal,
- });
- while (!f.events.includes('exec')) await new Promise((resolve) => setImmediate(resolve));
- controller.abort();
- await assert.rejects(pending, code('CANCELLED'));
- assert.equal(f.context.container.running, false);
- const untouched = fixture();
- await assert.rejects(
- new ContainerEvaluationJob(untouched.context).run(input, {
- ...controls,
- signal: controller.signal,
- }),
- code('CANCELLED'),
- );
- assert.deepEqual(untouched.events, []);
-});
-
-test('cleanup failure suppresses output and a durable recovery alarm retries destruction', async () => {
- const f = fixture({ failCleanup: true });
- await assert.rejects(
- new ContainerEvaluationJob(f.context).run(input, controls),
- code('CLEANUP_FAILED'),
- );
- assert.equal(f.values.get('job').state, 'running');
- assert.ok(Number.isSafeInteger(f.alarmAt));
- f.repairCleanup();
- f.values.get('job').deadlineAt = Date.now() - 1;
- await new ContainerEvaluationJob(f.context).alarm();
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('job').state, 'finished');
- assert.equal(f.values.get('job').outcome, 'DEADLINE_EXCEEDED');
- assert.equal(f.alarmAt, undefined);
-});
-
-test('cleanup must confirm both stopped state and inspection before releasing output or its alarm', async () => {
- for (const unconfirmedCleanup of ['running', 'inspect-live', 'inspect-error']) {
- const f = fixture({ unconfirmedCleanup });
- await assert.rejects(
- new ContainerEvaluationJob(f.context).run(input, controls),
- code('CLEANUP_FAILED'),
- );
- assert.equal(f.values.get('job').state, 'running');
- assert.ok(Number.isSafeInteger(f.alarmAt));
- f.values.get('job').deadlineAt = Date.now() - 1;
- await assert.rejects(new ContainerEvaluationJob(f.context).alarm(), code('CLEANUP_FAILED'));
- assert.equal(f.values.get('job').state, 'running');
- assert.ok(f.alarmAt > Date.now());
- f.repairCleanup();
- await new ContainerEvaluationJob(f.context).alarm();
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('job').state, 'finished');
- assert.equal(f.alarmAt, undefined);
- }
-});
-
-test('the same cleanup deadline bounds a stalled stopped-state inspection', async (t) => {
- t.mock.timers.enable({ apis: ['setTimeout'] });
- const f = fixture({ unconfirmedCleanup: 'inspect-pending' });
- const pending = new ContainerEvaluationJob(f.context).run(input, controls);
- const rejected = assert.rejects(pending, code('CLEANUP_FAILED'));
- // Let real promise/stream callbacks reach cleanup before advancing the clock.
- await new Promise((resolve) => setImmediate(resolve));
- assert.ok(f.events.includes('destroy'));
- t.mock.timers.tick(5_000);
- await rejected;
- assert.equal(f.values.get('job').state, 'running');
- assert.ok(Number.isSafeInteger(f.alarmAt));
-});
-
-test('startup or native process failures are bounded public errors with cleanup', async () => {
- for (const options of [{ startFailure: true }, { exitCode: 1 }]) {
- const f = fixture(options);
- await assert.rejects(
- new ContainerEvaluationJob(f.context).run(input, controls),
- code('WORKER_FAILED'),
- );
- assert.equal(f.context.container.running, false);
- }
-});
-
-test('durable cancellation fences a child before arrival and survives object reconstruction', async () => {
- const f = fixture();
- const job = new ContainerEvaluationJob(f.context);
- await job.cancel();
- assert.equal(f.values.get('job').state, 'finished');
- assert.equal(f.values.get('job').outcome, 'CANCELLED');
- await assert.rejects(
- new ContainerEvaluationJob(f.context).run(input, controls),
- code('JOB_ALREADY_USED'),
- );
- assert.equal(f.events.includes('start'), false);
- assert.equal(f.alarmAt, undefined);
-});
-
-test('durable cancellation during the persisted claim cannot start a late VM', async () => {
- const f = fixture();
- const job = new ContainerEvaluationJob(f.context);
- assert.equal(typeof job.cancel, 'function');
- let release;
- const gate = new Promise((resolve) => {
- release = resolve;
- });
- const transaction = f.context.storage.transaction;
- f.context.storage.transaction = (callback) =>
- transaction(async (tx) => {
- await gate;
- return callback(tx);
- });
- const rejected = assert.rejects(job.run(input, controls), code('CANCELLED'));
- const cancelled = job.cancel();
- release();
- await Promise.all([rejected, cancelled]);
- assert.equal(f.events.includes('start'), false);
- assert.equal(f.values.get('job').state, 'finished');
- assert.equal(f.values.get('job').outcome, 'CANCELLED');
- assert.equal(f.alarmAt, undefined);
-});
-
-test('durable cancellation waits for confirmed cleanup and prevents late startup input', async () => {
- const f = fixture({ pendingExec: true });
- const job = new ContainerEvaluationJob(f.context);
- assert.equal(typeof job.cancel, 'function');
- let release;
- const gate = new Promise((resolve) => {
- release = resolve;
- });
- const destroy = f.context.container.destroy.bind(f.context.container);
- f.context.container.destroy = async () => {
- await gate;
- await destroy();
- };
- const rejected = assert.rejects(job.run(input, controls), code('CANCELLED'));
- while (!f.events.includes('exec')) await new Promise((resolve) => setImmediate(resolve));
- let returned = false;
- const cancelled = job.cancel().then(() => {
- returned = true;
- });
- await new Promise((resolve) => setImmediate(resolve));
- assert.equal(returned, false);
- assert.equal(f.context.container.running, true);
- assert.equal(f.values.get('job').cancelled, true);
- const repeated = job.cancel();
- const alarm = job.alarm();
- release();
- await Promise.all([rejected, cancelled, repeated, alarm]);
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('job').state, 'finished');
- assert.equal(f.events.filter((event) => event === 'destroy').length, 1);
- f.finishStartup();
- await new Promise((resolve) => setImmediate(resolve));
- assert.deepEqual(f.received, []);
-});
-
-test('failed cancellation retains a durable fence and alarm for recovery after eviction', async () => {
- const f = fixture({ pendingExec: true, failCleanup: true });
- const job = new ContainerEvaluationJob(f.context);
- assert.equal(typeof job.cancel, 'function');
- const rejected = assert.rejects(job.run(input, controls), code('CLEANUP_FAILED'));
- while (!f.events.includes('exec')) await new Promise((resolve) => setImmediate(resolve));
- await assert.rejects(job.cancel(), code('CLEANUP_FAILED'));
- await rejected;
- assert.equal(f.values.get('job').state, 'running');
- assert.equal(f.values.get('job').cancelled, true);
- assert.ok(Number.isSafeInteger(f.alarmAt));
- f.repairCleanup();
- await new ContainerEvaluationJob(f.context).alarm();
- assert.equal(f.values.get('job').state, 'finished');
- assert.equal(f.values.get('job').outcome, 'CANCELLED');
- assert.equal(f.context.container.running, false);
- assert.equal(f.alarmAt, undefined);
- await assert.rejects(
- new ContainerEvaluationJob(f.context).run(input, controls),
- code('JOB_ALREADY_USED'),
- );
-});
-
-test('repeated cancellation preserves completed work and never restarts or destroys it again', async () => {
- const f = fixture();
- const job = new ContainerEvaluationJob(f.context);
- assert.equal(typeof job.cancel, 'function');
- await job.run(input, controls);
- const previous = structuredClone(f.values.get('job'));
- await Promise.all([job.cancel(), job.cancel()]);
- await new ContainerEvaluationJob(f.context).cancel();
- assert.deepEqual(f.values.get('job'), previous);
- assert.equal(f.events.filter((event) => event === 'start').length, 1);
- assert.equal(f.events.filter((event) => event === 'destroy').length, 1);
-});
diff --git a/hosting/test/database.mjs b/hosting/test/database.mjs
deleted file mode 100644
index 22aaa300..00000000
--- a/hosting/test/database.mjs
+++ /dev/null
@@ -1,23 +0,0 @@
-import { readFile } from 'node:fs/promises';
-
-export async function migrateAccounts(database) {
- for (const file of [
- '0001_accounts.sql',
- '0002_login_intents.sql',
- '0003_browser_sessions.sql',
- '0004_browser_logins.sql',
- '0005_connections.sql',
- '0006_account_actions.sql',
- '0007_browser_login_return.sql',
- '0008_identity_actions.sql',
- '0009_account_deletion.sql',
- ]) {
- const source = await readFile(new URL(`../migrations/${file}`, import.meta.url), 'utf8');
- await database.batch(
- source
- .split(';')
- .filter((sql) => sql.trim())
- .map((sql) => database.prepare(sql)),
- );
- }
-}
diff --git a/hosting/test/deletion-integration-worker.ts b/hosting/test/deletion-integration-worker.ts
deleted file mode 100644
index 4df3c550..00000000
--- a/hosting/test/deletion-integration-worker.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { WorkerEntrypoint } from 'cloudflare:workers';
-import gateway, { type Env } from '../src/worker';
-
-// No native job is started in this identity/storage fixture. The real admission
-// cancellation contract is exercised separately by admission-worker.test.mjs.
-export class EmptyCompute extends WorkerEntrypoint<Env> {
- health() {
- return { paused: false, activeRequests: 0, pendingCleanup: 0, maxConcurrent: 1 };
- }
- dispatch(): Response {
- return new Response('Native execution excluded from fixture', { status: 503 });
- }
- async retireTenant(tenant: string): Promise<void> {
- await this.env.ACCOUNTS.prepare(
- 'CREATE TABLE IF NOT EXISTS fixture_retired (tenant TEXT PRIMARY KEY)',
- ).run();
- await this.env.ACCOUNTS.prepare('INSERT OR IGNORE INTO fixture_retired VALUES (?)')
- .bind(tenant)
- .run();
- }
-}
-
-// Allows tests to invoke the actual scheduled handler. This file never ships.
-export default {
- async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
- if (new URL(request.url).pathname === '/fixture/recover') {
- await gateway.scheduled({ cron: '* * * * *', scheduledTime: Date.now(), noRetry() {} }, env);
- return new Response('Recovered');
- }
- return gateway.fetch(request, env, ctx);
- },
-};
diff --git a/hosting/test/deletion-recovery.test.mjs b/hosting/test/deletion-recovery.test.mjs
deleted file mode 100644
index b6d09204..00000000
--- a/hosting/test/deletion-recovery.test.mjs
+++ /dev/null
@@ -1,123 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { before, test } from 'node:test';
-import { fileURLToPath } from 'node:url';
-import { build } from 'esbuild';
-
-let deletionPorts;
-before(async () => {
- const output = new URL('../../.cache/hosted-deletion-recovery/ports.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/deletion-recovery.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ deletionPorts } = await import(output));
-});
-const account = `ka_${'a'.repeat(32)}`,
- origin = 'https://kiln.example.com';
-const tenant = createHash('sha256')
- .update(JSON.stringify(['kiln-tenant-v1', origin, account]))
- .digest('base64url');
-
-test('deletion binding derives tenancy outside compute and accepts only an exact, complete storage receipt', async () => {
- const calls = [];
- let response = { state: 'purged', pendingWrites: 0, remainingObjects: 0 };
- const env = {
- NATIVE_COMPUTE: { retireTenant: async (value) => calls.push(['compute', value]) },
- TENANTS: {
- getByName: (value) => ({
- async fetch(url, init) {
- calls.push(['storage', value, url, init]);
- return Response.json(response);
- },
- }),
- },
- };
- const ports = deletionPorts(env, origin, {});
- await ports.retireCompute(account);
- assert.equal(await ports.retireStorage(account), true);
- assert.deepEqual(calls, [
- ['compute', tenant],
- ['storage', tenant, 'https://tenant.internal/internal/account-deletion', { method: 'POST' }],
- ]);
- response = { state: 'retiring', pendingWrites: 1, remainingObjects: 1 };
- assert.equal(await ports.retireStorage(account), false);
- for (const invalid of [
- { state: 'purged', pendingWrites: 1, remainingObjects: 0 },
- { state: 'purged', pendingWrites: 0, remainingObjects: 1 },
- { state: 'purged', pendingWrites: 0 },
- { state: 'active', pendingWrites: 0, remainingObjects: 0 },
- { state: 'purged', pendingWrites: 0, remainingObjects: 0, tenant: 'other' },
- 'x'.repeat(2048),
- ]) {
- response = invalid;
- await assert.rejects(ports.retireStorage(account));
- }
- await assert.rejects(ports.retireStorage('invalid-account'));
- await assert.rejects(deletionPorts({ TENANTS: env.TENANTS }, origin, {}).retireCompute(account));
-});
-
-test('grant cleanup is bounded to the deleting owner and persists progress only after revocation', async () => {
- const revoked = [],
- cleared = [];
- let known = ['known-grant'],
- listed = [{ id: 'orphan-grant', userId: account }];
- const env = {
- ACCOUNTS: {
- withSession(mode) {
- assert.equal(mode, 'first-primary');
- return {
- prepare(sql) {
- return {
- bind(...args) {
- assert.equal(args[0], account);
- return {
- all: async () => {
- assert.match(sql, /LIMIT 4/);
- return { results: known.map((id) => ({ id })) };
- },
- run: async () => {
- cleared.push(args);
- known = known.filter((id) => id !== args[1]);
- },
- };
- },
- };
- },
- };
- },
- },
- };
- const oauth = {
- listUserGrants: async (user, options) => {
- assert.equal(user, account);
- assert.deepEqual(options, { limit: 4 });
- return { items: listed };
- },
- revokeGrant: async (id, user) => {
- revoked.push([id, user]);
- listed = listed.filter((row) => row.id !== id);
- },
- };
- const ports = deletionPorts(env, origin, oauth);
- assert.equal(await ports.revokeGrants(account), false);
- assert.deepEqual(revoked, [
- ['known-grant', account],
- ['orphan-grant', account],
- ]);
- assert.equal(cleared.length, 2);
- assert.equal(await ports.revokeGrants(account), true);
- listed = [{ id: 'foreign', userId: 'other' }];
- await assert.rejects(ports.revokeGrants(account));
- assert.equal(revoked.length, 2);
- listed = [];
- known = ['failed-grant'];
- oauth.revokeGrant = async () => {
- throw new Error('Injected revocation failure');
- };
- await assert.rejects(ports.revokeGrants(account));
- assert.deepEqual(known, ['failed-grant']);
-});
diff --git a/hosting/test/deletions-worker.ts b/hosting/test/deletions-worker.ts
deleted file mode 100644
index 9e6a3cd1..00000000
--- a/hosting/test/deletions-worker.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { D1AccountDeletions } from '../src/account-deletions';
-import { serviceFailure } from '../src/http';
-import type { BrowserSession } from '../src/browser-sessions';
-import type { VerifiedIdentity } from '../src/accounts';
-
-// This synthetic interface supplies verified proofs only for local tests. It is
-// not a production route, credential issuer or native execution qualification.
-export default {
- async fetch(
- request: Request,
- env: { ACCOUNTS: D1Database },
- ctx: ExecutionContext,
- ): Promise<Response> {
- const database = env.ACCOUNTS;
- const ports = {
- async retireCompute(account: string) {
- await database
- .prepare("INSERT INTO fixture_calls VALUES ('compute',?)")
- .bind(account)
- .run();
- if (await database.prepare("SELECT 1 FROM fixture_faults WHERE name='compute'").first())
- throw new Error('Injected compute cleanup');
- if (
- await database.prepare("SELECT 1 FROM fixture_faults WHERE name='held-compute'").first()
- ) {
- const pending = new Promise<void>((resolve) => setTimeout(resolve, 20_200)).then(
- async () => {
- await database
- .prepare("INSERT INTO fixture_calls VALUES ('compute-returned',?)")
- .bind(account)
- .run();
- },
- );
- // Keep the originating request alive so this fixture proves a real
- // late completion, not just workerd cancelling an abandoned promise.
- ctx.waitUntil(pending);
- await pending;
- }
- if (
- await database.prepare("SELECT 1 FROM fixture_faults WHERE name='lease-takeover'").first()
- )
- await database
- .prepare("UPDATE kiln_deletions SET lease_token='replacement' WHERE account_id=?")
- .bind(account)
- .run();
- },
- async retireStorage(account: string) {
- await database
- .prepare("INSERT INTO fixture_calls VALUES ('storage',?)")
- .bind(account)
- .run();
- if (
- await database.prepare("SELECT 1 FROM fixture_faults WHERE name='storage-error'").first()
- )
- throw new Error('Injected storage failure');
- return !(await database
- .prepare("SELECT 1 FROM fixture_faults WHERE name='storage-pending'")
- .first());
- },
- async revokeGrants(account: string) {
- await database.prepare("INSERT INTO fixture_calls VALUES ('grants',?)").bind(account).run();
- return !(await database
- .prepare("SELECT 1 FROM fixture_faults WHERE name='grants-pending'")
- .first());
- },
- };
- try {
- const now = Number(request.headers.get('x-fixture-now')) || Date.now();
- const jobs = new D1AccountDeletions(database, 'https://kiln.example.com', ports, () => now);
- const path = new URL(request.url).pathname;
- if (path === '/request') {
- const value = (await request.json()) as {
- proof: BrowserSession;
- identity: VerifiedIdentity;
- receipt: string;
- };
- return Response.json(await jobs.request(value.proof, value.identity, value.receipt));
- }
- if (path === '/recover') return Response.json(await jobs.recover());
- if (path === '/status')
- return Response.json(await jobs.status(request.headers.get('x-fixture-receipt')));
- return new Response('Not found', { status: 404 });
- } catch (error) {
- return serviceFailure(error);
- }
- },
-};
diff --git a/hosting/test/deletions.test.mjs b/hosting/test/deletions.test.mjs
deleted file mode 100644
index 2fb4d088..00000000
--- a/hosting/test/deletions.test.mjs
+++ /dev/null
@@ -1,304 +0,0 @@
-import assert from 'node:assert/strict';
-import { randomBytes } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { before, after, beforeEach, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-import { migrateAccounts } from './database.mjs';
-
-let runtime, database;
-let now;
-before(async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./deletions-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- d1Databases: ['ACCOUNTS'],
- outboundService: () => {
- throw new Error('Unexpected network');
- },
- }),
- );
- database = await runtime.getD1Database('ACCOUNTS');
- await migrateAccounts(database);
- await database.exec(
- 'CREATE TABLE fixture_calls (phase TEXT, account TEXT); CREATE TABLE fixture_faults (name TEXT PRIMARY KEY)',
- );
-});
-after(async () => runtime?.dispose());
-beforeEach(async () => {
- now = Date.now();
- await database.exec(
- 'DELETE FROM fixture_calls; DELETE FROM fixture_faults; DELETE FROM kiln_deletions; DELETE FROM kiln_browser_sessions; DELETE FROM kiln_connections; DELETE FROM kiln_account_events; DELETE FROM kiln_identities; DELETE FROM kiln_accounts',
- );
-});
-const random = () => randomBytes(32).toString('hex');
-const send = (path, init = {}) =>
- runtime.dispatchFetch(`https://fixture.internal${path}`, {
- ...init,
- headers: { 'x-fixture-now': String(now), ...init.headers },
- });
-async function owner() {
- const accountId = `ka_${randomBytes(16).toString('hex')}`;
- const identity = { issuer: 'https://github.com', subject: random() };
- const proof = {
- binding: random(),
- accountId,
- accountEpoch: 1,
- authenticatedAt: now,
- expiresAt: now + 100_000,
- csrf: random(),
- };
- await database.batch([
- database.prepare('INSERT INTO kiln_accounts(id,created_at) VALUES (?,?)').bind(accountId, now),
- database
- .prepare('INSERT INTO kiln_identities VALUES (?,?,?,?)')
- .bind(identity.issuer, identity.subject, accountId, now),
- database
- .prepare('INSERT INTO kiln_browser_sessions VALUES (?,?,?,?,?,?,?)')
- .bind(proof.binding, accountId, 1, now, proof.expiresAt, proof.expiresAt, proof.csrf),
- ]);
- return { proof, identity, receipt: random() };
-}
-const begin = (value) => send('/request', { method: 'POST', body: JSON.stringify(value) });
-const status = async (value) =>
- (await send('/status', { headers: { 'x-fixture-receipt': value.receipt } })).json();
-const row = (value) =>
- database
- .prepare('SELECT * FROM kiln_deletions WHERE receipt_hash IS NOT NULL AND account_id=?')
- .bind(value.proof.accountId)
- .first();
-const account = (value) =>
- database.prepare('SELECT * FROM kiln_accounts WHERE id=?').bind(value.proof.accountId).first();
-const calls = async () => (await database.prepare('SELECT * FROM fixture_calls').all()).results;
-async function recover() {
- assert.equal((await send('/recover')).status, 200);
-}
-
-test('deletion atomically revokes access and persists a private recovery receipt before external work', async () => {
- const a = await owner(),
- b = await owner();
- assert.equal((await begin(a)).status, 200);
- assert.equal((await account(a)).state, 'deleting');
- assert.equal((await account(a)).authorization_epoch, 2);
- assert.equal(
- await database
- .prepare('SELECT 1 FROM kiln_browser_sessions WHERE account_id=?')
- .bind(a.proof.accountId)
- .first(),
- null,
- );
- assert.equal((await account(b)).state, 'active');
- assert.deepEqual(await calls(), []);
- assert.equal((await status(a)).state, 'pending');
- assert.equal((await status(a)).phase, 'compute');
- assert.notEqual((await row(a)).receipt_hash, a.receipt);
- assert.equal((await begin(a)).status, 403);
- assert.equal((await send('/status', { headers: { 'x-fixture-receipt': random() } })).status, 404);
-});
-
-test('revocation and recovery intent roll back together on a storage failure', async () => {
- const a = await owner();
- await database.exec(
- "CREATE TRIGGER fail_deletion BEFORE INSERT ON kiln_deletions BEGIN SELECT RAISE(ABORT,'fixture'); END",
- );
- try {
- assert.equal((await begin(a)).status, 503);
- assert.equal((await account(a)).state, 'active');
- assert.equal((await account(a)).authorization_epoch, 1);
- assert.ok(
- await database
- .prepare('SELECT 1 FROM kiln_browser_sessions WHERE account_id=?')
- .bind(a.proof.accountId)
- .first(),
- );
- assert.equal(await row(a), null);
- } finally {
- await database.exec('DROP TRIGGER fail_deletion');
- }
-});
-
-test('only an unexpired current browser proof and its freshly verified identity may request deletion', async () => {
- const a = await owner(),
- b = await owner();
- for (const invalid of [
- { ...a, identity: b.identity },
- { ...a, proof: { ...a.proof, accountEpoch: 2 } },
- { ...a, proof: { ...a.proof, binding: b.proof.binding } },
- { ...a, receipt: 'invalid' },
- ])
- assert.equal((await begin(invalid)).status, 403);
- now += 100_001;
- assert.equal((await begin(a)).status, 403);
- assert.equal((await account(a)).state, 'active');
-});
-
-test('recovery preserves strict cleanup order, then removes identity records without reactivating the old account', async () => {
- const a = await owner(),
- b = await owner();
- await begin(a);
- await recover();
- assert.equal((await status(a)).state, 'complete');
- assert.equal(await account(a), null);
- assert.equal((await account(b)).state, 'active');
- assert.deepEqual(
- (await calls()).map(({ phase }) => phase),
- ['compute', 'storage', 'grants'],
- );
- assert((await calls()).every(({ account }) => account === a.proof.accountId));
- assert.equal(
- await database
- .prepare('SELECT 1 FROM kiln_identities WHERE account_id=?')
- .bind(a.proof.accountId)
- .first(),
- null,
- );
- const receipt = await database
- .prepare("SELECT * FROM kiln_deletions WHERE phase='complete'")
- .first();
- assert.equal(receipt.account_id, null);
- assert.equal(receipt.lease_token, null);
- await recover();
- assert.equal((await calls()).length, 3);
- now += 7 * 86400_000 + 1;
- await recover();
- assert.equal(
- (await send('/status', { headers: { 'x-fixture-receipt': a.receipt } })).status,
- 404,
- );
-});
-
-test('unconfirmed compute cleanup prevents storage removal and survives a recovery restart', async () => {
- const a = await owner();
- await begin(a);
- await database.exec("INSERT INTO fixture_faults VALUES ('compute')");
- await recover();
- assert.equal((await status(a)).phase, 'compute');
- assert.deepEqual(
- (await calls()).map(({ phase }) => phase),
- ['compute'],
- );
- assert.equal((await account(a)).state, 'deleting');
- await recover();
- assert.equal((await calls()).length, 1, 'backoff prevents immediate retry storms');
- await database.exec('DELETE FROM fixture_faults');
- now += 60_001;
- await recover();
- assert.equal((await status(a)).state, 'complete');
-});
-
-test('incomplete storage or token cleanup never clears identities or claims completion', async () => {
- for (const fault of ['storage-pending', 'storage-error', 'grants-pending']) {
- const a = await owner();
- await begin(a);
- await database.prepare('INSERT INTO fixture_faults VALUES (?)').bind(fault).run();
- await recover();
- assert.equal((await status(a)).state, 'pending');
- assert.equal((await account(a)).state, 'deleting');
- assert.ok(
- await database
- .prepare('SELECT 1 FROM kiln_identities WHERE account_id=?')
- .bind(a.proof.accountId)
- .first(),
- );
- await database.exec('DELETE FROM fixture_faults');
- now += 60_001;
- await recover();
- assert.equal((await status(a)).state, 'complete');
- }
-});
-
-test('concurrent recovery claims do not double-run a phase and expired leases are recoverable', async () => {
- const a = await owner();
- await begin(a);
- await database
- .prepare('UPDATE kiln_deletions SET lease_token=?,lease_until=?')
- .bind('crashed-worker', now + 60_000)
- .run();
- await recover();
- assert.deepEqual(await calls(), []);
- now += 60_001;
- await Promise.all([recover(), recover(), recover()]);
- assert.equal((await status(a)).state, 'complete');
- assert.deepEqual(
- (await calls()).map(({ phase }) => phase),
- ['compute', 'storage', 'grants'],
- );
-});
-
-test('a replaced recovery lease cannot advance or finalize another worker claim', async () => {
- const a = await owner();
- await begin(a);
- await database.exec("INSERT INTO fixture_faults VALUES ('lease-takeover')");
- await recover();
- assert.equal((await status(a)).phase, 'compute');
- assert.equal((await row(a)).lease_token, 'replacement');
- assert.deepEqual(
- (await calls()).map(({ phase }) => phase),
- ['compute'],
- );
- await database.exec('DELETE FROM fixture_faults');
- now += 60_001;
- await recover();
- assert.equal((await status(a)).state, 'complete');
-});
-
-test('a timed-out cleanup keeps the deletion pending and its late completion cannot advance it', async () => {
- const a = await owner();
- await begin(a);
- await database.exec("INSERT INTO fixture_faults VALUES ('held-compute')");
- // Exercise the real 20-second production deadline, not a shortened fixture.
- const started = Date.now();
- await recover();
- assert(Date.now() - started < 26_000);
- assert.equal((await status(a)).phase, 'compute');
- assert.equal((await account(a)).state, 'deleting');
- const releasedBy = Date.now() + 2000;
- while (
- !(await calls()).some(({ phase }) => phase === 'compute-returned') &&
- Date.now() < releasedBy
- )
- await new Promise((resolve) => setTimeout(resolve, 10));
- assert.deepEqual(
- (await calls()).map(({ phase }) => phase),
- ['compute', 'compute-returned'],
- );
- assert.equal((await status(a)).phase, 'compute');
- await database.exec('DELETE FROM fixture_faults');
- now += 60_001;
- await recover();
- assert.equal((await status(a)).state, 'complete');
-});
-
-test('failed final erasure rolls back identity removal and cannot claim completion', async () => {
- const a = await owner();
- await begin(a);
- await database.exec(
- "CREATE TRIGGER prevent_account_delete BEFORE DELETE ON kiln_accounts BEGIN SELECT RAISE(ABORT,'fixture'); END",
- );
- try {
- await recover();
- assert.equal((await status(a)).phase, 'identity');
- assert.equal((await status(a)).state, 'pending');
- assert.equal((await account(a)).state, 'deleting');
- assert.ok(
- await database
- .prepare('SELECT 1 FROM kiln_identities WHERE account_id=?')
- .bind(a.proof.accountId)
- .first(),
- );
- } finally {
- await database.exec('DROP TRIGGER prevent_account_delete');
- }
- now += 60_001;
- await recover();
- assert.equal((await status(a)).state, 'complete');
-});
diff --git a/hosting/test/deployment-config.test.mjs b/hosting/test/deployment-config.test.mjs
deleted file mode 100644
index 0104cf60..00000000
--- a/hosting/test/deployment-config.test.mjs
+++ /dev/null
@@ -1,387 +0,0 @@
-import assert from 'node:assert/strict';
-import { test } from 'node:test';
-import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
-import { resolve, sep } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { execFile } from 'node:child_process';
-import { promisify } from 'node:util';
-import { createHash } from 'node:crypto';
-import { deploymentConfig } from '../scripts/deployment-config.mjs';
-
-function fixture() {
- return {
- account: 'a'.repeat(32),
- prefix: 'kiln-qualification-v1',
- origin: 'https://kiln.instruktlabs.com',
- database: {
- id: '12345678-1234-4234-8234-123456789abc',
- name: 'kiln-qualification-v1-accounts',
- },
- oauthKv: 'b'.repeat(32),
- bucket: 'kiln-qualification-v1-artifacts',
- images: {
- coordinator: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-coordinator@sha256:${'c'.repeat(64)}`,
- software: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-software@sha256:${'d'.repeat(64)}`,
- },
- compute: {
- maxConcurrent: 1,
- tenantPerMinute: 9,
- tenantPerDay: 9,
- globalPerDay: 9,
- globalPerMonth: 9,
- deadlineMs: 120000,
- },
- storage: { maxBytes: 67108864, maxObjects: 256, maxGroups: 64 },
- requestLimits: {
- edge: { namespace: '1001', perMinute: 600 },
- account: { namespace: '1002', perMinute: 120 },
- },
- };
-}
-
-test('the complete deployment has separate gateway, storage, admission and three native services', () => {
- const result = deploymentConfig(fixture());
- assert.deepEqual(Object.keys(result.workers).sort(), [
- 'admission',
- 'evaluation',
- 'gateway',
- 'render',
- 'request',
- 'tenant',
- ]);
- const { gateway, tenant, admission, request, evaluation, render } = result.workers;
- assert.deepEqual(gateway.env.ACCOUNTS, { type: 'd1', ...fixture().database });
- assert.deepEqual(gateway.env.OAUTH_KV, { type: 'kv', id: fixture().oauthKv });
- assert.deepEqual(gateway.env.OPERATIONS, {
- type: 'analytics-engine-dataset',
- name: 'kiln_qualification_v1_ops',
- });
- assert.deepEqual(result.wrangler.gateway.analytics_engine_datasets, [
- { binding: 'OPERATIONS', dataset: 'kiln_qualification_v1_ops' },
- ]);
- assert.deepEqual(gateway.env.NATIVE_COMPUTE, {
- type: 'worker',
- worker: admission.name,
- exportName: 'KilnCompute',
- });
- assert.deepEqual(gateway.env.TENANTS, {
- type: 'durable-object',
- worker: tenant.name,
- exportName: 'KilnTenant',
- });
- assert.deepEqual(admission.env.REQUESTS, {
- type: 'durable-object',
- worker: request.name,
- exportName: 'KilnNativeRequest',
- });
- assert.deepEqual(request.env.EVALUATIONS, {
- type: 'durable-object',
- worker: evaluation.name,
- exportName: 'KilnEvaluationJob',
- });
- assert.deepEqual(request.env.RENDERS, {
- type: 'durable-object',
- worker: render.name,
- exportName: 'KilnRenderJob',
- });
- assert.deepEqual(request.env.TENANTS, gateway.env.TENANTS);
- assert.deepEqual(tenant.env.ARTIFACTS, { type: 'r2', name: fixture().bucket });
- assert.deepEqual(gateway.triggers, [{ type: 'scheduled', schedule: '* * * * *' }]);
- assert.equal(gateway.env.PUBLIC_ORIGIN.value, fixture().origin);
- assert.equal(request.env.PUBLIC_ORIGIN.value, fixture().origin);
- assert.equal(admission.env.COMPUTE_GLOBAL_PER_MONTH.value, '9');
- assert.equal(tenant.env.STORAGE_MAX_BYTES.value, '67108864');
-});
-
-test('prepared alert queries require an exact dataset and account without enabling delivery', () => {
- const plan = deploymentConfig(fixture()).monitoring;
- assert.equal(plan.configured, false);
- assert.equal(plan.destination, null);
- assert.equal(plan.dataset, 'events.analyticsEngine.kiln_qualification_v1_ops');
- assert.equal(plan.alerts.length, 6);
- for (const alert of plan.alerts) {
- assert(alert.query.startsWith('SELECT COUNT(*) AS value\n'));
- assert(alert.query.includes(`FROM ${plan.dataset}\n`));
- assert(alert.query.includes(`accountTag = '${fixture().account}'`));
- assert(alert.query.includes("timestamp >= NOW() - INTERVAL '5' MINUTE"));
- assert(alert.query.includes("blob1 = 'kiln.ops.v1'"));
- assert(!alert.query.endsWith(';'));
- assert.equal(alert.executionIntervalMinutes, 1);
- assert.equal(alert.repeatIntervalMinutes, 60);
- }
- const heartbeats = plan.alerts.filter((a) => a.name.endsWith('heartbeat'));
- assert.equal(heartbeats.length, 2);
- for (const alert of heartbeats) {
- assert.equal(alert.comparison, '<');
- assert.equal(alert.threshold, 1);
- // An aggregate without GROUP BY retains a zero row for missing heartbeat.
- assert(!alert.query.includes('GROUP BY'));
- }
-});
-
-test('configuration contains secret names only and exposes no operator, native or HTTP access', () => {
- const result = deploymentConfig(fixture());
- for (const [role, worker] of Object.entries(result.workers)) {
- assert.equal(worker.workersDev, false);
- assert.equal(worker.previewUrls, false);
- assert.deepEqual(worker.domains, []);
- assert(worker.compatibilityFlags.includes('global_fetch_strictly_public'));
- assert.equal(worker.observability.logs.invocationLogs, false);
- assert.equal(worker.observability.logs.enabled, false);
- assert.equal(worker.observability.traces.enabled, false);
- if (role !== 'gateway') {
- assert.equal(worker.env.OPERATIONS, undefined);
- assert.deepEqual(worker.triggers, []);
- for (const name of Object.keys(worker.env))
- assert(!/ACCOUNTS|OAUTH|GOOGLE|GITHUB/.test(name));
- }
- for (const value of Object.values(worker.env))
- assert.notEqual(value.exportName, 'KilnComputeControl');
- }
- for (const name of [
- 'GOOGLE_CLIENT_ID',
- 'GOOGLE_CLIENT_SECRET',
- 'GITHUB_CLIENT_ID',
- 'GITHUB_CLIENT_SECRET',
- ])
- assert.deepEqual(result.workers.gateway.env[name], { type: 'secret' });
- for (const container of Object.values(result.containers)) {
- assert.equal(container.ssh.enabled, false);
- assert.equal(container.observability.logs.enabled, false);
- assert.equal(container.schedulingPolicy, 'durable-object');
- for (const image of Object.values(container.images))
- assert.match(image.reference, /@sha256:[a-f0-9]{64}$/);
- }
-});
-
-test('offline preparation builds actual role-specific bundles and migrations without overwriting evidence', async () => {
- const cache = fileURLToPath(new URL('../../.cache/', import.meta.url));
- const directory = await mkdtemp(resolve(cache, 'deployment-config-test-'));
- assert(directory.startsWith(resolve(cache) + sep));
- try {
- const manifest = resolve(directory, 'manifest.json'),
- output = resolve(directory, 'candidate');
- await writeFile(manifest, JSON.stringify(fixture()));
- const args = [
- fileURLToPath(new URL('../scripts/prepare-deployment.mjs', import.meta.url)),
- '--manifest',
- manifest,
- '--output',
- output,
- ];
- const { stdout } = await promisify(execFile)(process.execPath, args);
- const receipt = JSON.parse(stdout);
- assert.equal(receipt.deployed, false);
- assert.equal(receipt.publicHttp, false);
- assert.equal(receipt.resourcesCreated, false);
- assert.equal(receipt.workers.length, 6);
- assert.equal(receipt.migrations.length, 9);
- assert(receipt.files.some((file) => file.path === 'monitoring-candidate.json'));
- assert.equal(new Set(receipt.files.map((file) => file.path)).size, receipt.files.length);
- for (const file of receipt.files) {
- const bytes = await readFile(resolve(output, file.path));
- assert.equal(createHash('sha256').update(bytes).digest('hex'), file.sha256);
- assert.equal(bytes.length, file.bytes);
- }
- for (const role of ['gateway', 'tenant', 'admission', 'request', 'evaluation', 'render'])
- assert(receipt.files.some((file) => file.path === `${role}.wrangler.json`));
- for (const worker of receipt.workers) {
- const bytes = await readFile(resolve(output, worker.bundle));
- assert.equal(createHash('sha256').update(bytes).digest('hex'), worker.sha256);
- assert(
- worker.inputs.every(
- (input) => !/(?:^|\/)(?:test|probe)\//.test(input.replaceAll('\\', '/')),
- ),
- );
- if (worker.role !== 'gateway')
- assert(
- !worker.inputs.some((input) => /oauth|\/auth\.ts/.test(input.replaceAll('\\', '/'))),
- );
- const config = JSON.parse(await readFile(resolve(output, `${worker.role}.wrangler.json`)));
- assert.equal(resolve(output, config.main), resolve(output, worker.bundle));
- }
- for (const migration of receipt.migrations)
- assert.equal(
- createHash('sha256')
- .update(await readFile(resolve(output, 'migrations', migration.name)))
- .digest('hex'),
- migration.sha256,
- );
- assert.deepEqual(
- JSON.parse(await readFile(resolve(output, 'deployment-receipt.json'))),
- receipt,
- );
- await assert.rejects(promisify(execFile)(process.execPath, args));
- assert.deepEqual(
- JSON.parse(await readFile(resolve(output, 'deployment-receipt.json'))),
- receipt,
- );
- await writeFile(
- manifest,
- JSON.stringify({ ...fixture(), secret: 'unintended-sensitive-input' }),
- );
- await assert.rejects(
- promisify(execFile)(process.execPath, [...args.slice(0, -1), resolve(directory, 'invalid')]),
- (error) => !`${error.stdout}${error.stderr}`.includes('unintended-sensitive-input'),
- );
- } finally {
- await rm(directory, { recursive: true, force: true });
- }
-});
-
-test('Wrangler conversion keeps self bindings local and external bindings explicit', () => {
- const result = deploymentConfig(fixture());
- for (const [role, config] of Object.entries(result.wrangler)) {
- const worker = result.workers[role];
- assert.equal(config.account_id, fixture().account);
- assert.deepEqual(config.routes, []);
- assert.equal(config.workers_dev, false);
- assert.equal(config.preview_urls, false);
- for (const binding of config.durable_objects?.bindings ?? []) {
- const target = worker.env[binding.name];
- assert.equal(binding.class_name, target.exportName);
- assert.equal(binding.script_name, target.worker === worker.name ? undefined : target.worker);
- }
- for (const binding of config.services ?? []) {
- assert.equal(binding.service, worker.env[binding.binding].worker);
- assert.equal(binding.entrypoint, worker.env[binding.binding].exportName);
- }
- }
- assert.deepEqual(result.wrangler.gateway.triggers, { crons: ['* * * * *'] });
- assert.equal(result.wrangler.gateway.d1_databases[0].database_id, fixture().database.id);
- assert.equal(result.wrangler.gateway.kv_namespaces[0].id, fixture().oauthKv);
- for (const [role, image] of [
- ['request', 'coordinator'],
- ['evaluation', 'kiln'],
- ['render', 'renderer'],
- ])
- assert.equal(
- result.wrangler[role].containers[0].images[image].image,
- fixture().images[role === 'request' ? 'coordinator' : 'software'],
- );
-});
-
-test('gateway limits are explicit, isolated namespaces with one-minute windows', () => {
- const result = deploymentConfig(fixture());
- for (const [role, worker] of Object.entries(result.workers)) {
- for (const [kind, name] of [
- ['edge', 'EDGE_REQUEST_LIMIT'],
- ['account', 'ACCOUNT_REQUEST_LIMIT'],
- ]) {
- if (role !== 'gateway') {
- assert.equal(worker.env[name], undefined);
- continue;
- }
- const policy = fixture().requestLimits[kind];
- assert.deepEqual(worker.env[name], {
- type: 'rate-limit',
- namespace: policy.namespace,
- simple: { limit: policy.perMinute, period: 60 },
- });
- assert.deepEqual(
- result.wrangler.gateway.ratelimits.find((x) => x.name === name),
- {
- name,
- namespace_id: policy.namespace,
- simple: { limit: policy.perMinute, period: 60 },
- },
- );
- }
- }
- for (const mutate of [
- (x) => {
- delete x.requestLimits;
- },
- (x) => {
- x.requestLimits.account.namespace = x.requestLimits.edge.namespace;
- },
- (x) => {
- x.requestLimits.edge.namespace = '0';
- },
- (x) => {
- x.requestLimits.edge.namespace = '1\n';
- },
- (x) => {
- x.requestLimits.edge.namespace = '01';
- },
- (x) => {
- x.requestLimits.edge.namespace = '9007199254740992';
- },
- (x) => {
- x.requestLimits.edge.perMinute = 0;
- },
- (x) => {
- x.requestLimits.edge.perMinute = 1.1;
- },
- (x) => {
- x.requestLimits.edge.perMinute = Infinity;
- },
- (x) => {
- x.requestLimits.edge.period = 10;
- },
- ]) {
- const manifest = fixture();
- mutate(manifest);
- assert.throws(() => deploymentConfig(manifest), /Invalid deployment manifest/);
- }
-});
-
-test('unknown fields, secret values, unbounded policies and mutable or foreign images are rejected', () => {
- for (const mutate of [
- (x) => {
- x.secret = 'must-not-be-serialized';
- },
- (x) => {
- x.routes = ['*'];
- },
- (x) => {
- x.compute.unlimited = true;
- },
- (x) => {
- x.database.secret = 'must-not-be-serialized';
- },
- (x) => {
- x.origin += '/';
- },
- (x) => {
- x.origin = 'http://kiln.instruktlabs.com';
- },
- (x) => {
- x.prefix = '../foreign';
- },
- (x) => {
- x.bucket = 'unrelated-assets';
- },
- (x) => {
- x.database.id = '';
- },
- (x) => {
- x.oauthKv = '';
- },
- (x) => {
- x.compute.maxConcurrent = 17;
- },
- (x) => {
- x.compute.deadlineMs = 120001;
- },
- (x) => {
- x.compute.globalPerMonth = Infinity;
- },
- (x) => {
- x.compute.tenantPerDay = 0;
- },
- (x) => {
- x.storage.maxBytes = -1;
- },
- (x) => {
- x.images.coordinator = `${x.images.coordinator.split('@')[0]}:latest`;
- },
- (x) => {
- x.images.software = x.images.software.replace(x.account, '0'.repeat(32));
- },
- ]) {
- const input = fixture();
- mutate(input);
- assert.throws(() => deploymentConfig(input), /Invalid deployment/);
- }
-});
diff --git a/hosting/test/edge-mcp.test.mjs b/hosting/test/edge-mcp.test.mjs
deleted file mode 100644
index 9b2c2b98..00000000
--- a/hosting/test/edge-mcp.test.mjs
+++ /dev/null
@@ -1,193 +0,0 @@
-import assert from 'node:assert/strict';
-import { readFile } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { before, after, test } from 'node:test';
-import { build } from 'esbuild';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-import { generateEdgeManifest } from '../scripts/edge-manifest.mjs';
-import { createKilnToolHost } from '../../dist/mcp-engine.mjs';
-import { createPublicTools, hostedInstructions } from '../src/public-tools.ts';
-
-let runtime, manifest;
-before(async () => {
- manifest = JSON.parse(
- await readFile(new URL('../src/generated/edge-manifest.json', import.meta.url), 'utf8'),
- );
- const bundle = await build({
- stdin: {
- contents: `
- import {routeEdgeMcp} from './src/edge-mcp';
- export default {async fetch(request){const routed=await routeEdgeMcp(request);return routed instanceof Response?routed:new Response('compute',{status:599});}};
- `,
- resolveDir: fileURLToPath(new URL('../', import.meta.url)),
- loader: 'ts',
- },
- bundle: true,
- write: false,
- metafile: true,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- });
- assert.equal(
- Object.keys(bundle.metafile?.inputs ?? {}).some((p) => p.includes('mcp-engine')),
- false,
- );
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- outboundService: async () => {
- throw Error('No network');
- },
- }),
- );
-});
-after(async () => runtime?.dispose());
-const meta = {
- 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
- 'io.modelcontextprotocol/clientInfo': { name: 'edge-fixture', version: '1' },
- 'io.modelcontextprotocol/clientCapabilities': {},
-};
-function request(method, params = {}, modern = true, headers = {}) {
- return runtime.dispatchFetch('https://tenant.internal/mcp', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- 'mcp-protocol-version': modern ? '2026-07-28' : '2025-11-25',
- ...(modern
- ? { 'mcp-method': method, ...(params.name ? { 'mcp-name': params.name } : {}) }
- : {}),
- ...headers,
- },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method,
- params: { ...params, ...(modern ? { _meta: meta } : {}) },
- }),
- });
-}
-async function message(response) {
- const body = await response.text();
- return response.headers.get('content-type')?.includes('text/event-stream')
- ? body
- .split('\n')
- .filter((l) => l.startsWith('data:'))
- .map((l) => JSON.parse(l.slice(5)))
- .findLast((x) => x.id !== undefined)
- : JSON.parse(body);
-}
-test('committed metadata is regenerated from the actual native engine protocol', async () => {
- assert.deepEqual(manifest, await generateEdgeManifest());
- assert.equal(manifest.tools.length, 15);
-});
-test('modern metadata and legacy initialization expose the derived hosted contract without compute', async () => {
- for (const [method, key] of [
- ['tools/list', 'tools'],
- ['resources/list', 'resources'],
- ['resources/templates/list', 'resourceTemplates'],
- ]) {
- const r = await request(method);
- assert.equal(r.status, 200);
- assert.deepEqual(
- (await message(r)).result[key],
- key === 'tools' ? createPublicTools(manifest.tools).tools : manifest[key],
- );
- }
- const discover = await message(await request('server/discover'));
- assert.deepEqual(
- discover.result._meta['io.modelcontextprotocol/serverInfo'],
- manifest.serverInfo,
- );
- const legacy = await request(
- 'initialize',
- {
- protocolVersion: '2025-11-25',
- capabilities: {},
- clientInfo: { name: 'legacy', version: '1' },
- },
- false,
- );
- assert.equal(legacy.status, 200);
- const result = (await message(legacy)).result;
- assert.deepEqual(result.serverInfo, manifest.serverInfo);
- assert.deepEqual(result.capabilities, manifest.capabilities);
- assert.equal(result.instructions, hostedInstructions);
-});
-test('helper discovery uses the engine service and preserves exact compact results and errors', async () => {
- const native = createKilnToolHost();
- for (const args of [
- {},
- { query: 'wheel spokes' },
- { ids: ['createPart'] },
- { ids: ['shape:capture'] },
- { query: 1 },
- ]) {
- const r = await request('tools/call', { name: 'kiln_discover', arguments: args });
- assert.equal(r.status, 200);
- const actual = (await message(r)).result;
- const expected = await native.callTool('kiln_discover', args, {
- signal: new AbortController().signal,
- });
- assert.deepEqual(actual.content, expected.content);
- assert.equal(actual.isError, expected.isError);
- }
-});
-
-test('hosted discovery rejects local-only aliases and hostile keys without echoing private paths', async () => {
- for (const args of [
- { category: 'prop' },
- { 'C:/Users/private/input': true },
- { capabilities: true },
- ]) {
- const result = await message(
- await request('tools/call', { name: 'kiln_discover', arguments: args }),
- );
- assert.equal(result.error.code, -32602);
- assert.doesNotMatch(JSON.stringify(result), /C:\/Users|private\/input/);
- }
-});
-test('source operations, private resource reads and live host capabilities still require the admitted native path', async () => {
- assert.equal(
- (
- await request('tools/call', {
- name: 'kiln_render',
- arguments: { code: 'function build(){}' },
- })
- ).status,
- 599,
- );
- assert.equal((await request('resources/read', { uri: 'kiln://assets/private' })).status, 599);
- assert.equal(
- (await request('tools/call', { name: 'kiln_capabilities', arguments: {} })).status,
- 599,
- );
-});
-test('invalid and unknown protocol messages cannot start compute, including forged routing headers', async () => {
- assert.equal((await request('tools/call', { name: 'not_a_tool', arguments: {} })).status, 200);
- const r = await request('tools/list', {}, true, {
- 'mcp-method': 'tools/call',
- 'mcp-name': 'kiln_render',
- });
- assert.notEqual(r.status, 599);
- for (const body of [
- '{',
- '[]',
- JSON.stringify({ jsonrpc: '2.0', method: 'tools/call', params: { name: 'kiln_render' } }),
- ]) {
- const invalid = await runtime.dispatchFetch('https://tenant.internal/mcp', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- },
- body,
- });
- assert.notEqual(invalid.status, 599);
- }
- assert.equal((await runtime.dispatchFetch('https://tenant.internal/mcp')).status, 405);
-});
diff --git a/hosting/test/evaluation-request.test.mjs b/hosting/test/evaluation-request.test.mjs
deleted file mode 100644
index 6f340bec..00000000
--- a/hosting/test/evaluation-request.test.mjs
+++ /dev/null
@@ -1,214 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, test } from 'node:test';
-import { fileURLToPath } from 'node:url';
-import { build } from 'esbuild';
-
-let handleEvaluationRequest, handleRenderRequest;
-before(async () => {
- const output = new URL('../../.cache/hosted-evaluation-request/handler.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/evaluation-request.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ handleEvaluationRequest, handleRenderRequest } = await import(output));
-});
-
-function request(options = {}) {
- return new Request(options.url ?? 'http://kiln-evaluator.internal/evaluate', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'content-length': '2',
- 'x-kiln-deadline-ms': '30000',
- 'x-kiln-max-response-bytes': '4096',
- ...options.headers,
- },
- body: options.body ?? '{}',
- duplex: 'half',
- signal: options.signal,
- });
-}
-
-test('private rendering admits its own bounds but denies evaluation routes and caller authority', async () => {
- const url = 'http://kiln-renderer.internal/render';
- let calls = 0;
- const job = {
- run: async (bytes, controls) => {
- calls++;
- assert.equal(controls.maxResponseBytes, 20 * 1024 * 1024);
- return bytes;
- },
- };
- const valid = await handleRenderRequest(
- request({ url, headers: { 'x-kiln-max-response-bytes': String(20 * 1024 * 1024) } }),
- job,
- );
- assert.equal(valid.status, 200);
- assert.equal(await valid.text(), '{}');
- for (const options of [
- { url: 'http://kiln-evaluator.internal/evaluate' },
- { headers: { 'x-kiln-deadline-ms': '30001' } },
- { headers: { 'content-length': String(6 * 1024 * 1024 + 1) } },
- { headers: { 'x-kiln-max-response-bytes': String(20 * 1024 * 1024 + 1) } },
- { headers: { 'x-image': 'other' } },
- { headers: { authorization: 'Bearer PRIVATE' } },
- ]) {
- const result = await handleRenderRequest(request({ url, ...options }), job);
- assert(result.status >= 400);
- }
- assert.equal(calls, 1);
-});
-
-test('private evaluator forwards only bounded bytes and controls and waits for the job to settle', async () => {
- let entered, finish;
- const started = new Promise((resolve) => {
- entered = resolve;
- });
- const done = new Promise((resolve) => {
- finish = resolve;
- });
- let returned = false;
- const pending = handleEvaluationRequest(request(), {
- executionImage: () => `registry.cloudflare.com/fixture/kiln@sha256:${'a'.repeat(64)}`,
- async run(bytes, controls) {
- assert.equal(new TextDecoder().decode(bytes), '{}');
- assert.ok(controls.deadlineMs > 0 && controls.deadlineMs <= 30000);
- assert.equal(controls.maxResponseBytes, 4096);
- assert.deepEqual(Object.keys(controls).sort(), ['deadlineMs', 'maxResponseBytes', 'signal']);
- entered();
- await done;
- return new TextEncoder().encode('{"opaque":"engine validates this"}');
- },
- }).then((value) => {
- returned = true;
- return value;
- });
- await started;
- assert.equal(returned, false);
- finish();
- const result = await pending;
- assert.equal(result.status, 200);
- assert.equal(result.headers.get('cache-control'), 'no-store');
- assert.equal(result.headers.get('content-type'), 'application/json');
- assert.equal(result.headers.get('x-kiln-execution-image'), `sha256:${'a'.repeat(64)}`);
- const bytes = await result.arrayBuffer();
- assert.equal(Number(result.headers.get('content-length')), bytes.byteLength);
-});
-
-test('evaluator output cannot claim its own image identity or omit the host proof', async () => {
- for (const identity of [undefined, 'mutable:latest', `sha256:${'a'.repeat(64)}`]) {
- const result = await handleEvaluationRequest(request(), {
- run: async () => new TextEncoder().encode('{"image":"forged","ok":true}'),
- executionImage: () => identity,
- });
- assert.equal(result.status, 503);
- assert.equal(result.headers.get('x-kiln-execution-image'), null);
- }
- const forged = await handleEvaluationRequest(
- request({ headers: { 'x-kiln-execution-image': `sha256:${'a'.repeat(64)}` } }),
- { run: async () => assert.fail('caller identity must be rejected before execution') },
- );
- assert.equal(forged.status, 400);
-});
-
-test('private evaluator rejects authority, route and malformed limits before starting compute', async () => {
- let calls = 0;
- const job = {
- run: async () => {
- calls++;
- throw new Error('must not execute');
- },
- };
- for (const options of [
- { url: 'https://kiln-evaluator.internal/evaluate' },
- { url: 'http://kiln-evaluator.internal/evaluate?tenant=other' },
- { url: 'http://kiln-evaluator.internal/evaluate#fragment' },
- { url: 'http://kiln-evaluator.internal/other' },
- { headers: { authorization: 'Bearer PRIVATE' } },
- { headers: { cookie: 'PRIVATE' } },
- { headers: { 'x-tenant': 'other' } },
- { headers: { 'x-kiln-deadline-ms': '60001' } },
- { headers: { 'x-kiln-deadline-ms': '0' } },
- { headers: { 'x-kiln-deadline-ms': 'NaN' } },
- { headers: { 'x-kiln-max-response-bytes': '8388609' } },
- { headers: { 'content-length': '4194305' } },
- { headers: { 'content-length': '1' } },
- { headers: { 'content-type': 'text/plain' } },
- { body: 'x'.repeat(4 * 1024 * 1024 + 1) },
- { signal: AbortSignal.abort('PRIVATE') },
- ]) {
- const result = await handleEvaluationRequest(request(options), job);
- assert.ok(result.status >= 400, JSON.stringify(options));
- assert.doesNotMatch(await result.text(), /PRIVATE|other/);
- }
- assert.equal(calls, 0);
-});
-
-test('private evaluator propagates cancellation without reporting an unconfirmed cleanup as success', async () => {
- const abort = new AbortController();
- let entered, finish;
- const started = new Promise((resolve) => {
- entered = resolve;
- });
- const done = new Promise((resolve) => {
- finish = resolve;
- });
- let executionSignal,
- returned = false;
- const pending = handleEvaluationRequest(request({ signal: abort.signal }), {
- async run(_bytes, controls) {
- executionSignal = controls.signal;
- entered();
- await done;
- throw new Error('PRIVATE_CLEANUP_FAILURE');
- },
- }).then((value) => {
- returned = true;
- return value;
- });
- await started;
- abort.abort('PRIVATE_REASON');
- assert.equal(executionSignal.aborted, true);
- await new Promise((resolve) => setImmediate(resolve));
- assert.equal(returned, false);
- finish();
- const response = await pending;
- assert.equal(response.status, 503);
- assert.doesNotMatch(await response.text(), /PRIVATE/);
-});
-
-test('private evaluator rechecks output bounds and returns fixed errors for bad job output', async () => {
- for (const output of [new Uint8Array(), new Uint8Array(4097), 'PRIVATE', null]) {
- const response = await handleEvaluationRequest(request(), { run: async () => output });
- assert.equal(response.status, 503);
- assert.doesNotMatch(await response.text(), /PRIVATE/);
- }
-});
-
-test('reading a stalled request consumes the evaluation deadline without starting compute', async () => {
- let cancelled = false;
- let calls = 0;
- const body = new ReadableStream({
- cancel() {
- cancelled = true;
- },
- });
- const result = await handleEvaluationRequest(
- request({
- headers: { 'x-kiln-deadline-ms': '25' },
- body,
- }),
- {
- run: async () => {
- calls++;
- return new Uint8Array([1]);
- },
- },
- );
- assert.equal(result.status, 504);
- assert.equal(cancelled, true);
- assert.equal(calls, 0);
-});
diff --git a/hosting/test/gateway-preflight-worker.ts b/hosting/test/gateway-preflight-worker.ts
deleted file mode 100644
index 690fa228..00000000
--- a/hosting/test/gateway-preflight-worker.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { DurableObject } from 'cloudflare:workers';
-import { runGatewayPreflight, type PreflightEnv } from '../probe/gateway-preflight';
-
-export class PreflightFixture extends DurableObject<PreflightEnv> {
- async run() {
- return JSON.stringify(await runGatewayPreflight(this.ctx.storage, this.env));
- }
-}
-
-export default { fetch: () => new Response('Not found', { status: 404 }) };
diff --git a/hosting/test/gateway-preflight.test.mjs b/hosting/test/gateway-preflight.test.mjs
deleted file mode 100644
index b042a91f..00000000
--- a/hosting/test/gateway-preflight.test.mjs
+++ /dev/null
@@ -1,308 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-import { fileURLToPath } from 'node:url';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-import { deploymentConfig } from '../scripts/deployment-config.mjs';
-import { migrateAccounts } from './database.mjs';
-
-const origin = 'https://kiln-private-qualification.invalid';
-const manifest = {
- account: 'a'.repeat(32),
- prefix: 'kiln-preflight-fixture',
- origin,
- database: { id: '11111111-1111-1111-1111-111111111111', name: 'kiln-preflight-fixture-accounts' },
- oauthKv: 'b'.repeat(32),
- bucket: 'kiln-preflight-fixture-artifacts',
- requestLimits: {
- edge: { namespace: '8101', perMinute: 600 },
- account: { namespace: '8102', perMinute: 120 },
- },
- images: {
- coordinator: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-coordinator@sha256:${'c'.repeat(64)}`,
- software: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-software@sha256:${'d'.repeat(64)}`,
- },
- compute: {
- maxConcurrent: 1,
- tenantPerMinute: 9,
- tenantPerDay: 9,
- globalPerDay: 9,
- globalPerMonth: 9,
- deadlineMs: 120000,
- },
- storage: { maxBytes: 1048576, maxObjects: 32, maxGroups: 8 },
-};
-const configuration = deploymentConfig(manifest);
-const bundles = {};
-before(async () => {
- for (const [role, entry] of [
- ...Object.entries(configuration.entries),
- ['probe', '../test/gateway-preflight-worker'],
- ]) {
- const result = await build({
- entryPoints: [fileURLToPath(new URL(`../src/${entry}.ts`, import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- });
- bundles[role] = result.outputFiles[0].text;
- }
-});
-
-// Adapt the prepared production topology, not a hand-maintained copy of its links.
-// Miniflare does not qualify remote Analytics Engine, Cron or Container images.
-function worker(role) {
- const config = configuration.workers[role];
- const result = {
- name: config.name,
- modules: true,
- script: bundles[role],
- compatibilityDate: config.compatibilityDate,
- compatibilityFlags: config.compatibilityFlags,
- bindings: {},
- durableObjects: {},
- serviceBindings: {},
- kvNamespaces: {},
- d1Databases: {},
- r2Buckets: {},
- ratelimits: {},
- outboundService: () => {
- throw new Error('Network forbidden in private fixture');
- },
- };
- for (const [name, binding] of Object.entries(config.env)) {
- switch (binding.type) {
- case 'text':
- result.bindings[name] = binding.value;
- break;
- case 'durable-object':
- result.durableObjects[name] = {
- className: binding.exportName,
- scriptName: binding.worker,
- useSQLite: true,
- };
- break;
- case 'worker':
- result.serviceBindings[name] = { name: binding.worker, entrypoint: binding.exportName };
- break;
- case 'd1':
- result.d1Databases[name] = binding.id;
- break;
- case 'kv':
- result.kvNamespaces[name] = binding.id;
- break;
- case 'r2':
- result.r2Buckets[name] = binding.name;
- break;
- case 'rate-limit':
- result.ratelimits[name] = { namespace_id: binding.namespace, simple: binding.simple };
- break;
- case 'secret':
- case 'analytics-engine-dataset':
- break;
- default:
- assert.fail(`Unhandled binding type: ${binding.type}`);
- }
- }
- // Build Output declares namespace ownership through exports/migrations.
- // Miniflare v4 adaptation declares it through a local binding instead.
- for (const [name, exported] of Object.entries(config.exports))
- if (exported.type === 'durable-object')
- result.durableObjects[`REGISTER_${name}`] = { className: name, useSQLite: true };
- return result;
-}
-async function fixture(override = {}, fault) {
- const names = Object.fromEntries(
- Object.entries(configuration.workers).map(([role, config]) => [role, config.name]),
- );
- const runtime = new Miniflare(
- convertV4MiniflareOptions({
- workers: [
- {
- name: 'probe',
- modules: true,
- script: bundles.probe,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['global_fetch_strictly_public'],
- durableObjects: {
- RUN: { className: 'PreflightFixture', useSQLite: true },
- TENANTS: { className: 'KilnTenant', scriptName: names.tenant, useSQLite: true },
- },
- serviceBindings: {
- GATEWAY: names.gateway,
- COMPUTE: { name: names.admission, entrypoint: 'KilnCompute' },
- CONTROL: { name: names.admission, entrypoint: 'KilnComputeControl' },
- },
- d1Databases: { ACCOUNTS: manifest.database.id },
- kvNamespaces: { OAUTH_KV: manifest.oauthKv },
- r2Buckets: { ARTIFACTS: manifest.bucket },
- bindings: {
- PUBLIC_ORIGIN: origin,
- QUALIFICATION_MODE: 'isolated-synthetic-v1',
- ...override,
- },
- outboundService: () => {
- throw new Error('External identity providers must not be called');
- },
- },
- ...Object.keys(configuration.entries).map((role) => {
- const value = worker(role);
- if (fault === 'gateway-database' && role === 'gateway')
- value.d1Databases.ACCOUNTS = '22222222-2222-2222-2222-222222222222';
- return value;
- }),
- ],
- }),
- );
- try {
- const database = await runtime.getD1Database('ACCOUNTS', 'probe');
- await migrateAccounts(database);
- const namespace = await runtime.getDurableObjectNamespace('RUN', 'probe');
- const stub = namespace.get(namespace.idFromName('once'));
- return { runtime, database, run: { run: async () => JSON.parse(await stub.run()) } };
- } catch (error) {
- await runtime.dispose();
- throw error;
- }
-}
-
-test('private preflight uses real gateway, account authorities, tenant storage and compute control', async () => {
- const f = await fixture();
- try {
- assert.equal((await f.runtime.dispatchFetch('https://probe.invalid')).status, 404);
- const first = await Promise.all([f.run.run(), f.run.run()]);
- const receipt = first.find((value) => value.state === 'finished');
- assert(receipt);
- assert.equal(receipt.state, 'finished');
- assert.equal(receipt.passed, true, JSON.stringify(receipt));
- assert.equal(receipt.computePaused, true);
- assert.deepEqual(
- receipt.results.map(({ name, passed }) => [name, passed]),
- [
- ['fresh-resources', true],
- ['pause-native', true],
- ['metadata', true],
- ['synthetic-accounts', true],
- ['anonymous-denied', true],
- ['edge-discovery', true],
- ['oversized-denied', true],
- ['store-fixture', true],
- ['bearer-isolation', true],
- ['browser-isolation', true],
- ['revoke-connection', true],
- ['revoked-token-denied', true],
- ['other-account-preserved', true],
- ],
- );
- assert.doesNotMatch(
- JSON.stringify(receipt),
- /access_token|refresh_token|cookie|ka_[a-f0-9]|Bearer |source\.kiln|fixture-source/,
- );
- assert.equal(
- (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,
- 2,
- );
- assert.equal(
- (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_connections').first()).n,
- 2,
- );
- assert.equal(
- (
- await f.database
- .prepare("SELECT COUNT(*) AS n FROM kiln_connections WHERE state='revoked'")
- .first()
- ).n,
- 1,
- );
- const before = await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_connections').first();
- assert.deepEqual(await f.run.run(), receipt);
- assert.deepEqual(
- await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_connections').first(),
- before,
- );
- } finally {
- await f.runtime.dispose();
- }
-});
-
-test('a gateway bound to the wrong account database fails at token exchange and never retries provisioning', async () => {
- const f = await fixture({}, 'gateway-database');
- try {
- const first = await f.run.run();
- assert.equal(first.passed, false);
- assert.equal(first.computePaused, true);
- assert.deepEqual(first.results.at(-1), { name: 'synthetic-accounts', passed: false });
- assert.equal(first.results.length, 4);
- assert.equal(
- (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,
- 1,
- );
- assert.deepEqual(await f.run.run(), first);
- assert.equal(
- (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,
- 1,
- );
- assert.doesNotMatch(JSON.stringify(first), /token|cookie|ka_[a-f0-9]|SQL|D1_ERROR|Bearer /);
- } finally {
- await f.runtime.dispose();
- }
-});
-
-for (const seeded of ['accounts', 'oauth', 'artifacts'])
- test(`preflight refuses nonempty ${seeded} instead of altering existing data`, async () => {
- const f = await fixture();
- try {
- if (seeded === 'accounts')
- await f.database
- .prepare('INSERT INTO kiln_accounts(id,created_at) VALUES (?,0)')
- .bind(`ka_${'f'.repeat(32)}`)
- .run();
- if (seeded === 'oauth')
- await (await f.runtime.getKVNamespace('OAUTH_KV', 'probe')).put(
- 'existing',
- 'do-not-change',
- );
- if (seeded === 'artifacts')
- await (await f.runtime.getR2Bucket('ARTIFACTS', 'probe')).put('existing', 'do-not-change');
- const result = await f.run.run();
- assert.equal(result.passed, false);
- assert.equal(result.results.length, 1);
- assert.equal(result.results[0].name, 'fresh-resources');
- assert.equal(result.results[0].passed, false);
- assert.equal(
- (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,
- seeded === 'accounts' ? 1 : 0,
- );
- if (seeded === 'oauth')
- assert.equal(
- await (await f.runtime.getKVNamespace('OAUTH_KV', 'probe')).get('existing'),
- 'do-not-change',
- );
- if (seeded === 'artifacts')
- assert.equal(
- await (await (await f.runtime.getR2Bucket('ARTIFACTS', 'probe')).get('existing')).text(),
- 'do-not-change',
- );
- assert.deepEqual(await f.run.run(), result);
- } finally {
- await f.runtime.dispose();
- }
- });
-
-test('preflight refuses a production origin before accessing account storage', async () => {
- const f = await fixture({ PUBLIC_ORIGIN: 'https://kiln.instruktlabs.com' });
- try {
- const result = await f.run.run();
- assert.equal(result.passed, false);
- assert.equal(result.results.length, 0);
- assert.equal(
- (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,
- 0,
- );
- } finally {
- await f.runtime.dispose();
- }
-});
diff --git a/hosting/test/gateway.test.mjs b/hosting/test/gateway.test.mjs
deleted file mode 100644
index d215b70b..00000000
--- a/hosting/test/gateway.test.mjs
+++ /dev/null
@@ -1,234 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { before, after, test } from 'node:test';
-import { build } from 'esbuild';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-import { rateLimitBindings } from './rate-limit-bindings.mjs';
-
-let runtime;
-const origin = 'https://kiln.example.com',
- user = `ka_${'1'.repeat(32)}`;
-const nativeBody = JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method: 'tools/call',
- params: { name: 'kiln_validate', arguments: { code: 'function build(){}' } },
-});
-before(async () => {
- const bundle = await build({
- stdin: {
- contents: `
- import {forwardTenant} from './src/gateway';
- import {serviceFailure} from './src/http';
- export default {async fetch(request,bindings){
- const result=async(target,tenant,incoming)=>Response.json({target,tenant,path:new URL(incoming.url).pathname,headers:Object.fromEntries(incoming.headers),body:await incoming.text()});
- const env={ACCOUNT_REQUEST_LIMIT:bindings.ACCOUNT_REQUEST_LIMIT,TENANTS:{getByName:tenant=>({fetch:incoming=>result('storage',tenant,incoming)})}};
- if(!request.headers.has('x-fixture-no-compute'))env.NATIVE_COMPUTE={dispatch:(tenant,incoming)=>result('compute',tenant,incoming)};
- try{return await forwardTenant(request,env,{auth:{userId:'${user}',scope:['kiln:use']}},'${origin}');}catch(e){return serviceFailure(e);}
- }};`,
- resolveDir: fileURLToPath(new URL('../', import.meta.url)),
- loader: 'ts',
- },
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['global_fetch_strictly_public'],
- ratelimits: rateLimitBindings,
- }),
- );
-});
-after(async () => runtime?.dispose());
-
-test('authenticated MCP routes only to admission using a trusted account hash and stripped credentials', async () => {
- const response = await runtime.dispatchFetch(`${origin}/mcp`, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- authorization: 'Bearer fixture-secret',
- cookie: 'fixture=secret',
- 'x-tenant': 'other',
- 'mcp-protocol-version': '2025-11-25',
- },
- body: nativeBody,
- });
- assert.equal(response.status, 200);
- const body = await response.json();
- assert.equal(body.target, 'compute');
- assert.equal(body.path, '/mcp');
- assert.equal(body.body, nativeBody);
- assert.equal(
- body.tenant,
- createHash('sha256')
- .update(JSON.stringify(['kiln-tenant-v1', origin, user]))
- .digest('base64url'),
- );
- assert.equal(body.headers.authorization, undefined);
- assert.equal(body.headers.cookie, undefined);
- assert.equal(body.headers['x-tenant'], undefined);
- assert.equal(body.headers['mcp-protocol-version'], '2025-11-25');
-});
-
-test('missing compute binding fails closed while artifact downloads remain available without compute admission', async () => {
- const headers = { 'x-fixture-no-compute': '1' };
- assert.equal(
- (
- await runtime.dispatchFetch(`${origin}/mcp`, {
- method: 'POST',
- headers: { ...headers, 'content-type': 'application/json' },
- body: nativeBody,
- })
- ).status,
- 503,
- );
- const download = await runtime.dispatchFetch(`${origin}/mcp/artifacts/${'a'.repeat(32)}`, {
- headers,
- });
- assert.equal(download.status, 200);
- assert.equal((await download.json()).target, 'storage');
-});
-
-test('authenticated discovery and malformed messages never call storage or require native admission', async () => {
- for (const [method, params] of [
- ['tools/list', {}],
- ['tools/call', { name: 'kiln_discover', arguments: { query: 'wheel' } }],
- ]) {
- const response = await runtime.dispatchFetch(`${origin}/mcp`, {
- method: 'POST',
- headers: {
- 'x-fixture-no-compute': '1',
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
- });
- assert.equal(response.status, 200);
- assert.equal(response.headers.get('cache-control'), 'no-store');
- const text = await response.text();
- assert.ok(!text.includes('"target":"compute"'));
- assert.ok(!text.includes('"target":"storage"'));
- assert.ok(text.includes(method === 'tools/list' ? '"tools":' : '"content":'));
- }
- const malformed = await runtime.dispatchFetch(`${origin}/mcp`, {
- method: 'POST',
- headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
- body: '{',
- });
- assert.equal(malformed.status, 400);
- assert.equal((await runtime.dispatchFetch(`${origin}/mcp`)).status, 405);
-});
-
-async function publicTool(name, args = {}, extraHeaders = {}) {
- return runtime.dispatchFetch(`${origin}/mcp`, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- 'mcp-protocol-version': '2025-11-25',
- ...extraHeaders,
- },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 7,
- method: 'tools/call',
- params: { name, arguments: args },
- }),
- });
-}
-
-test('public operations reach only their fixed engine action after credential stripping', async () => {
- for (const [name, args, engine, fixed] of [
- [
- 'kiln_material_create_procedural',
- { draft: { name: 'fixture' } },
- 'kiln_material',
- { action: 'create-procedural' },
- ],
- ['kiln_material_get', { materialId: 'stone' }, 'kiln_material', { action: 'get' }],
- ['kiln_assets_restore', { assetId: 'box' }, 'kiln_assets', { action: 'restore' }],
- ['kiln_renderer_status', {}, 'kiln_renderer', { action: 'status' }],
- ['kiln_capabilities', {}, 'kiln_discover', { capabilities: true }],
- ]) {
- const response = await publicTool(name, args, { authorization: 'Bearer fixture-secret' });
- assert.equal(response.status, 200);
- const forwarded = await response.json();
- assert.equal(forwarded.target, 'compute', name);
- assert.equal(forwarded.headers.authorization, undefined);
- assert.deepEqual(JSON.parse(forwarded.body), {
- jsonrpc: '2.0',
- id: 7,
- method: 'tools/call',
- params: { name: engine, arguments: { ...args, ...fixed } },
- });
- }
-});
-
-test('hidden selectors, unrelated fields and routing header mismatches never admit a native job', async () => {
- for (const [name, args, headers] of [
- ['kiln_material', { action: 'get', materialId: 'stone' }],
- ['kiln_assets', { action: 'restore', assetId: 'box' }],
- ['kiln_material_get', { materialId: 'stone', action: 'import' }],
- ['kiln_material_get', { materialId: 'stone', payload: {} }],
- ['kiln_capabilities', { query: 'wheel' }],
- ['kiln_discover', { capabilities: true }],
- [
- 'kiln_renderer_status',
- {},
- { 'mcp-method': 'tools/call', 'mcp-name': 'kiln_renderer_reprobe' },
- ],
- ['kiln_renderer_status', {}, { 'mcp-method': 'tools/list' }],
- ]) {
- const response = await publicTool(name, args, headers);
- const text = await response.text();
- assert.ok(!text.includes('"target":"compute"'), `${name}: ${text}`);
- assert.ok(text.includes('"error":') || text.includes('"isError":true'), text);
- }
-});
-
-test('modern operation translation preserves request metadata and rewrites matched routing headers', async () => {
- const name = 'kiln_material_get';
- const metadata = {
- 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
- 'io.modelcontextprotocol/clientInfo': { name: 'public-tools-fixture', version: '1' },
- 'io.modelcontextprotocol/clientCapabilities': {},
- };
- for (const headerName of [name, `=?base64?${Buffer.from(name).toString('base64')}?=`]) {
- const response = await runtime.dispatchFetch(`${origin}/mcp`, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- 'mcp-protocol-version': '2026-07-28',
- 'mcp-method': 'tools/call',
- 'mcp-name': headerName,
- },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 'modern-7',
- method: 'tools/call',
- params: {
- name,
- arguments: { materialId: 'stone' },
- _meta: metadata,
- },
- }),
- });
- const forwarded = await response.json();
- assert.equal(forwarded.target, 'compute');
- assert.equal(forwarded.headers['mcp-name'], 'kiln_material');
- assert.equal(forwarded.headers['mcp-method'], 'tools/call');
- const message = JSON.parse(forwarded.body);
- assert.equal(message.id, 'modern-7');
- assert.deepEqual(message.params._meta, metadata);
- assert.deepEqual(message.params.arguments, { materialId: 'stone', action: 'get' });
- }
-});
diff --git a/hosting/test/google-worker.ts b/hosting/test/google-worker.ts
deleted file mode 100644
index 8ea7bdb1..00000000
--- a/hosting/test/google-worker.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { googleAuthorizationUrl, googleIdentity, type GoogleEnv } from '../src/google';
-import { serviceFailure } from '../src/http';
-
-// Fixtures have no production entry or credentials. The real gateway must load
-// these values from its consumed browser-bound login intent, never from a caller.
-const flow = { state: 's'.repeat(43), verifier: 'v'.repeat(43), nonce: 'n'.repeat(43) };
-export default {
- async fetch(request: Request, env: GoogleEnv): Promise<Response> {
- try {
- const origin = 'https://kiln.example.com';
- if (new URL(request.url).pathname === '/start')
- return Response.json({
- url: await googleAuthorizationUrl(origin, flow, env, request.signal),
- });
- return Response.json(await googleIdentity(request, origin, flow, env));
- } catch (error) {
- return serviceFailure(error);
- }
- },
-} satisfies ExportedHandler<GoogleEnv>;
diff --git a/hosting/test/google.test.mjs b/hosting/test/google.test.mjs
deleted file mode 100644
index fb4329c5..00000000
--- a/hosting/test/google.test.mjs
+++ /dev/null
@@ -1,224 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash, generateKeyPairSync, sign } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-const origin = 'https://kiln.example.com';
-const issuer = 'https://accounts.google.com';
-const clientId = 'fixture-google-client';
-const state = 's'.repeat(43),
- verifier = 'v'.repeat(43),
- nonce = 'n'.repeat(43);
-const keys = generateKeyPairSync('rsa', { modulusLength: 2048 });
-const wrongKeys = generateKeyPairSync('rsa', { modulusLength: 2048 });
-const jwk = {
- ...keys.publicKey.export({ format: 'jwk' }),
- kid: 'fixture-key',
- alg: 'RS256',
- use: 'sig',
-};
-let runtime;
-let tokenCalls = 0;
-let metadataPatch = {};
-let jwksUnavailable = false;
-const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
-function idToken(mode) {
- const now = Math.floor(Date.now() / 1000);
- const claims = {
- iss: issuer,
- sub: 'immutable-google-subject',
- aud: clientId,
- iat: now,
- exp: now + 300,
- nonce,
- };
- if (mode === 'legacy-issuer') claims.iss = 'accounts.google.com';
- if (mode === 'wrong-issuer') claims.iss = 'https://foreign.example';
- if (mode === 'wrong-audience') claims.aud = 'another-client';
- if (mode === 'wrong-azp') claims.azp = 'another-client';
- if (mode === 'expired') claims.exp = now - 600;
- if (mode === 'wrong-nonce') claims.nonce = 'foreign-nonce';
- if (mode === 'missing-nonce') delete claims.nonce;
- if (mode === 'missing-subject') delete claims.sub;
- const header = { alg: mode === 'unsigned' ? 'none' : 'RS256', kid: 'fixture-key' };
- const input = `${encode(header)}.${encode(claims)}`;
- const signature =
- mode === 'unsigned'
- ? ''
- : sign(
- 'RSA-SHA256',
- Buffer.from(input),
- mode === 'wrong-signature' ? wrongKeys.privateKey : keys.privateKey,
- ).toString('base64url');
- return `${input}.${signature}`;
-}
-
-before(async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./google-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- bindings: {
- GOOGLE_CLIENT_ID: clientId,
- GOOGLE_CLIENT_SECRET: 'fixture-secret-not-a-credential',
- },
- outboundService: async (request) => {
- if (request.url === `${issuer}/.well-known/openid-configuration`) {
- assert.equal(request.method, 'GET');
- assert.equal(request.headers.get('authorization'), null);
- return Response.json({
- issuer,
- authorization_endpoint: `${issuer}/o/oauth2/v2/auth`,
- token_endpoint: 'https://oauth2.googleapis.com/token',
- jwks_uri: 'https://www.googleapis.com/oauth2/v3/certs',
- id_token_signing_alg_values_supported: ['RS256'],
- code_challenge_methods_supported: ['S256'],
- ...metadataPatch,
- });
- }
- if (request.url === 'https://oauth2.googleapis.com/token') {
- tokenCalls++;
- assert.equal(request.method, 'POST');
- const form = new URLSearchParams(await request.text());
- assert.equal(form.get('client_id'), clientId);
- assert.equal(form.get('client_secret'), 'fixture-secret-not-a-credential');
- assert.equal(form.get('code_verifier'), verifier);
- assert.equal(form.get('redirect_uri'), `${origin}/oauth/google/callback`);
- assert.equal(form.get('grant_type'), 'authorization_code');
- const mode = form.get('code');
- if (mode === 'outage')
- return new Response('private provider diagnostic', { status: 503 });
- if (mode === 'redirect')
- return new Response(null, {
- status: 302,
- headers: { location: 'https://foreign.example/steal' },
- });
- if (mode === 'oversize')
- return new Response('x'.repeat(70_000), {
- headers: { 'content-type': 'application/json' },
- });
- return Response.json({
- access_token: 'fixture-access-token',
- token_type: 'Bearer',
- expires_in: 300,
- ...(mode === 'missing-token' ? {} : { id_token: idToken(mode) }),
- });
- }
- if (request.url === 'https://www.googleapis.com/oauth2/v3/certs') {
- assert.equal(request.method, 'GET');
- assert.equal(request.headers.get('authorization'), null);
- return jwksUnavailable
- ? new Response('private JWKS diagnostic', { status: 503 })
- : Response.json({ keys: [jwk] });
- }
- throw new Error('Unexpected Google fixture request');
- },
- }),
- );
-});
-after(async () => runtime?.dispose());
-const callback = (code = 'valid', extra = '') =>
- runtime.dispatchFetch(`${origin}/oauth/google/callback?code=${code}&state=${state}${extra}`);
-
-test('Google authorization uses minimal scopes, exact callback, state, nonce and S256', async () => {
- const response = await runtime.dispatchFetch(`${origin}/start`);
- assert.equal(response.status, 200);
- const url = new URL((await response.json()).url);
- assert.equal(url.origin + url.pathname, `${issuer}/o/oauth2/v2/auth`);
- assert.equal(url.searchParams.get('client_id'), clientId);
- assert.equal(url.searchParams.get('scope'), 'openid profile');
- assert.equal(url.searchParams.get('redirect_uri'), `${origin}/oauth/google/callback`);
- assert.equal(url.searchParams.get('response_type'), 'code');
- assert.equal(url.searchParams.get('state'), state);
- assert.equal(url.searchParams.get('nonce'), nonce);
- assert.equal(url.searchParams.get('code_challenge_method'), 'S256');
- assert.equal(
- url.searchParams.get('code_challenge'),
- createHash('sha256').update(verifier).digest('base64url'),
- );
- assert.equal(url.searchParams.has('client_secret'), false);
- assert.equal(url.searchParams.has('access_type'), false);
-});
-
-test('both documented Google issuer spellings verify and produce one canonical identity without tokens', async () => {
- for (const code of ['valid', 'legacy-issuer']) {
- const response = await callback(code);
- assert.equal(response.status, 200);
- assert.deepEqual(await response.json(), { issuer, subject: 'immutable-google-subject' });
- }
-});
-
-test('invalid ID tokens fail issuer, audience, authorized-party, expiry, nonce and signature checks', async () => {
- for (const mode of [
- 'wrong-issuer',
- 'wrong-audience',
- 'wrong-azp',
- 'expired',
- 'wrong-nonce',
- 'missing-nonce',
- 'missing-subject',
- 'wrong-signature',
- 'unsigned',
- 'missing-token',
- ]) {
- const response = await callback(mode);
- assert.equal(response.status, 400, mode);
- assert.equal(await response.text(), 'Google sign-in failed; restart sign-in');
- }
-});
-
-test('state errors, duplicate codes, a foreign callback and provider denial stop before token exchange', async () => {
- const before = tokenCalls;
- for (const url of [
- `${origin}/oauth/google/callback?code=valid&state=foreign`,
- `${origin}/oauth/google/callback?code=valid`,
- `${origin}/oauth/google/callback?code=valid&code=other&state=${state}`,
- `${origin}/oauth/google/callback?error=access_denied&state=${state}`,
- `${origin}/oauth/github/callback?code=valid&state=${state}`,
- `https://foreign.example/oauth/google/callback?code=valid&state=${state}`,
- ])
- assert.equal((await runtime.dispatchFetch(url)).status, 400);
- assert.equal(tokenCalls, before);
-});
-
-test('discovery cannot redirect credentials or JWKS requests to a different service', async () => {
- const before = tokenCalls;
- try {
- for (const patch of [
- { issuer: 'https://foreign.example' },
- { token_endpoint: 'https://foreign.example/token' },
- { jwks_uri: 'http://127.0.0.1/keys' },
- { authorization_endpoint: 'https://foreign.example/authorize' },
- ]) {
- metadataPatch = patch;
- assert.equal((await callback()).status, 502);
- }
- } finally {
- metadataPatch = {};
- }
- assert.equal(tokenCalls, before);
-});
-
-test('provider outages, redirects and oversized responses fail without exposing diagnostic bodies', async () => {
- for (const mode of ['outage', 'redirect', 'oversize']) {
- const response = await callback(mode);
- assert.equal(response.status, 502, mode);
- assert.equal(await response.text(), 'Google sign-in provider unavailable; restart sign-in');
- }
- jwksUnavailable = true;
- try {
- assert.equal((await callback()).status, 502);
- } finally {
- jwksUnavailable = false;
- }
-});
diff --git a/hosting/test/http.test.mjs b/hosting/test/http.test.mjs
deleted file mode 100644
index 1bfcb32b..00000000
--- a/hosting/test/http.test.mjs
+++ /dev/null
@@ -1,71 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-
-let readBounded;
-let boundedRequest;
-before(async () => {
- const output = new URL('../../.cache/hosted-http-test/http.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/http.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ readBounded, boundedRequest } = await import(output));
-});
-
-test('public body admission honors an already cancelled incoming request', async () => {
- const controller = new AbortController();
- controller.abort(new Error('private cancellation reason'));
- const request = new Request('https://kiln.example.com/mcp', {
- method: 'POST',
- body: '{}',
- signal: controller.signal,
- });
- await assert.rejects(
- boundedRequest(request, 32),
- (error) => error.status === 499 && error.message === 'Request cancelled',
- );
-});
-
-test('public body reads enforce elapsed time even while chunks keep timers queued', async (t) => {
- let now = 1000;
- t.mock.method(Date, 'now', () => now);
- let pulls = 0;
- let cancelled = false;
- const body = new ReadableStream({
- pull(controller) {
- now += 6000;
- if (++pulls === 100) controller.close();
- else controller.enqueue(new Uint8Array());
- },
- cancel() {
- cancelled = true;
- },
- });
- await assert.rejects(
- readBounded(body, 32),
- (error) => error.status === 408 && error.message === 'Request timed out',
- );
- assert.ok(pulls < 100);
- assert.equal(cancelled, true);
-});
-
-test('bounded bodies retain bytes when a stream reuses its read buffer', async () => {
- const shared = new Uint8Array(1);
- let value = 0;
- const body = new ReadableStream(
- {
- pull(controller) {
- if (++value === 4) return controller.close();
- shared[0] = value;
- controller.enqueue(shared);
- },
- },
- { highWaterMark: 0 },
- );
- assert.deepEqual(await readBounded(body, 32), new Uint8Array([1, 2, 3]));
-});
diff --git a/hosting/test/integrated-probe.test.mjs b/hosting/test/integrated-probe.test.mjs
deleted file mode 100644
index 1653d74a..00000000
--- a/hosting/test/integrated-probe.test.mjs
+++ /dev/null
@@ -1,441 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-import { fileURLToPath } from 'node:url';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
-import { execFile } from 'node:child_process';
-import { promisify } from 'node:util';
-import { resolve, sep } from 'node:path';
-
-let IntegratedBudget, runIntegratedOnce, integratedSource, integratedCases;
-before(async () => {
- for (const name of ['integrated-budget', 'integrated-run']) {
- const output = new URL(`../../.cache/integrated-test/${name}.mjs`, import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL(`../probe/${name}.ts`, import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- const value = await import(output);
- if (name === 'integrated-budget') ({ IntegratedBudget } = value);
- else ({ runIntegratedOnce, integratedSource, integratedCases } = value);
- }
-});
-function storage() {
- const values = new Map();
- let tail = Promise.resolve();
- const api = {
- get: async (k) => structuredClone(values.get(k)),
- put: async (k, v) => {
- values.set(k, structuredClone(v));
- },
- transaction(fn) {
- const p = tail.then(() => fn(api));
- tail = p.catch(() => {});
- return p;
- },
- };
- return api;
-}
-test('the trial budget never reopens and bounds every kind across retries and reconstruction', async () => {
- const store = storage(),
- budget = new IntegratedBudget(store);
- await assert.rejects(budget.claim('coordinator', 'a'.repeat(64)));
- await budget.open();
- await assert.rejects(budget.open());
- for (const [kind, max] of [
- ['coordinator', 9],
- ['evaluation', 4],
- ['render', 4],
- ]) {
- for (let i = 0; i < max; i++) await budget.claim(kind, i.toString(16).padStart(64, '0'));
- await assert.rejects(budget.claim(kind, 'f'.repeat(64)));
- await assert.rejects(budget.claim(kind, '0'.repeat(64)));
- }
- assert.equal((await budget.status()).claims.length, 17);
- await budget.close();
- await assert.rejects(new IntegratedBudget(store).open());
- await assert.rejects(new IntegratedBudget(store).claim('render', 'e'.repeat(64)));
-});
-function fixture(failAt) {
- const calls = [],
- evidence = [];
- let paused = false,
- opened = 0,
- closed = 0;
- const ref = `p_${'a'.repeat(64)}`,
- asset = { assetId: 'fixture', revisionId: 'v1' };
- const text = (value) => ({ content: [{ type: 'text', text: JSON.stringify(value) }] });
- const ports = {
- open: async () => {
- opened++;
- },
- close: async () => {
- closed++;
- },
- pause: async () => {
- paused = true;
- },
- status: async () => ({ activeRequests: 0, pendingCleanup: 0, paused, maxConcurrent: 1 }),
- retain: async (name, bytes) => {
- evidence.push({ name, bytes });
- },
- async dispatch(owner, request) {
- const input = await request.json();
- calls.push({ owner, input });
- const index = calls.length;
- if (index === 10) return new Response('quota', { status: 429 });
- if (index === failAt) return new Response('private failure', { status: 503 });
- let result;
- if (index === 1)
- result = {
- ...text({
- ok: true,
- programRef: ref,
- viewFidelity: { delivered: 'full-material', degraded: false },
- }),
- content: [
- ...text({
- ok: true,
- programRef: ref,
- viewFidelity: { delivered: 'full-material', degraded: false },
- }).content,
- { type: 'image', data: 'cG5n', mimeType: 'image/png' },
- ],
- };
- if (index === 2) result = text({ ok: true, asset });
- if (index === 3) result = text({ ok: true, programRef: ref, asset });
- if (index === 4) result = text({ programRef: ref, code: integratedSource, nextOffset: null });
- if (index === 5) result = text({ ok: true, asset });
- if (index === 6)
- result = {
- contents: [
- { blob: Buffer.from('glTFfixture').toString('base64'), mimeType: 'model/gltf-binary' },
- ],
- };
- if (index === 7)
- result = {
- contents: [
- {
- text: JSON.stringify({
- assetId: 'fixture',
- revisionId: 'v1',
- preview: { fidelity: { delivered: 'full-material', degraded: false } },
- build: { engine: 'fixture-identity' },
- }),
- },
- ],
- };
- if (index === 8) result = { isError: true, content: [{ type: 'text', text: 'not found' }] };
- if (index === 9)
- return Response.json({
- jsonrpc: '2.0',
- id: input.id,
- error: { code: -32603, message: 'not found' },
- });
- return Response.json({ jsonrpc: '2.0', id: input.id, result });
- },
- };
- return {
- ports,
- calls,
- evidence,
- get opened() {
- return opened;
- },
- get closed() {
- return closed;
- },
- get paused() {
- return paused;
- },
- };
-}
-test('the fixed trial checks fresh-request lifecycle, tenant denial and quota rejection exactly once', async () => {
- const s = storage(),
- f = fixture();
- const first = await runIntegratedOnce(s, f.ports);
- assert.equal(first.passed, true);
- assert.equal(first.results.length, 10);
- assert.equal(f.calls.length, 10);
- assert.equal(f.opened, 1);
- assert.equal(f.closed, 1);
- assert.equal(f.paused, true);
- assert.equal(f.evidence.length, 10);
- assert.deepEqual(
- first.results.map((r) => r.name),
- integratedCases,
- );
- assert.notEqual(f.calls[0].owner, f.calls[7].owner);
- assert.deepEqual(await runIntegratedOnce(s, f.ports), first);
- assert.equal(f.calls.length, 10);
-});
-test('a failed case stops further requests and still closes the budget and pauses admission', async () => {
- const f = fixture(3),
- result = await runIntegratedOnce(storage(), f.ports);
- assert.equal(result.passed, false);
- assert.equal(f.calls.length, 3);
- assert.equal(f.closed, 1);
- assert.equal(f.paused, true);
- assert(!JSON.stringify(result).includes('private failure'));
-});
-test('unconfirmed final cleanup cannot produce a passing trial', async () => {
- const f = fixture();
- f.ports.status = async () => ({
- activeRequests: f.paused ? 1 : 0,
- pendingCleanup: f.paused ? 1 : 0,
- paused: f.paused,
- maxConcurrent: 1,
- });
- const result = await runIntegratedOnce(storage(), f.ports);
- assert.equal(result.passed, false);
- assert.equal(result.cleanupConfirmed, false);
-});
-
-async function workerFixture() {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('../probe/integrated-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- return new Miniflare({
- ...convertV4MiniflareOptions({
- workers: [
- {
- name: 'private-integration',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['enable_ctx_exports', 'enable_request_signal'],
- durableObjects: Object.fromEntries(
- Object.entries({
- RUN: 'KilnIntegratedRun',
- BUDGET: 'KilnIntegratedBudget',
- ADMISSION: 'KilnAdmission',
- TENANTS: 'KilnTenant',
- REQUESTS: 'IntegratedRequestJob',
- EVALUATIONS: 'IntegratedEvaluationJob',
- RENDERS: 'IntegratedRenderJob',
- }).map(([binding, className]) => [binding, { className, useSQLite: true }]),
- ),
- bindings: {
- PUBLIC_ORIGIN: 'https://kiln.instruktlabs.com',
- STORAGE_MAX_BYTES: '67108864',
- STORAGE_MAX_OBJECTS: '256',
- STORAGE_MAX_GROUPS: '64',
- COMPUTE_MAX_CONCURRENT: '1',
- COMPUTE_TENANT_PER_MINUTE: '9',
- COMPUTE_TENANT_PER_DAY: '9',
- COMPUTE_GLOBAL_PER_DAY: '9',
- COMPUTE_GLOBAL_PER_MONTH: '9',
- COMPUTE_DEADLINE_MS: '120000',
- },
- r2Buckets: ['ARTIFACTS'],
- outboundService: async () => {
- throw new Error('No external network in local trial fixture');
- },
- },
- {
- name: 'operator',
- modules: true,
- compatibilityDate: '2026-10-06',
- serviceBindings: {
- PROBE: { name: 'private-integration', entrypoint: 'KilnIntegratedControl' },
- },
- durableObjects: {
- REQUESTS: {
- className: 'IntegratedRequestJob',
- scriptName: 'private-integration',
- useSQLite: true,
- },
- },
- script: `export default {async fetch(request,env){
- switch(new URL(request.url).pathname) {
- case '/closed-budget-request': {
- let cancelled=false, denied=false;
- let stopped;
- const cancellation=new Promise(resolve=>{stopped=resolve;});
- const body=new ReadableStream({start(c){c.enqueue(new TextEncoder().encode('{}'));},cancel(){cancelled=true;stopped();}});
- const input=new Request('https://tenant.internal/mcp',{method:'POST',body});
- try{await env.REQUESTS.getByName('denied-budget').run('a'.repeat(43),input,Date.now()+60000);}catch{denied=true;}
- let timer;try{await Promise.race([cancellation,new Promise(resolve=>{timer=setTimeout(resolve,1000);})]);}finally{clearTimeout(timer);}
- return Response.json({cancelled,denied});
- }
- case '/status': return Response.json(await env.PROBE.status());
- case '/stop': return Response.json(await env.PROBE.stop());
- case '/run': return Response.json(await env.PROBE.runFixed());
- default: return env.PROBE.fetch(request);
- }
- }};`,
- },
- ],
- }),
- unsafeInspectDurableObjects: true,
- });
-}
-
-test('actual private RPC, admission and budget stop at a missing container and persist across eviction', async () => {
- const runtime = await workerFixture();
- try {
- const operator = await runtime.getWorker('operator');
- const rpc = async (path) => (await operator.fetch(`https://operator.invalid/${path}`)).json();
- assert.equal((await runtime.dispatchFetch('https://probe.invalid/run')).status, 404);
- assert.equal((await operator.fetch('https://operator.invalid/arbitrary')).status, 404);
- const first = await rpc('run');
- assert.equal(first.state, 'finished');
- assert.equal(first.passed, false);
- assert.equal(first.cleanupConfirmed, true);
- assert.equal(first.results.length, 1);
- assert.equal(first.results[0].name, 'render');
- assert.equal(first.results[0].status, 503);
- const status = await rpc('status');
- assert.deepEqual(status.admission, {
- paused: true,
- activeRequests: 0,
- pendingCleanup: 0,
- maxConcurrent: 1,
- });
- assert.equal(status.budget.state, 'closed');
- assert.equal(status.budget.claims.length, 1);
- assert.equal(status.budget.claims[0].kind, 'coordinator');
- const bucket = await runtime.getR2Bucket('ARTIFACTS', 'private-integration');
- assert.deepEqual(
- (await bucket.list()).objects.map((o) => o.key),
- ['probe-evidence/render.json'],
- );
- for (const [binding, className, name] of [
- ['RUN', 'KilnIntegratedRun', 'integrated-v1'],
- ['BUDGET', 'KilnIntegratedBudget', 'integrated-v1'],
- ['ADMISSION', 'KilnAdmission', 'global-v1'],
- ]) {
- const ns = await runtime.getDurableObjectNamespace(binding, 'private-integration');
- await runtime.unsafeEvictDurableObject('private-integration', className, {
- id: ns.idFromName(name).toString(),
- });
- }
- assert.deepEqual(await rpc('run'), first);
- assert.deepEqual(await rpc('stop'), status);
- } finally {
- await runtime.dispose();
- }
-});
-
-test('operator stop before the trial permanently closes its allowance without admitting a job', async () => {
- const runtime = await workerFixture();
- try {
- const operator = await runtime.getWorker('operator');
- const rpc = async (path) => (await operator.fetch(`https://operator.invalid/${path}`)).json();
- await rpc('stop');
- const result = await rpc('run');
- assert.equal(result.state, 'finished');
- assert.equal(result.passed, false);
- assert.equal(result.cleanupConfirmed, true);
- assert.deepEqual(result.results, []);
- const status = await rpc('status');
- assert.deepEqual(status.budget, { state: 'closed', claims: [] });
- assert.equal(status.admission.activeRequests, 0);
- assert.deepEqual(await rpc('closed-budget-request'), { cancelled: true, denied: true });
- assert.deepEqual((await rpc('status')).budget, status.budget);
- assert.deepEqual(await rpc('run'), result);
- } finally {
- await runtime.dispose();
- }
-});
-
-test('the prepared deployment keeps all execution private and pins bounded immutable images', async () => {
- const cache = fileURLToPath(new URL('../../.cache/', import.meta.url));
- const directory = await mkdtemp(resolve(cache, 'integrated-config-test-'));
- assert(directory.startsWith(resolve(cache) + sep));
- try {
- // Metadata fixture only: this does not install, authenticate or invoke cf.
- const metadata = resolve(directory, 'cf-package.json');
- await writeFile(metadata, JSON.stringify({ name: 'cf', version: '1.0.0-beta.12' }));
- const { stdout } = await promisify(execFile)(process.execPath, [
- fileURLToPath(new URL('../scripts/build-integrated-probe.mjs', import.meta.url)),
- '--account',
- '0'.repeat(32),
- '--output',
- directory,
- '--cf-package',
- metadata,
- ]);
- const receipt = JSON.parse(stdout);
- assert.equal(receipt.deployed, false);
- assert.deepEqual(receipt.maxVmStarts, { coordinator: 9, evaluation: 4, render: 4, total: 17 });
- const output = resolve(directory, '.cloudflare/output/v0');
- const worker = JSON.parse(
- await readFile(resolve(output, 'workers/default/worker.config.json')),
- );
- assert.equal(worker.workersDev, false);
- assert.equal(worker.previewUrls, false);
- assert.deepEqual(worker.domains, []);
- assert.deepEqual(worker.triggers, []);
- assert.equal(worker.env.ARTIFACTS.name, 'kiln-private-integrated-v1-evidence');
- assert.equal(worker.env.COMPUTE_MAX_CONCURRENT.value, '1');
- assert.equal(worker.env.COMPUTE_GLOBAL_PER_MONTH.value, '9');
- assert.equal(worker.env.COMPUTE_DEADLINE_MS.value, '120000');
- const wrangler = JSON.parse(await readFile(resolve(directory, 'wrangler.json')));
- assert.equal(wrangler.workers_dev, false);
- assert.equal(wrangler.preview_urls, false);
- assert.deepEqual(wrangler.routes, []);
- assert.equal(wrangler.account_id, '0'.repeat(32));
- assert.equal(
- resolve(directory, wrangler.main),
- resolve(output, 'workers/default/bundle/worker.mjs'),
- );
- assert.deepEqual(wrangler.exports, worker.exports);
- assert.equal(wrangler.durable_objects.bindings.length, 7);
- for (const binding of wrangler.durable_objects.bindings) {
- assert.equal(Object.hasOwn(binding, 'script_name'), false);
- assert.equal(binding.class_name, worker.env[binding.name].exportName);
- }
- assert.deepEqual(wrangler.limits, { cpu_ms: 30000, subrequests: 500 });
- for (const [key, binding] of Object.entries(worker.env))
- if (binding.type === 'text') assert.equal(wrangler.vars[key], binding.value);
- assert.deepEqual(wrangler.r2_buckets, [
- { binding: 'ARTIFACTS', bucket_name: worker.env.ARTIFACTS.name },
- ]);
- assert.equal(
- Object.values(worker.exports).filter((e) => e.type === 'durable-object').length,
- 7,
- );
- for (const [kind, key] of [
- ['coordinator', 'coordinator'],
- ['evaluation', 'kiln'],
- ['render', 'renderer'],
- ]) {
- const container = JSON.parse(
- await readFile(
- resolve(output, `containers/kiln-private-integrated-v1-${kind}/container.config.json`),
- ),
- );
- assert.equal(container.schedulingPolicy, 'durable-object');
- assert.equal(container.ssh.enabled, false);
- assert.equal(container.observability.logs.enabled, false);
- assert.deepEqual(Object.keys(container.images), [key]);
- assert.equal(
- container.images[key].reference,
- kind === 'coordinator' ? receipt.coordinator : receipt.software,
- );
- assert.match(container.images[key].reference, /@sha256:[a-f0-9]{64}$/);
- const deployed = wrangler.containers.find((item) => item.name === container.name);
- assert.equal(deployed.scheduling_policy, 'durable_object');
- assert.equal(deployed.ssh.enabled, false);
- assert.equal(deployed.observability.logs.enabled, false);
- assert.deepEqual(deployed.images, { [key]: { image: container.images[key].reference } });
- }
- assert(
- !receipt.inputs.some((input) =>
- /oauth|\/src\/(?:auth|github|google|browser-|account-)/.test(input.replaceAll('\\', '/')),
- ),
- );
- } finally {
- await rm(directory, { recursive: true, force: true });
- }
-});
diff --git a/hosting/test/lifecycle-config.test.mjs b/hosting/test/lifecycle-config.test.mjs
deleted file mode 100644
index 440f27a5..00000000
--- a/hosting/test/lifecycle-config.test.mjs
+++ /dev/null
@@ -1,143 +0,0 @@
-import assert from 'node:assert/strict';
-import { test } from 'node:test';
-import { mkdtemp, readFile, writeFile, rm, realpath } from 'node:fs/promises';
-import { createHash } from 'node:crypto';
-import { execFile } from 'node:child_process';
-import { promisify } from 'node:util';
-import { fileURLToPath } from 'node:url';
-import { resolve, sep } from 'node:path';
-import { lifecycleConfig } from '../probe/lifecycle-config.mjs';
-import { deploymentConfig } from '../scripts/deployment-config.mjs';
-import { assertLifecycleBoundary } from '../probe/lifecycle-build-boundary.mjs';
-import { lifecycleManifest } from './lifecycle-fixture.mjs';
-
-test('private bundles reject unexpected helpers and identity code in native roles', () => {
- for (const role of ['request', 'evaluation', 'render']) {
- assert.throws(() =>
- assertLifecycleBoundary(role, [
- `hosting/probe/lifecycle-${role}-worker.ts`,
- 'hosting/probe/qualification-accounts.ts',
- ]),
- );
- assert.throws(() => assertLifecycleBoundary(role, ['hosting/src/google.ts']));
- }
- for (const path of [
- 'hosting/test/fixture.ts',
- 'hosting/probe/unreviewed-helper.mjs',
- 'hosting/probe/nested/helper.ts',
- ])
- assert.throws(() => assertLifecycleBoundary('operator', [path]));
-});
-
-test('offline private lifecycle preparation hashes eight isolated bundles and refuses overwrite', async () => {
- const cache = await realpath(fileURLToPath(new URL('../../.cache/', import.meta.url)));
- const directory = await mkdtemp(resolve(cache, 'lifecycle-candidate-test-'));
- assert((await realpath(directory)).startsWith(cache + sep));
- try {
- const manifest = resolve(directory, 'manifest.json'),
- output = resolve(directory, 'candidate');
- await writeFile(manifest, JSON.stringify(lifecycleManifest));
- const args = [
- fileURLToPath(new URL('../scripts/prepare-deployment.mjs', import.meta.url)),
- '--private-lifecycle',
- '--manifest',
- manifest,
- '--output',
- output,
- ];
- const { stdout } = await promisify(execFile)(process.execPath, args);
- const receipt = JSON.parse(stdout);
- assert.equal(receipt.mode, 'private-lifecycle');
- assert.equal(receipt.workers.length, 8);
- assert.equal(receipt.migrations.length, 9);
- assert.deepEqual(receipt.requiredGatewaySecrets, []);
- assert.equal(receipt.deployed, false);
- assert.equal(receipt.publicHttp, false);
- for (const file of receipt.files) {
- const bytes = await readFile(resolve(output, file.path));
- assert.equal(createHash('sha256').update(bytes).digest('hex'), file.sha256);
- }
- for (const worker of receipt.workers) {
- const inputs = worker.inputs.join('\n');
- if (worker.role !== 'operator')
- assert.doesNotMatch(inputs, /qualification-accounts|gateway-preflight|lifecycle-run/);
- if (['request', 'evaluation', 'render'].includes(worker.role))
- assert.doesNotMatch(inputs, /oauth|\/auth\.ts/);
- }
- await assert.rejects(promisify(execFile)(process.execPath, args));
- assert.deepEqual(
- JSON.parse(await readFile(resolve(output, 'deployment-receipt.json'))),
- receipt,
- );
- } finally {
- assert((await realpath(directory)).startsWith(cache + sep));
- await rm(directory, { recursive: true });
- }
-});
-test('private lifecycle configuration preserves production boundaries and binds only native wrappers to its allowance', () => {
- const c = lifecycleConfig(lifecycleManifest),
- base = deploymentConfig(lifecycleManifest);
- assert.equal(Object.keys(c.workers).length, 8);
- for (const role of ['tenant', 'admission']) assert.deepEqual(c.workers[role], base.workers[role]);
- for (const role of ['request', 'evaluation', 'render']) {
- const copy = structuredClone(c.workers[role]);
- assert.equal(copy.env.BUDGET.worker, c.workers.allowance.name);
- assert.equal(copy.env.BUDGET.exportName, 'KilnLifecycleBudget');
- delete copy.env.BUDGET;
- assert.deepEqual(copy, base.workers[role]);
- assert.equal(c.entries[role], `../probe/lifecycle-${role}-worker`);
- assert(!c.workers[role].env.ACCOUNTS);
- }
- assert.equal(c.workers.operator.env.GATEWAY.worker, c.workers.gateway.name);
- assert.equal(c.workers.operator.env.EXPECTED_IMAGE.value, `sha256:${'d'.repeat(64)}`);
- assert.deepEqual(c.workers.operator.env.ACCOUNTS, c.workers.gateway.env.ACCOUNTS);
- assert.deepEqual(c.workers.operator.env.ARTIFACTS, c.workers.tenant.env.ARTIFACTS);
- for (const [role, w] of Object.entries(c.workers)) {
- assert.equal(w.workersDev, false);
- assert.equal(w.previewUrls, false);
- assert.deepEqual(w.domains, []);
- assert.deepEqual(w.triggers, []);
- assert.equal(w.observability.enabled, false);
- assert(!Object.values(w.env).some((binding) => binding.type === 'secret'));
- assert.deepEqual(c.wrangler[role].routes, []);
- }
- assert.deepEqual(c.containers, base.containers);
-});
-test('private lifecycle configuration refuses production targets and altered execution allowances', () => {
- for (const edit of [
- (m) => {
- m.origin = 'https://kiln.instruktlabs.com';
- },
- (m) => {
- m.prefix = 'kiln-production';
- },
- (m) => {
- m.compute.globalPerDay = 15;
- },
- (m) => {
- m.compute.deadlineMs = 60000;
- },
- (m) => {
- m.storage.maxBytes *= 2;
- },
- (m) => {
- m.requestLimits.edge.perMinute = 601;
- },
- ]) {
- const m = structuredClone(lifecycleManifest);
- edit(m);
- assert.throws(() => lifecycleConfig(m));
- }
-});
-
-test('private deployment orders every cross-worker dependency before its caller', () => {
- const c = lifecycleConfig(lifecycleManifest);
- const positions = new Map(c.deployOrder.map((role, index) => [c.workers[role].name, index]));
- for (const worker of Object.values(c.workers))
- for (const binding of Object.values(worker.env))
- if (binding.worker && binding.worker !== worker.name)
- assert(
- positions.get(binding.worker) < positions.get(worker.name),
- `${worker.name} -> ${binding.worker}`,
- );
-});
diff --git a/hosting/test/lifecycle-fixture.mjs b/hosting/test/lifecycle-fixture.mjs
deleted file mode 100644
index 6b4dcd3a..00000000
--- a/hosting/test/lifecycle-fixture.mjs
+++ /dev/null
@@ -1,28 +0,0 @@
-export const lifecycleManifest = {
- account: 'a'.repeat(32),
- prefix: 'kiln-private-lifecycle-v1',
- origin: 'https://kiln-private-qualification.invalid',
- database: {
- id: '11111111-1111-1111-1111-111111111111',
- name: 'kiln-private-lifecycle-v1-accounts',
- },
- oauthKv: 'b'.repeat(32),
- bucket: 'kiln-private-lifecycle-v1-artifacts',
- requestLimits: {
- edge: { namespace: '8201', perMinute: 600 },
- account: { namespace: '8202', perMinute: 120 },
- },
- images: {
- coordinator: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-coordinator@sha256:${'c'.repeat(64)}`,
- software: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-software@sha256:${'d'.repeat(64)}`,
- },
- compute: {
- maxConcurrent: 1,
- tenantPerMinute: 14,
- tenantPerDay: 14,
- globalPerDay: 14,
- globalPerMonth: 14,
- deadlineMs: 120000,
- },
- storage: { maxBytes: 67108864, maxObjects: 256, maxGroups: 64 },
-};
diff --git a/hosting/test/lifecycle-observer.test.mjs b/hosting/test/lifecycle-observer.test.mjs
deleted file mode 100644
index 8934b4d8..00000000
--- a/hosting/test/lifecycle-observer.test.mjs
+++ /dev/null
@@ -1,185 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, test } from 'node:test';
-import { fileURLToPath } from 'node:url';
-import { build } from 'esbuild';
-import { readFile } from 'node:fs/promises';
-
-let observer;
-before(async () => {
- const output = new URL('../../.cache/lifecycle-observer-test/observer.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../probe/lifecycle-observer.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- observer = (await import(output)).default;
-});
-const options = { method: 'POST', headers: { 'X-Kiln-Operator': 'private-lifecycle-v1' } };
-const invoke = (path, env, init = options) =>
- observer.fetch(new Request(`http://127.0.0.1:8798/${path}`, init), env);
-
-test('observer config stays loopback-only with exactly the fixed private control binding', async () => {
- const config = JSON.parse(
- await readFile(new URL('../probe/lifecycle-observer.wrangler.jsonc', import.meta.url), 'utf8'),
- );
- assert.deepEqual(config.dev, { ip: '127.0.0.1', port: 8798, local_protocol: 'http' });
- assert.equal(config.workers_dev, false);
- assert.equal(config.preview_urls, false);
- assert.deepEqual(config.routes, []);
- assert.deepEqual(config.observability, { enabled: false });
- assert.deepEqual(config.services, [
- {
- binding: 'PROBE',
- service: 'kiln-private-lifecycle-v1-operator',
- entrypoint: 'KilnLifecycleControl',
- remote: true,
- },
- ]);
-});
-
-test('loopback observer refuses browser traffic and arbitrary controls without calling RPC', async () => {
- const env = {
- PROBE: new Proxy(
- {},
- {
- get() {
- assert.fail('Unexpected control call');
- },
- },
- ),
- };
- for (const [url, init] of [
- ['http://127.0.0.1:8798/run-fixed', {}],
- ['http://127.0.0.1:8798/run-fixed', { method: 'POST' }],
- ['http://127.0.0.1:8798/run-fixed', { method: 'OPTIONS' }],
- ['http://attacker.invalid:8798/run-fixed', options],
- ['http://127.0.0.1:8799/run-fixed', options],
- ['http://127.0.0.1:8798/run-fixed?restart=1', options],
- ['http://127.0.0.1:8798/arbitrary', options],
- ...['Origin', 'Sec-Fetch-Site'].map((name) => [
- 'http://127.0.0.1:8798/run-fixed',
- { ...options, headers: { ...options.headers, [name]: 'https://attacker.invalid' } },
- ]),
- ])
- assert.equal((await observer.fetch(new Request(url, init), env)).status, 404);
-});
-
-test('observer forwards only fixed controls, releases RPC capabilities and sends private JSON', async () => {
- const calls = [],
- disposed = [];
- const env = {
- PROBE: Object.fromEntries(
- ['runFixed', 'status', 'stop'].map((action) => [
- action,
- (...args) => {
- assert.deepEqual(args, []);
- calls.push(action);
- const result = { state: 'finished', passed: true };
- Object.defineProperty(result, Symbol.dispose, {
- value: () => disposed.push(`${action}-result`),
- });
- const work = Promise.resolve(result);
- work[Symbol.dispose] = () => disposed.push(`${action}-promise`);
- return work;
- },
- ]),
- ),
- };
- for (const [path, action] of [
- ['run-fixed', 'runFixed'],
- ['status', 'status'],
- ['stop', 'stop'],
- ]) {
- const response = await invoke(path, env);
- assert.equal(response.status, 200);
- assert.equal(response.headers.get('cache-control'), 'no-store');
- assert.equal(response.headers.has('access-control-allow-origin'), false);
- assert.deepEqual(await response.json(), { state: 'finished', passed: true });
- assert.deepEqual(disposed.slice(-2), [`${action}-result`, `${action}-promise`]);
- }
- assert.deepEqual(calls, ['runFixed', 'status', 'stop']);
-});
-
-test('observer failures redact RPC errors and never issue another operation', async () => {
- let calls = 0,
- disposed = 0;
- const env = {
- PROBE: {
- runFixed() {
- calls++;
- const work = Promise.reject(new Error('PRIVATE_CREDENTIAL_OR_DOWNLOAD'));
- work[Symbol.dispose] = () => disposed++;
- return work;
- },
- },
- };
- const response = await invoke('run-fixed', env);
- assert.equal(response.status, 502);
- assert.doesNotMatch(await response.text(), /PRIVATE_CREDENTIAL_OR_DOWNLOAD/);
- assert.equal(calls, 1);
- assert.equal(disposed, 1);
-});
-
-test('observer cancels uploaded input, passes no arguments and refuses oversized receipts', async () => {
- let cancelled = false,
- disposed = 0;
- const body = new ReadableStream({
- cancel() {
- cancelled = true;
- },
- });
- const result = { unused: 'x'.repeat(128 * 1024) };
- Object.defineProperty(result, Symbol.dispose, { value: () => disposed++ });
- const response = await invoke(
- 'status',
- {
- PROBE: {
- status(...args) {
- assert.deepEqual(args, []);
- return Promise.resolve(result);
- },
- },
- },
- { ...options, body, duplex: 'half' },
- );
- assert.equal(cancelled, true);
- assert.equal(disposed, 1);
- assert.equal(response.status, 502);
- assert((await response.text()).length < 256);
-});
-
-test('observation deadlines release capabilities and discard late results without retry', async (t) => {
- t.mock.timers.enable({ apis: ['setTimeout'] });
- for (const [action, path, deadline] of [
- ['status', 'status', 10000],
- ['runFixed', 'run-fixed', 960000],
- ]) {
- let resolve,
- calls = 0,
- disposed = 0;
- const work = new Promise((done) => {
- resolve = done;
- });
- work[Symbol.dispose] = () => disposed++;
- const pending = invoke(path, {
- PROBE: {
- [action]() {
- calls++;
- return work;
- },
- },
- });
- t.mock.timers.tick(deadline);
- const response = await pending;
- assert.equal(response.status, 502);
- assert.equal(disposed, 1);
- const result = { state: 'finished' };
- Object.defineProperty(result, Symbol.dispose, { value: () => disposed++ });
- resolve(result);
- await new Promise((done) => setImmediate(done));
- assert.equal(disposed, 2);
- assert.equal(calls, 1);
- }
-});
diff --git a/hosting/test/lifecycle-probe.test.mjs b/hosting/test/lifecycle-probe.test.mjs
deleted file mode 100644
index 8490032d..00000000
--- a/hosting/test/lifecycle-probe.test.mjs
+++ /dev/null
@@ -1,147 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-import { fileURLToPath } from 'node:url';
-
-let LifecycleBudget, lifecycleBudget, runLifecycleOnce;
-before(async () => {
- for (const name of ['lifecycle-budget', 'lifecycle-run']) {
- const output = new URL(`../../.cache/lifecycle-tests/${name}.mjs`, import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL(`../probe/${name}.ts`, import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- const value = await import(output);
- if (name === 'lifecycle-budget') ({ LifecycleBudget, lifecycleBudget } = value);
- else ({ runLifecycleOnce } = value);
- }
-});
-function storage() {
- const values = new Map();
- let tail = Promise.resolve();
- const api = {
- get: async (key) => structuredClone(values.get(key)),
- put: async (key, value) => {
- values.set(key, structuredClone(value));
- },
- transaction(fn) {
- const next = tail.then(() => fn(api));
- tail = next.catch(() => {});
- return next;
- },
- };
- return api;
-}
-test('native lifecycle allowance cannot refund or reopen and bounds concurrent claims', async () => {
- const store = storage(),
- budget = new LifecycleBudget(store);
- await assert.rejects(budget.claim('coordinator', 'a'.repeat(64)));
- await budget.open();
- await assert.rejects(budget.open());
- for (const [kind, maximum] of Object.entries(lifecycleBudget)) {
- const results = await Promise.allSettled(
- Array.from({ length: maximum + 3 }, (_, i) =>
- budget.claim(kind, i.toString(16).padStart(64, '0')),
- ),
- );
- assert.equal(results.filter((result) => result.status === 'fulfilled').length, maximum);
- await assert.rejects(budget.claim(kind, '0'.repeat(64)));
- }
- assert.equal((await budget.status()).claims.length, 22);
- await budget.close();
- const reconstructed = new LifecycleBudget(store);
- await assert.rejects(reconstructed.open());
- await assert.rejects(reconstructed.claim('render', 'f'.repeat(64)));
-});
-test('closed or malformed native lifecycle allowances fail without allocating a claim', async () => {
- const stopped = new LifecycleBudget(storage());
- await stopped.close();
- await assert.rejects(stopped.open());
- const budget = new LifecycleBudget(storage());
- await budget.open();
- for (const kind of ['other', '__proto__', 'constructor'])
- await assert.rejects(budget.claim(kind, 'a'.repeat(64)));
- for (const id of ['', 'x'.repeat(64), `${'a'.repeat(64)}\n`])
- await assert.rejects(budget.claim('render', id));
- assert.equal((await budget.status()).claims.length, 0);
-});
-test('an interrupted native lifecycle record does not reopen or resume', async () => {
- const store = storage();
- const previous = { state: 'running', passed: false, results: [] };
- await store.put('native-lifecycle', previous);
- assert.deepEqual(
- await runLifecycleOnce(
- store,
- new Proxy(
- {},
- {
- get() {
- throw new Error('INTERRUPTED_RUN_TOUCHED_PORT');
- },
- },
- ),
- ),
- previous,
- );
-});
-function fixture() {
- let paused = true,
- calls = 0,
- retained = 0,
- closed = 0;
- const ports = {
- expectedImage: `sha256:${'b'.repeat(64)}`,
- open: async () => {
- paused = false;
- },
- close: async () => {
- closed++;
- },
- pause: async () => {
- paused = true;
- },
- status: async () => ({ paused, activeRequests: 0, pendingCleanup: 0 }),
- mcp: async () => {
- calls++;
- return new Response(new Uint8Array(8 * 1024 * 1024 + 1));
- },
- retain: async () => {
- retained++;
- },
- };
- return { ports, counts: () => ({ paused, calls, retained, closed }) };
-}
-test('native lifecycle stops before retaining an oversized response and seals admission', async () => {
- const f = fixture(),
- result = await runLifecycleOnce(storage(), f.ports);
- assert.equal(result.passed, false);
- assert.equal(result.admissionIdleAndPaused, true);
- assert.equal(result.results.length, 1);
- assert.deepEqual(f.counts(), { paused: true, calls: 1, retained: 0, closed: 1 });
-});
-// Exercise the production ten-second evidence deadline, not an injected shorter timeout.
-test('a stalled evidence write cannot resume a failed lifecycle after its deadline', {
- timeout: 20000,
-}, async () => {
- const f = fixture(),
- store = storage();
- let finish;
- f.ports.mcp = async () => new Response('{}');
- f.ports.retain = () =>
- new Promise((resolve) => {
- finish = resolve;
- });
- const started = Date.now();
- const result = await runLifecycleOnce(store, f.ports);
- assert(Date.now() - started >= 9500);
- assert.equal(result.passed, false);
- assert.equal(result.admissionIdleAndPaused, true);
- assert.equal(result.results.length, 1);
- assert.equal(f.counts().closed, 1);
- finish();
- await Promise.resolve();
- assert.deepEqual(await store.get('native-lifecycle'), result);
-});
diff --git a/hosting/test/lifecycle-readback.test.mjs b/hosting/test/lifecycle-readback.test.mjs
deleted file mode 100644
index 52d88524..00000000
--- a/hosting/test/lifecycle-readback.test.mjs
+++ /dev/null
@@ -1,472 +0,0 @@
-import assert from 'node:assert/strict';
-import { test } from 'node:test';
-import { createHash } from 'node:crypto';
-import { lifecycleConfig } from '../probe/lifecycle-config.mjs';
-import { lifecycleManifest } from './lifecycle-fixture.mjs';
-import { verifyLifecycleDeployment, planLifecycleCleanup } from '../probe/lifecycle-readback.mjs';
-
-const hash = (value) => createHash('sha256').update(value).digest('hex');
-const id = (value) => hash(value).slice(0, 32);
-function fixture() {
- const manifest = structuredClone(lifecycleManifest),
- config = lifecycleConfig(manifest);
- const namespaces = Object.values(config.workers).flatMap((w) =>
- Object.entries(w.exports)
- .filter(([, e]) => e.type === 'durable-object')
- .map(([name]) => ({
- id: id(w.name + name),
- script: w.name,
- class: name,
- use_sqlite: true,
- })),
- );
- const ns = (worker, name) => namespaces.find((n) => n.script === worker && n.class === name);
- const bindings = (w) =>
- Object.entries(w.env).map(([name, b]) => {
- switch (b.type) {
- case 'text':
- return { name, type: 'plain_text', text: b.value };
- case 'worker':
- return {
- name,
- type: 'service',
- service: b.worker,
- ...(b.exportName ? { entrypoint: b.exportName } : {}),
- };
- case 'durable-object':
- return {
- name,
- type: 'durable_object_namespace',
- namespace_id: ns(b.worker, b.exportName).id,
- class_name: b.exportName,
- };
- case 'd1':
- return { name, type: 'd1', id: b.id };
- case 'kv':
- return { name, type: 'kv_namespace', namespace_id: b.id };
- case 'r2':
- return { name, type: 'r2_bucket', bucket_name: b.name };
- case 'rate-limit':
- return { name, type: 'ratelimit', namespace_id: b.namespace, simple: b.simple };
- case 'analytics-engine-dataset':
- return { name, type: 'analytics_engine', dataset: b.name };
- default:
- throw new Error('Unexpected fixture binding');
- }
- });
- const workers = Object.fromEntries(
- Object.entries(config.workers).map(([role, w]) => {
- const bytes = Buffer.from(`fixture ${role}`),
- versionId = id(`${role}version`);
- return [
- role,
- {
- worker: {
- id: id(w.name),
- name: w.name,
- subdomain: { enabled: false, previews_enabled: false },
- observability: config.wrangler[role].observability,
- logpush: false,
- tail_consumers: [],
- references: { domains: [], queues: [], dispatch_namespace_outbounds: [] },
- },
- scriptSettings: {
- logpush: false,
- tail_consumers: [],
- observability: structuredClone(config.wrangler[role].observability),
- },
- version: {
- id: versionId,
- main_module: 'worker.mjs',
- modules: [{ name: 'worker.mjs', content_base64: bytes.toString('base64') }],
- bindings: bindings(w),
- exports: w.exports,
- urls: [],
- compatibility_date: w.compatibilityDate,
- compatibility_flags: w.compatibilityFlags,
- limits: config.wrangler[role].limits,
- containers: Object.values(config.containers)
- .filter((c) => Object.values(w.exports).some((e) => e.container === c.name))
- .map((c) => ({
- name: c.name,
- class_name: Object.entries(w.exports).find(([, e]) => e.container === c.name)[0],
- images: Object.fromEntries(
- Object.entries(c.images).map(([k, v]) => [k, v.reference]),
- ),
- })),
- },
- deployments: {
- deployments: [
- {
- id: id(`${role}deployment`),
- versions: [{ version_id: versionId, percentage: 100 }],
- },
- ],
- },
- routes: [],
- schedules: [],
- },
- ];
- }),
- );
- const applications = Object.entries(config.containers).map(([role, c]) => ({
- id: id(c.name),
- account_id: manifest.account,
- name: c.name,
- scheduling_policy: 'durable_object',
- durable_objects: {
- namespace_id: ns(config.workers[role].name, Object.keys(config.workers[role].exports)[0]).id,
- },
- configuration: { wrangler_ssh: { enabled: false } },
- observability: { logs: { enabled: false } },
- health: { instances: { active: 0, starting: 0 } },
- }));
- const migrations = Array.from(
- { length: 9 },
- (_, i) => `${String(i + 1).padStart(4, '0')}_fixture.sql`,
- );
- const receipt = {
- mode: 'private-lifecycle',
- sourceDirty: false,
- sourceCommit: 'e'.repeat(40),
- deployOrder: config.deployOrder,
- images: manifest.images,
- workers: Object.entries(workers).map(([role, w]) => ({
- role,
- name: w.worker.name,
- sha256: hash(Buffer.from(w.version.modules[0].content_base64, 'base64')),
- })),
- migrations: migrations.map((name) => ({ name, sha256: 'f'.repeat(64) })),
- };
- const snapshot = {
- account: manifest.account,
- complete: true,
- workers,
- namespaces,
- applications,
- database: { uuid: manifest.database.id, name: manifest.database.name },
- kv: { id: manifest.oauthKv, title: `${manifest.prefix}-oauth` },
- bucket: { name: manifest.bucket },
- managedDomain: { enabled: false },
- customDomains: { domains: [] },
- migrations,
- };
- return { manifest, receipt, snapshot };
-}
-function deployed() {
- const f = fixture();
- return { ...f, verified: verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot) };
-}
-function stopped() {
- const f = deployed();
- const claims = f.verified.applications.map((a) => ({ kind: a.kind, id: hash(a.name) }));
- const instances = f.verified.applications.map((a, i) => ({
- id: claims[i].id,
- application_id: a.id,
- image: Object.values(a.images)[0],
- status: { state: 'stopped' },
- }));
- const status = {
- record: { state: 'finished', passed: true },
- budget: { state: 'closed', claims },
- admission: { paused: true, activeRequests: 0, pendingCleanup: 0 },
- operatorStopped: true,
- alarmAt: null,
- };
- return { ...f, status, instances };
-}
-
-test('private deployment readback binds exact deployed code, versions, resources and images', () => {
- const f = deployed();
- assert.equal(f.verified.workers.length, 8);
- assert.equal(f.verified.applications.length, 3);
- assert.equal(f.verified.namespaces.length, 7);
- assert.equal(f.verified.privateConfigurationVerified, true);
- assert.equal(f.verified.sourceCommit, f.receipt.sourceCommit);
- assert.equal(f.verified.database.id, f.manifest.database.id);
-});
-
-function disabledProviderSettings(snapshot) {
- for (const entry of Object.values(snapshot.workers)) {
- entry.scriptSettings = { logpush: false, tail_consumers: null, observability: null };
- entry.worker.observability = {
- enabled: false,
- head_sampling_rate: 1,
- redact_query_string: false,
- logs: {
- enabled: false,
- head_sampling_rate: 1,
- invocation_logs: true,
- persist: true,
- destinations: [],
- },
- traces: { enabled: false, head_sampling_rate: 1, persist: true, destinations: [] },
- };
- }
-}
-
-test('readback accepts provider-disabled raw observability with inactive CLI defaults', () => {
- const f = fixture();
- disabledProviderSettings(f.snapshot);
- assert.equal(
- verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot).privateConfigurationVerified,
- true,
- );
-});
-
-test('readback handles omitted empty collections and the D1 database_id alias', () => {
- const f = fixture();
- delete f.snapshot.workers.allowance.version.bindings;
- delete f.snapshot.workers.gateway.version.exports;
- for (const role of ['gateway', 'operator']) {
- const binding = f.snapshot.workers[role].version.bindings.find((b) => b.type === 'd1');
- binding.database_id = binding.id;
- }
- assert.equal(
- verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot).privateConfigurationVerified,
- true,
- );
- f.snapshot.workers.gateway.version.bindings.find((b) => b.type === 'd1').database_id = 'other';
- assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));
-});
-
-test('omitted bindings or exports still fail when the candidate requires them', () => {
- for (const field of ['bindings', 'exports']) {
- const f = fixture();
- delete f.snapshot.workers.request.version[field];
- assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));
- }
-});
-
-test('disabled readback requires explicit raw evidence and rejects active or contradictory logging', () => {
- for (const edit of [
- (e) => {
- delete e.scriptSettings;
- },
- (e) => {
- delete e.scriptSettings.observability;
- },
- (e) => {
- delete e.scriptSettings.logpush;
- },
- (e) => {
- delete e.scriptSettings.tail_consumers;
- },
- (e) => {
- e.scriptSettings.logpush = true;
- },
- (e) => {
- e.scriptSettings.tail_consumers = [{ service: 'external' }];
- },
- (e) => {
- e.scriptSettings.observability = { enabled: true };
- },
- (e) => {
- e.worker.observability.enabled = true;
- },
- (e) => {
- e.worker.observability.logs.enabled = true;
- },
- (e) => {
- e.worker.observability.traces.enabled = true;
- },
- (e) => {
- e.worker.observability.logs.destinations = ['external'];
- },
- (e) => {
- e.worker.observability.traces.destinations = ['external'];
- },
- ]) {
- const f = fixture();
- disabledProviderSettings(f.snapshot);
- edit(f.snapshot.workers.gateway);
- assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));
- }
-});
-
-test('readback rejects code, public surfaces, stored logs and inactive-version discrepancies', () => {
- for (const edit of [
- (s) => {
- s.workers.gateway.version.modules[0].content_base64 =
- Buffer.from('altered').toString('base64');
- },
- (s) => {
- s.workers.gateway.version.urls.push('https://public.example');
- },
- (s) => {
- s.workers.gateway.worker.subdomain.enabled = true;
- },
- (s) => {
- s.workers.gateway.worker.subdomain.previews_enabled = true;
- },
- (s) => {
- s.workers.gateway.worker.observability.logs.persist = true;
- },
- (s) => {
- s.workers.gateway.worker.observability.enabled = true;
- },
- (s) => {
- s.workers.gateway.worker.tail_consumers.push({ service: 'external' });
- },
- (s) => {
- s.workers.gateway.routes.push({ pattern: '*.example/*' });
- },
- (s) => {
- s.workers.gateway.schedules.push({ cron: '* * * * *' });
- },
- (s) => {
- s.workers.gateway.deployments.deployments[0].versions.push({
- version_id: 'unreviewed',
- percentage: 1,
- });
- },
- (s) => {
- s.workers.gateway.version.limits.cpu_ms = 300000;
- },
- (s) => {
- s.managedDomain.enabled = true;
- },
- (s) => {
- s.customDomains.domains.push({ domain: 'assets.example' });
- },
- (s) => {
- s.complete = false;
- },
- ]) {
- const f = fixture();
- edit(f.snapshot);
- assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));
- }
-});
-
-test('readback rejects changed tenancy, unexpected secrets, image drift and incomplete migrations', () => {
- for (const edit of [
- (s) => {
- s.workers.gateway.version.bindings.find((b) => b.name === 'ACCOUNTS').id = 'other';
- },
- (s) => {
- s.workers.request.version.bindings.find((b) => b.name === 'TENANTS').namespace_id = 'other';
- },
- (s) => {
- s.workers.operator.version.bindings.find((b) => b.name === 'GATEWAY').service =
- 'another-worker';
- },
- (s) => {
- s.workers.gateway.version.bindings.push({ name: 'SECRET', type: 'secret_text' });
- },
- (s) => {
- s.workers.gateway.version.bindings.find((b) => b.type === 'ratelimit').simple.limit = 100000;
- },
- (s) => {
- s.workers.render.version.containers[0].images.renderer += '0';
- },
- (s) => {
- s.namespaces[0].script = 'other-owner';
- },
- (s) => {
- s.applications[0].account_id = 'other';
- },
- (s) => {
- s.applications[0].configuration.wrangler_ssh.enabled = true;
- },
- (s) => {
- s.applications[0].health.instances.active = 1;
- },
- (s) => {
- s.bucket.name = 'production';
- },
- (s) => {
- s.kv.id = 'other';
- },
- (s) => {
- s.migrations = [];
- },
- ]) {
- const f = fixture();
- edit(f.snapshot);
- assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));
- }
-});
-
-test('cleanup plans only recorded trial resources in reverse dependency order after verified stop', () => {
- const f = stopped();
- const plan = planLifecycleCleanup(f.manifest, f.verified, f.status, f.instances);
- assert.deepEqual(
- plan.workers.map((w) => w.role),
- f.receipt.deployOrder.toReversed(),
- );
- assert.deepEqual(
- plan.applications.map((a) => a.id).sort(),
- f.verified.applications.map((a) => a.id).sort(),
- );
- assert.equal(plan.database.id, f.manifest.database.id);
- assert.equal(plan.kv.id, f.manifest.oauthKv);
- assert.equal(plan.bucket, f.manifest.bucket);
- assert.equal(plan.registryImages, 'preserve');
- assert.equal(plan.verifiedStoppedInstances, 3);
-});
-
-test('cleanup refuses active, unclaimed, foreign or excessive VM records and uncertain stop', () => {
- for (const edit of [
- (f) => {
- f.status.budget.state = 'open';
- },
- (f) => {
- f.status.operatorStopped = false;
- },
- (f) => {
- f.status.alarmAt = Date.now();
- },
- (f) => {
- f.status.record.state = 'running';
- },
- (f) => {
- f.status.admission.pendingCleanup = 1;
- },
- (f) => {
- f.status.admission.activeRequests = 1;
- },
- (f) => {
- f.status.admission.paused = false;
- },
- (f) => {
- f.instances[0].status.state = 'running';
- },
- (f) => {
- f.instances[0].application_id = 'other';
- },
- (f) => {
- f.instances[0].image = 'other';
- },
- (f) => {
- f.instances[0].id = hash('unclaimed');
- },
- (f) => {
- f.instances.push({ ...f.instances[0] });
- },
- (f) => {
- f.status.budget.claims.push(
- ...Array.from({ length: 5 }, (_, i) => ({ kind: 'render', id: hash(String(i)) })),
- );
- },
- (f) => {
- f.verified.database.id = 'production';
- },
- (f) => {
- f.verified.workers[0].name = 'production';
- },
- ]) {
- const f = stopped();
- edit(f);
- assert.throws(() => planLifecycleCleanup(f.manifest, f.verified, f.status, f.instances));
- }
-});
-
-test('failed starts need no running VM and failed qualification still permits verified cleanup', () => {
- const f = stopped();
- f.status.record.passed = false;
- f.instances.pop();
- const plan = planLifecycleCleanup(f.manifest, f.verified, f.status, f.instances);
- assert.equal(plan.verifiedStoppedInstances, 2);
- assert.equal(plan.claims, 3);
-});
diff --git a/hosting/test/lifecycle-worker.test.mjs b/hosting/test/lifecycle-worker.test.mjs
deleted file mode 100644
index f1a1788a..00000000
--- a/hosting/test/lifecycle-worker.test.mjs
+++ /dev/null
@@ -1,312 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-import { fileURLToPath } from 'node:url';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-import { lifecycleConfig } from '../probe/lifecycle-config.mjs';
-import { lifecycleManifest } from './lifecycle-fixture.mjs';
-import { migrateAccounts } from './database.mjs';
-
-const c = lifecycleConfig(lifecycleManifest),
- bundles = {};
-before(async () => {
- for (const [role, entry] of Object.entries(c.entries)) {
- const result = await build({
- entryPoints: [fileURLToPath(new URL(`../src/${entry}.ts`, import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- metafile: true,
- });
- bundles[role] = result.outputFiles[0].text;
- const inputs = Object.keys(result.metafile.inputs).join('\n').replaceAll('\\', '/');
- if (role !== 'operator')
- assert.doesNotMatch(inputs, /qualification-accounts|lifecycle-run|gateway-preflight/);
- if (['request', 'evaluation', 'render'].includes(role))
- assert.doesNotMatch(inputs, /oauth|\/src\/(?:auth|google|github|browser-|account-)/);
- }
- bundles.observer = (
- await build({
- entryPoints: [fileURLToPath(new URL('../probe/lifecycle-observer.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- })
- ).outputFiles[0].text;
-});
-function worker(role) {
- const config = c.workers[role];
- const result = {
- name: config.name,
- modules: true,
- script: bundles[role],
- compatibilityDate: config.compatibilityDate,
- compatibilityFlags: config.compatibilityFlags,
- bindings: {},
- durableObjects: {},
- serviceBindings: {},
- kvNamespaces: {},
- d1Databases: {},
- r2Buckets: {},
- ratelimits: {},
- outboundService: () => {
- throw new Error('No external network in private lifecycle fixture');
- },
- };
- for (const [name, binding] of Object.entries(config.env)) {
- switch (binding.type) {
- case 'text':
- result.bindings[name] = binding.value;
- break;
- case 'durable-object':
- result.durableObjects[name] = {
- className: binding.exportName,
- scriptName: binding.worker,
- useSQLite: true,
- };
- break;
- case 'worker':
- result.serviceBindings[name] = { name: binding.worker, entrypoint: binding.exportName };
- break;
- case 'd1':
- result.d1Databases[name] = binding.id;
- break;
- case 'kv':
- result.kvNamespaces[name] = binding.id;
- break;
- case 'r2':
- result.r2Buckets[name] = binding.name;
- break;
- case 'rate-limit':
- result.ratelimits[name] = { namespace_id: binding.namespace, simple: binding.simple };
- break;
- case 'analytics-engine-dataset':
- break;
- default:
- assert.fail(`Unexpected binding ${binding.type}`);
- }
- }
- for (const [name, exported] of Object.entries(config.exports))
- if (exported.type === 'durable-object')
- result.durableObjects[`REGISTER_${name}`] = { className: name, useSQLite: true };
- return result;
-}
-async function fixture(fault) {
- const runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- workers: [
- ...Object.keys(c.entries).map((role) => {
- const value = worker(role);
- if (role === 'gateway' && fault === 'database')
- value.d1Databases.ACCOUNTS = '22222222-2222-2222-2222-222222222222';
- if (role === 'operator' && fault === 'uncertain-cleanup')
- value.serviceBindings.CONTROL = { name: 'uncertain-control', entrypoint: 'Control' };
- return value;
- }),
- {
- name: 'uncertain-control',
- modules: true,
- compatibilityDate: '2026-10-06',
- script: `import {WorkerEntrypoint} from 'cloudflare:workers';
- export class Control extends WorkerEntrypoint {
- setPaused(){return {paused:true,activeRequests:1,pendingCleanup:1};}
- }
- export default {fetch(){return new Response('Not found',{status:404});}};`,
- },
- {
- name: 'loopback-observer',
- modules: true,
- compatibilityDate: '2026-10-06',
- script: bundles.observer,
- serviceBindings: {
- PROBE: { name: c.workers.operator.name, entrypoint: 'KilnLifecycleControl' },
- },
- },
- {
- name: 'local-observer',
- modules: true,
- compatibilityDate: '2026-10-06',
- serviceBindings: {
- PROBE: { name: c.workers.operator.name, entrypoint: 'KilnLifecycleControl' },
- },
- durableObjects: {
- REQUEST: {
- className: 'KilnNativeRequest',
- scriptName: c.workers.request.name,
- useSQLite: true,
- },
- EVALUATION: {
- className: 'KilnEvaluationJob',
- scriptName: c.workers.evaluation.name,
- useSQLite: true,
- },
- RENDER: {
- className: 'KilnRenderJob',
- scriptName: c.workers.render.name,
- useSQLite: true,
- },
- },
- script: `export default {async fetch(request,env){
- switch(new URL(request.url).pathname){
- case '/denied': {
- const outcomes=[];
- for(const name of ['REQUEST','EVALUATION','RENDER']) {
- let cancelled=false,denied=false,done;
- const cancellation=new Promise(resolve=>{done=resolve;});
- const body=new ReadableStream({start(c){c.enqueue(new TextEncoder().encode('{}'));},cancel(){cancelled=true;done();}});
- const input=new Request('https://native.invalid/mcp',{method:'POST',body});
- try {
- const stub=env[name].getByName('closed-budget');
- if(name==='REQUEST') await stub.run('a'.repeat(43),input,Date.now()+60000);
- else await stub.fetch(input);
- } catch { denied=true; }
- let timer;
- try {await Promise.race([cancellation,new Promise(resolve=>{timer=setTimeout(resolve,1000);})]);}
- finally {clearTimeout(timer);}
- outcomes.push({name,cancelled,denied});
- }
- return Response.json(outcomes);
- }
- default: return new Response('Not found',{status:404});
- }
- }};`,
- },
- ],
- }),
- unsafeInspectDurableObjects: true,
- });
- try {
- const name = c.workers.operator.name;
- const database = await runtime.getD1Database('ACCOUNTS', name);
- await migrateAccounts(database);
- const namespace = await runtime.getDurableObjectNamespace('RUN', name);
- const observer = await runtime.getWorker('local-observer');
- const loopback = await runtime.getWorker('loopback-observer');
- const call = async (path) =>
- (
- await (path === 'denied'
- ? observer.fetch('https://observer.invalid/denied')
- : loopback.fetch(`http://127.0.0.1:8798/${path === 'run' ? 'run-fixed' : path}`, {
- method: 'POST',
- headers: { 'X-Kiln-Operator': 'private-lifecycle-v1' },
- }))
- ).json();
- return {
- runtime,
- database,
- namespace,
- run: () => call('run'),
- stop: () => call('stop'),
- status: () => call('status'),
- denied: () => call('denied'),
- };
- } catch (error) {
- await runtime.dispose();
- throw error;
- }
-}
-test('combined private operator passes the gateway before native admission, seals on missing VM and survives eviction', async () => {
- const f = await fixture();
- try {
- const attempts = await Promise.all([f.run(), f.run()]);
- const first = attempts.find((result) => result.state === 'finished');
- assert(first);
- assert.equal(first.preflight.passed, true, JSON.stringify(first));
- assert.equal(first.native.passed, false);
- assert.equal(first.native.results.length, 1);
- assert.equal(first.native.results[0].name, 'material-create');
- assert.equal(first.native.results[0].status, 503);
- assert.equal(first.passed, false);
- const status = await f.status();
- assert.equal(status.budget.state, 'closed');
- assert.deepEqual(
- status.budget.claims.map((v) => v.kind),
- ['coordinator'],
- );
- assert.equal(status.admission.paused, true);
- assert.equal(status.admission.activeRequests, 0);
- assert.equal(status.admission.pendingCleanup, 0);
- assert.equal(
- (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,
- 2,
- );
- assert.equal(
- (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_connections').first()).n,
- 4,
- );
- assert.doesNotMatch(
- JSON.stringify(first),
- /access_token|refresh_token|cookie|Bearer |ka_[a-f0-9]/,
- );
- await f.runtime.unsafeEvictDurableObject(c.workers.operator.name, 'KilnLifecycleRun', {
- id: f.namespace.idFromName('lifecycle-v1').toString(),
- });
- assert.deepEqual(await f.run(), first);
- assert.deepEqual((await f.status()).budget, status.budget);
- for (const w of Object.values(c.workers)) {
- const bound = await f.runtime.getWorker(w.name);
- if (w.name !== c.workers.gateway.name)
- assert.equal((await bound.fetch('https://private.invalid/run')).status, 404);
- }
- } finally {
- await f.runtime.dispose();
- }
-});
-test('operator stop before setup cannot provision identities or native work', async () => {
- const f = await fixture();
- try {
- await f.stop();
- const first = await f.run(),
- status = await f.status();
- assert.equal(first.passed, false);
- assert.equal(first.state, 'stopped');
- assert.deepEqual(status.budget, { state: 'closed', claims: [] });
- assert.equal(status.admission.paused, true);
- assert.deepEqual(
- await f.denied(),
- ['REQUEST', 'EVALUATION', 'RENDER'].map((name) => ({ name, cancelled: true, denied: true })),
- );
- assert.deepEqual((await f.status()).budget, status.budget);
- assert.equal(
- (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,
- 0,
- );
- } finally {
- await f.runtime.dispose();
- }
-});
-test('failed gateway preflight cannot open the native allowance', async () => {
- const f = await fixture('database');
- try {
- const first = await f.run();
- assert.equal(first.preflight.passed, false);
- assert.equal(first.native, null);
- const status = await f.status();
- assert.deepEqual(status.budget, { state: 'closed', claims: [] });
- assert.equal(status.admission.paused, true);
- assert.deepEqual(await f.run(), first);
- } finally {
- await f.runtime.dispose();
- }
-});
-
-test('operator stop retains a recovery alarm when control reports uncertain cleanup', async () => {
- const f = await fixture('uncertain-cleanup');
- try {
- const failed = await f.run();
- assert.equal(failed.passed, false);
- const afterRun = await f.status();
- assert(afterRun.alarmAt > Date.now() && afterRun.alarmAt <= Date.now() + 61000);
- await f.stop();
- const status = await f.status();
- assert(status.alarmAt > Date.now());
- assert.deepEqual(status.budget, { state: 'closed', claims: [] });
- assert.equal(status.operatorStopped, true);
- } finally {
- await f.runtime.dispose();
- }
-});
diff --git a/hosting/test/login-intents-worker.ts b/hosting/test/login-intents-worker.ts
deleted file mode 100644
index 9923bc27..00000000
--- a/hosting/test/login-intents-worker.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { authorizationFailure } from '../src/auth';
-import { D1LoginIntents, type LoginIntent } from '../src/login-intents';
-
-export default {
- async fetch(request: Request, env: { ACCOUNTS: D1Database }): Promise<Response> {
- try {
- const input = (await request.json()) as LoginIntent & { handle: string };
- const store = new D1LoginIntents(env.ACCOUNTS, new URL(request.url).origin);
- switch (new URL(request.url).pathname) {
- case '/consent':
- await store.claimConsent(input.handle);
- break;
- case '/create':
- await store.create(input);
- break;
- case '/consume':
- await store.consume(input);
- break;
- default:
- return new Response(null, { status: 404 });
- }
- return new Response(null, { status: 204 });
- } catch (error) {
- return authorizationFailure(error);
- }
- },
-};
diff --git a/hosting/test/login-intents.test.mjs b/hosting/test/login-intents.test.mjs
deleted file mode 100644
index 94db085e..00000000
--- a/hosting/test/login-intents.test.mjs
+++ /dev/null
@@ -1,94 +0,0 @@
-import assert from 'node:assert/strict';
-import { randomUUID } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-import { migrateAccounts } from './database.mjs';
-
-let runtime, database;
-before(async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./login-intents-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- d1Databases: ['ACCOUNTS'],
- }),
- );
- database = await runtime.getD1Database('ACCOUNTS');
- await migrateAccounts(database);
-});
-after(async () => runtime?.dispose());
-const intent = () => ({
- id: randomUUID(),
- state: randomUUID(),
- provider: 'google',
- purpose: 'sign-in',
-});
-const call = (action, input, origin = 'https://kiln.test') =>
- runtime.dispatchFetch(`${origin}/${action}`, { method: 'POST', body: JSON.stringify(input) });
-
-test('only one simultaneous use of a browser-validated consent handle succeeds', async () => {
- const input = { handle: randomUUID() };
- const results = await Promise.all(Array.from({ length: 24 }, () => call('consent', input)));
- assert.equal(results.filter((r) => r.status === 204).length, 1);
- assert.equal(results.filter((r) => r.status === 400).length, 23);
- assert.equal((await call('consent', input, 'https://other.test')).status, 204);
-});
-
-test('only one simultaneous callback can consume an intent, even with stale upstream KV', async () => {
- const input = intent();
- assert.equal((await call('create', input)).status, 204);
- const stored = await database
- .prepare('SELECT * FROM kiln_login_intents WHERE id=?')
- .bind(input.id)
- .first();
- assert.ok(!JSON.stringify(stored).includes(input.state));
- const results = await Promise.all(Array.from({ length: 24 }, () => call('consume', input)));
- assert.equal(results.filter((r) => r.status === 204).length, 1);
- assert.equal(results.filter((r) => r.status === 400).length, 23);
-});
-
-test('provider, purpose, origin and state must all match without burning the valid intent', async () => {
- const input = intent();
- assert.equal((await call('create', input)).status, 204);
- for (const patch of [
- { provider: 'github' },
- { purpose: 'link' },
- { state: randomUUID() },
- { id: randomUUID() },
- ]) {
- assert.equal((await call('consume', { ...input, ...patch })).status, 400);
- }
- assert.equal((await call('consume', input, 'https://other.test')).status, 400);
- assert.equal((await call('consume', input)).status, 204);
-});
-
-test('expired intents fail closed; malformed input cannot reach storage', async () => {
- const input = intent();
- assert.equal((await call('create', input)).status, 204);
- await database
- .prepare('UPDATE kiln_login_intents SET expires_at=0 WHERE id=?')
- .bind(input.id)
- .run();
- assert.equal((await call('consume', input)).status, 400);
- for (const patch of [
- { id: '' },
- { state: '' },
- { state: 'x'.repeat(4097) },
- { provider: 'foreign' },
- { purpose: 'link' },
- ]) {
- assert.equal((await call('create', { ...intent(), ...patch })).status, 400);
- }
- assert.equal((await call('consent', { handle: '' })).status, 400);
-});
diff --git a/hosting/test/native-assets.test.mjs b/hosting/test/native-assets.test.mjs
deleted file mode 100644
index 5146f307..00000000
--- a/hosting/test/native-assets.test.mjs
+++ /dev/null
@@ -1,477 +0,0 @@
-import assert from 'node:assert/strict';
-import { mkdir } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-import { createKilnToolHost } from '../../dist/mcp-engine.mjs';
-import { decodeAssetBundle } from '../../lib/assets.js';
-import { renderGLB } from '../../lib/render.js';
-import {
- createMaterialRecordV1,
- createMaterialLibraryPayload,
-} from '../../lib/material-library-node.js';
-import { materialLibraryPortableSpec } from '../../lib/material-library.js';
-
-let NativeAssetLibrary;
-let NativeProgramStore;
-let runtime;
-let namespace;
-const source =
- "function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#aaaaaa'),{parent:r});return r;}";
-const persisted = (value) => JSON.parse(JSON.stringify(value));
-let glb;
-before(async () => {
- const outdir = fileURLToPath(new URL('../../.cache/hosted-asset-test/', import.meta.url));
- await mkdir(outdir, { recursive: true });
- await build({
- entryPoints: ['native-assets', 'native-programs'].map((name) =>
- fileURLToPath(new URL(`../src/${name}.ts`, import.meta.url)),
- ),
- bundle: true,
- format: 'esm',
- platform: 'node',
- packages: 'external',
- outdir,
- outExtension: { '.js': '.mjs' },
- alias: Object.fromEntries(
- [
- ['assets', 'assets'],
- ['assets/node', 'assets-node'],
- ['material-library/node', 'material-library-node'],
- ].map(([name, file]) => [
- `@instruktlabs/kiln/${name}`,
- fileURLToPath(new URL(`../../lib/${file}.js`, import.meta.url)),
- ]),
- ),
- });
- ({ NativeAssetLibrary } = await import(
- new URL('../../.cache/hosted-asset-test/native-assets.mjs', import.meta.url)
- ));
- ({ NativeProgramStore } = await import(
- new URL('../../.cache/hosted-asset-test/native-programs.mjs', import.meta.url)
- ));
- const worker = await build({
- entryPoints: [fileURLToPath(new URL('../src/tenant-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- name: 'native-assets',
- modules: true,
- script: worker.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- r2Buckets: ['ARTIFACTS'],
- durableObjects: { TENANTS: { className: 'KilnTenant', useSQLite: true } },
- bindings: {
- STORAGE_MAX_BYTES: String(16 * 1024 * 1024),
- STORAGE_MAX_OBJECTS: '256',
- STORAGE_MAX_GROUPS: '64',
- },
- outboundService: async () => {
- throw new Error('No external requests');
- },
- }),
- unsafeInspectDurableObjects: true,
- });
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
- glb = (await renderGLB(source)).glb;
-});
-after(async () => runtime?.dispose());
-const fetchFor = (owner) => async (request) => {
- const url = new URL(request.url);
- assert.equal(url.origin, 'http://kiln-storage.internal');
- assert.equal(request.headers.get('authorization'), null);
- return namespace
- .get(namespace.idFromName(owner))
- .fetch(new Request(`https://tenant.internal${url.pathname}`, request));
-};
-const library = (owner) => new NativeAssetLibrary({ fetch: fetchFor(owner) });
-const usage = async (owner) =>
- (
- await namespace.get(namespace.idFromName(owner)).fetch('https://tenant.internal/internal/usage')
- ).json();
-
-test('new saves require matching host proof when configured, while imports preserve original provenance', async () => {
- let proofs = 0;
- const assets = new NativeAssetLibrary({
- fetch: fetchFor('build-proof'),
- executionIdentity: (draft) => {
- proofs++;
- assert.equal(draft.code, source);
- assert.deepEqual(draft.glb, Uint8Array.from(glb));
- return `cloudflare-container:sha256:${'a'.repeat(64)}`;
- },
- });
- const saved = await assets.save('project', {
- name: 'Verified box',
- code: source,
- glb,
- build: { engine: 'source-claimed-forgery', options: {}, warnings: [] },
- });
- assert.equal(proofs, 1);
- assert.equal(saved.build.engine, `cloudflare-container:sha256:${'a'.repeat(64)}`);
- const record = await assets.read('project', saved.assetId, saved.revisionId);
- record.manifest.build.engine = 'imported:unknown-original-host';
- const imported = await assets.import('library', [record]);
- assert.equal(proofs, 1);
- assert.equal(imported[0].build.engine, 'imported:unknown-original-host');
- const before = await usage('build-proof');
- await assert.rejects(assets.save('project', { name: 'Missing build', code: source, glb }));
- const unavailable = new NativeAssetLibrary({
- fetch: fetchFor('build-proof'),
- executionIdentity: () => {
- throw new Error('No verified evaluation');
- },
- });
- await assert.rejects(
- unavailable.save('project', {
- name: 'Missing proof',
- code: source,
- glb,
- build: { engine: 'forged', options: {}, warnings: [] },
- }),
- /verified evaluation/,
- );
- assert.deepEqual(await usage('build-proof'), before);
-});
-
-test('native links use server-issued tickets for exact saved revisions and never accept backend URLs', async () => {
- const assets = library('download-links');
- const saved = await assets.save('project', { name: 'Box', code: source, glb });
- const urls = await assets.downloadUrls(
- 'https://kiln.example.com',
- 'project',
- saved.assetId,
- saved.revisionId,
- );
- assert.deepEqual(Object.keys(urls).sort(), ['asset.glb', 'manifest.json', 'source.kiln.js']);
- const uri = new URL(urls['source.kiln.js']);
- assert.equal(uri.origin, 'https://kiln.example.com');
- assert.match(uri.pathname, /^\/downloads\/[a-f0-9]{64}\/source\.kiln\.js$/);
- const read = await namespace
- .getByName('download-links')
- .fetch(`https://tenant.internal/internal${uri.pathname}`);
- assert.equal(read.status, 200);
- assert.equal(await read.text(), source);
- assert.equal(
- (
- await namespace
- .getByName('other-downloads')
- .fetch(`https://tenant.internal/internal${uri.pathname}`)
- ).status,
- 404,
- );
- await assert.rejects(
- assets.downloadUrls('https://evil.example/path', 'project', saved.assetId, saved.revisionId),
- );
- await assert.rejects(
- assets.downloadUrls('https://kiln.example.com', 'foreign', saved.assetId, saved.revisionId),
- );
- for (const invalid of [
- { ticket: 'a'.repeat(64), expiresAt: Date.now() + 600000, files: ['../../secret'] },
- { ticket: `${'a'.repeat(64)}\n`, expiresAt: Date.now() + 600000, files: ['asset.glb'] },
- { ticket: 'a'.repeat(64), expiresAt: 0, files: ['asset.glb'] },
- { ticket: 'a'.repeat(64), expiresAt: Date.now() + 600000, files: ['https://evil.example'] },
- { ticket: 'a'.repeat(64), expiresAt: Date.now() + 600000, files: ['asset.glb', 'asset.glb'] },
- ]) {
- const forged = new NativeAssetLibrary({ fetch: async () => Response.json(invalid) });
- await assert.rejects(
- forged.downloadUrls('https://kiln.example.com', 'project', saved.assetId, saved.revisionId),
- );
- }
-});
-
-test('save, revise, reconnect and export preserve exact records and source lineage', async () => {
- const assets = library('saved');
- assert.deepEqual(
- assets.collections().map((item) => item.id),
- ['project', 'library'],
- );
- const first = await assets.save('project', { name: 'Box', code: source, glb });
- const revised = await assets.save('project', {
- name: 'Revised',
- assetId: first.assetId,
- parentRevision: first.revisionId,
- code: `${source}\n// revised`,
- glb,
- });
- assert.equal(revised.parentRevision, first.revisionId);
- await runtime.unsafeEvictDurableObject('native-assets', 'KilnTenant', {
- id: namespace.idFromName('saved').toString(),
- });
- const fresh = library('saved');
- const records = await fresh.list('project');
- assert.equal(records.length, 2);
- const original = await fresh.read('project', first.assetId, first.revisionId);
- assert.deepEqual(original.manifest, persisted(first));
- assert.deepEqual(Buffer.from(original.files['asset.glb']), Buffer.from(glb));
- assert.equal(new TextDecoder().decode(original.files['source.kiln.js']), source);
- const latest = await fresh.read('project', revised.assetId, revised.revisionId);
- const decoded = decodeAssetBundle(await fresh.exportBundle([original, latest]));
- assert.equal(decoded.length, 2);
- assert.deepEqual(decoded[1].manifest, persisted(revised));
- assert.deepEqual(Buffer.from(decoded[0].files['asset.glb']), Buffer.from(glb));
- await assert.rejects(
- library('other').read('project', first.assetId, first.revisionId),
- /not found/i,
- );
-});
-
-test('copy and repeated imports preserve identity and do not allocate duplicate storage', async () => {
- const assets = library('copy');
- const saved = await assets.save('project', { name: 'Box', code: source, glb });
- const record = await assets.read('project', saved.assetId, saved.revisionId);
- record.manifest.ownerProvenance = { fixture: 'preserve unknown provenance' };
- await assets.import('library', [record]);
- const before = await usage('copy');
- await library('copy').import('library', [record]);
- assert.deepEqual(await usage('copy'), before);
- const copied = await assets.read('library', saved.assetId, saved.revisionId);
- assert.deepEqual(copied.manifest, record.manifest);
- const changed = structuredClone(record);
- changed.manifest.name = 'Conflicting name';
- await assert.rejects(assets.import('library', [changed]), /immutable/);
- assert.deepEqual(
- (await assets.read('library', saved.assetId, saved.revisionId)).manifest,
- record.manifest,
- );
-});
-
-test('invalid batches publish nothing and concurrent new saves require a parent', async () => {
- const assets = library('invalid-assets');
- const first = await assets.save('project', { name: 'Box', assetId: 'shared', code: source, glb });
- const record = await assets.read('project', first.assetId, first.revisionId);
- const broken = structuredClone(record);
- broken.manifest.revisionId = 'r_broken';
- broken.files['asset.glb'][0] = 0;
- const before = await usage('invalid-assets');
- await assert.rejects(assets.import('library', [record, broken]), /integrity|GLB/);
- assert.deepEqual(await usage('invalid-assets'), before);
- assert.equal((await assets.list('library')).length, 0);
- const races = await Promise.allSettled(
- [1, 2].map(() => assets.save('library', { name: 'Race', assetId: 'race', code: source, glb })),
- );
- assert.equal(races.filter((item) => item.status === 'fulfilled').length, 1);
- assert.equal(races.filter((item) => item.status === 'rejected').length, 1);
- assert.equal(
- (await usage('invalid-assets')).objects,
- 6,
- 'A failed competing save discards only its unpinned files',
- );
-});
-
-test('partial upload failure discards staging files while deletion preserves copies in other collections', async () => {
- let uploads = 0;
- const flaky = new NativeAssetLibrary({
- fetch: async (request) => {
- if (new URL(request.url).pathname === '/internal/artifacts' && ++uploads === 2) {
- return new Response('fixture upload failure', { status: 503 });
- }
- return fetchFor('failed-save')(request);
- },
- });
- await assert.rejects(flaky.save('project', { name: 'Failed', code: source, glb }), /unavailable/);
- assert.equal((await usage('failed-save')).objects, 0);
- const assets = library('deletion');
- const saved = await assets.save('project', { name: 'Keep copy', code: source, glb });
- const record = await assets.read('project', saved.assetId, saved.revisionId);
- await assets.import('library', [record]);
- await assets.deleteRevision('project', saved.assetId, saved.revisionId);
- await assert.rejects(assets.read('project', saved.assetId, saved.revisionId), /not found/);
- assert.deepEqual(
- (await assets.read('library', saved.assetId, saved.revisionId)).manifest,
- record.manifest,
- );
-});
-
-test('a lost commit acknowledgement preserves saved files through cleanup and reconnect', async () => {
- const owner = 'lost-commit-ack';
- const flaky = new NativeAssetLibrary({
- fetch: async (request) => {
- const response = await fetchFor(owner)(request);
- if (new URL(request.url).pathname === '/internal/assets/commit') {
- assert.equal(response.status, 201);
- await response.body?.cancel();
- return new Response('fixture lost acknowledgement', { status: 503 });
- }
- return response;
- },
- });
- await assert.rejects(
- flaky.save('project', { name: 'Committed before disconnect', code: source, glb }),
- /unavailable/,
- );
- await runtime.unsafeEvictDurableObject('native-assets', 'KilnTenant', {
- id: namespace.idFromName(owner).toString(),
- });
- const fresh = library(owner);
- const records = await fresh.list('project');
- assert.equal(records.length, 1);
- const saved = await fresh.read('project', records[0].assetId, records[0].revisionId);
- assert.deepEqual(Buffer.from(saved.files['asset.glb']), Buffer.from(glb));
- assert.deepEqual(saved.files['source.kiln.js'], new TextEncoder().encode(source));
- assert.equal((await usage(owner)).objects, 3, 'Cleanup must retain every committed file');
-});
-
-test('saved records survive unsaved expiry and integrity corruption is refused', async () => {
- const assets = library('retained');
- const saved = await assets.save('project', { name: 'Box', code: source, glb });
- const database = await runtime.unsafeGetDurableObjectStorage('native-assets', 'KilnTenant', {
- id: namespace.idFromName('retained').toString(),
- });
- await database.exec('UPDATE artifacts SET expires_at = 1');
- assert.deepEqual(
- (await assets.read('project', saved.assetId, saved.revisionId)).manifest,
- persisted(saved),
- );
- const rows = await database.exec("SELECT object_key FROM artifacts WHERE filename = 'asset.glb'");
- await (await runtime.getR2Bucket('ARTIFACTS')).put(rows[0].object_key, 'corrupt');
- await assert.rejects(
- assets.read('project', saved.assetId, saved.revisionId),
- /integrity|unavailable/,
- );
-});
-
-test('real registry tools save, list, load and export a hosted revision after fresh host construction', async () => {
- const make = () =>
- createKilnToolHost({
- programStore: new NativeProgramStore({ fetch: fetchFor('engine-assets') }),
- assetLibrary: library('engine-assets'),
- evaluatorProfile: 'trusted-local',
- });
- const invoke = async (host, name, args) => {
- const response = await host.callTool(name, args, { signal: new AbortController().signal });
- assert.notEqual(response.isError, true, JSON.stringify(response.content));
- return JSON.parse(response.content.find((item) => item.type === 'text').text);
- };
- const first = make();
- const validated = await invoke(first, 'kiln_validate', { code: `\ufeff${source}` });
- const saved = await invoke(first, 'kiln_save', {
- programRef: validated.programRef,
- name: 'Hosted Box',
- collection: 'project',
- });
- assert.ok(saved.asset.assetId);
- const second = make();
- const listed = await invoke(second, 'kiln_assets', { action: 'list', collection: 'project' });
- assert.ok(JSON.stringify(listed).includes(saved.asset.assetId));
- const loaded = await invoke(second, 'kiln_assets', {
- action: 'restore',
- collection: 'project',
- assetId: saved.asset.assetId,
- revisionId: saved.asset.revisionId,
- });
- assert.ok(loaded.programRef);
- assert.equal(
- loaded.programRef,
- validated.programRef,
- 'Restore must retain the exact authored BOM and reference',
- );
- const exported = await invoke(second, 'kiln_export', {
- collection: 'project',
- assetId: saved.asset.assetId,
- revisionId: saved.asset.revisionId,
- });
- assert.ok(JSON.stringify(exported).includes('asset.glb'));
-});
-
-test('saved material closure survives export, import and offline rebuild without the original library', async () => {
- const material = await createMaterialRecordV1({
- materialId: 'hosted-plaster',
- name: 'Hosted plaster',
- tileable: true,
- sources: [
- {
- id: 'authored',
- kind: 'procedural',
- provider: 'Kiln',
- creator: 'Test author',
- license: {
- spdx: 'CC0-1.0',
- url: 'https://creativecommons.org/publicdomain/zero/1.0/',
- attribution: '',
- },
- originalFiles: [],
- },
- ],
- maps: [
- {
- slot: 'baseColor',
- sourceId: 'authored',
- transforms: [],
- procedural: {
- schemaVersion: 2,
- size: 8,
- usage: 'albedo',
- layers: [
- { op: 'noise', colorA: 0x779944, colorB: 0xeeeecc, seed: 17, scale: 4, octaves: 2 },
- ],
- },
- },
- ],
- });
- const code = `async function build(){const r=createRoot('Root');const m=await compilePortableMaterialSpecV2(${JSON.stringify(materialLibraryPortableSpec(material.manifest))});createPart('Body',boxGeo(1,1,1),m,{parent:r});return r;}`;
- const baked = await renderGLB(code, {
- materialResources: await createMaterialLibraryPayload([material]),
- });
- const origin = new NativeAssetLibrary({
- fetch: fetchFor('material-origin'),
- materials: { read: async () => material },
- });
- const saved = await origin.save('project', {
- name: 'Material box',
- code,
- glb: baked.glb,
- build: {
- engine: 'fixture',
- options: baked.rebuildOptions,
- warnings: [],
- dependencies: [
- { kind: 'kiln.material.v1', delivery: 'runtime', manifest: material.manifest },
- ],
- rebuild: 'external-dependencies-required',
- },
- });
- const record = await library('material-origin').read('project', saved.assetId, saved.revisionId);
- assert.deepEqual(record.materialResources.records[0].manifest, material.manifest);
- const bundle = await origin.exportBundle([record]);
- const installedMaterials = [];
- const target = new NativeAssetLibrary({
- fetch: fetchFor('material-target'),
- materials: {
- import: async (records) => {
- installedMaterials.push(...records);
- return records.map((record) => record.manifest);
- },
- read: async (id, revision) =>
- installedMaterials.find(
- (record) => record.manifest.materialId === id && record.manifest.revisionId === revision,
- ),
- },
- });
- await target.import('library', decodeAssetBundle(bundle));
- assert.equal(
- installedMaterials.length,
- 1,
- 'Import installs the exact material closure in an injected library',
- );
- const restored = await target.read('library', saved.assetId, saved.revisionId);
- const rebuilt = await renderGLB(code, { materialResources: restored.materialResources });
- assert.deepEqual(Buffer.from(rebuilt.glb), Buffer.from(baked.glb));
- const broken = structuredClone(record);
- broken.materialResources.records[0].files[material.manifest.maps[0].file] = 'invalid';
- const before = await usage('material-target');
- await assert.rejects(target.import('project', [broken]));
- assert.deepEqual(await usage('material-target'), before);
- const missing = structuredClone(record);
- delete missing.materialResources;
- await assert.rejects(
- library('material-missing').import('project', [missing]),
- /material unavailable/i,
- );
-});
diff --git a/hosting/test/native-build-identity.test.mjs b/hosting/test/native-build-identity.test.mjs
deleted file mode 100644
index c7e36da0..00000000
--- a/hosting/test/native-build-identity.test.mjs
+++ /dev/null
@@ -1,48 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, test } from 'node:test';
-import { fileURLToPath } from 'node:url';
-import { build } from 'esbuild';
-
-let NativeBuildIdentities;
-const image = `sha256:${'a'.repeat(64)}`;
-before(async () => {
- const output = new URL('../../.cache/native-build-identity-test.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-build-identity.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ NativeBuildIdentities } = await import(output));
-});
-
-test('saved identity is bound to exact evaluated source and output, independent of caller buffers', () => {
- const records = new NativeBuildIdentities();
- const glb = new Uint8Array([1, 2, 3]);
- records.record('source', glb, image);
- const draft = { code: 'source', glb: Uint8Array.from(glb), build: { engine: 'forged' } };
- assert.equal(records.forDraft(draft), `cloudflare-container:${image}`);
- glb[0] = 9;
- assert.equal(records.forDraft(draft), `cloudflare-container:${image}`);
- for (const value of [
- { ...draft, glb },
- { ...draft, code: 'other' },
- { ...draft, code: undefined },
- ])
- assert.throws(() => records.forDraft(value), /verified evaluation/i);
- assert.throws(() => new NativeBuildIdentities().forDraft(draft), /verified evaluation/i);
-});
-
-test('missing, malformed or conflicting identities cannot be saved and retained proofs are bounded', () => {
- const records = new NativeBuildIdentities();
- for (const identity of [undefined, '', 'latest', `${image}\n`])
- assert.throws(() => records.record('a', new Uint8Array([1]), identity));
- records.record('a', new Uint8Array([1]), image);
- assert.throws(() => records.record('a', new Uint8Array([1]), `sha256:${'b'.repeat(64)}`));
- for (let i = 1; i < 16; i++) records.record(`source-${i}`, new Uint8Array([i]), image);
- assert.throws(() => records.record('overflow', new Uint8Array([100]), image));
- records.record('a', new Uint8Array([1]), image);
- assert.throws(() => records.record('x'.repeat(1024 * 1024 + 1), new Uint8Array([1]), image));
- assert.throws(() => records.record('a', new Uint8Array(4 * 1024 * 1024 + 1), image));
-});
diff --git a/hosting/test/native-build.test.mjs b/hosting/test/native-build.test.mjs
deleted file mode 100644
index 2ab3b43f..00000000
--- a/hosting/test/native-build.test.mjs
+++ /dev/null
@@ -1,48 +0,0 @@
-import assert from 'node:assert/strict';
-import { cp, mkdir, mkdtemp, readFile, readdir, rm, symlink } from 'node:fs/promises';
-import { spawnSync } from 'node:child_process';
-import { fileURLToPath } from 'node:url';
-import { join, resolve, sep } from 'node:path';
-import { test } from 'node:test';
-
-test('native-only build works without checkout engine bundles or SDK files', async () => {
- const cache = fileURLToPath(new URL('../../.cache/', import.meta.url));
- await mkdir(cache, { recursive: true });
- const fixture = await mkdtemp(join(cache, 'native-build-'));
- try {
- const hosting = join(fixture, 'hosting');
- await mkdir(join(hosting, 'scripts'), { recursive: true });
- await cp(new URL('../src/', import.meta.url), join(hosting, 'src'), { recursive: true });
- // The private storage adapter bundles this pure source-reference contract.
- // Neither dist/ nor lib/ exists in the isolated checkout.
- await mkdir(join(fixture, 'src'));
- await cp(
- new URL('../../src/program-store.ts', import.meta.url),
- join(fixture, 'src', 'program-store.ts'),
- );
- for (const name of ['build.mjs', 'build-boundary.mjs', 'edge-manifest.mjs'])
- await cp(new URL(`../scripts/${name}`, import.meta.url), join(hosting, 'scripts', name));
- await symlink(
- fileURLToPath(new URL('../node_modules/', import.meta.url)),
- join(hosting, 'node_modules'),
- 'junction',
- );
- const result = spawnSync(
- process.execPath,
- [join(hosting, 'scripts', 'build.mjs'), '--native-only'],
- { encoding: 'utf8', timeout: 20000 },
- );
- assert.equal(result.status, 0, result.stderr);
- const output = join(fixture, '.cache', 'hosted-worker');
- const entries = await readdir(output);
- assert.equal(entries.filter((name) => name.endsWith('.mjs')).length, 7);
- assert.ok(entries.every((name) => name.startsWith('native-')));
- for (const name of entries.filter((name) => name.endsWith('-build.json'))) {
- const manifest = JSON.parse(await readFile(join(output, name), 'utf8'));
- assert.ok(!manifest.inputs.some((path) => /edge-mcp|mcp-engine|\/lib\//.test(path)));
- }
- } finally {
- assert.ok(resolve(fixture).startsWith(`${resolve(cache)}${sep}native-build-`));
- await rm(fixture, { recursive: true, force: true });
- }
-});
diff --git a/hosting/test/native-evaluator.test.mjs b/hosting/test/native-evaluator.test.mjs
deleted file mode 100644
index 906ddf47..00000000
--- a/hosting/test/native-evaluator.test.mjs
+++ /dev/null
@@ -1,250 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, test } from 'node:test';
-import { fileURLToPath } from 'node:url';
-import { build } from 'esbuild';
-import { evaluateEvaluatorRequestV2 } from '../../lib/evaluator/index.js';
-
-const source = 'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}';
-let createNativeEvaluatorPort;
-let handleEvaluationRequest;
-const image = `sha256:${'a'.repeat(64)}`;
-before(async () => {
- const output = new URL('../../.cache/hosted-native-evaluator/client.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-evaluator.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- packages: 'external',
- alias: {
- '@instruktlabs/kiln/evaluator': fileURLToPath(
- new URL('../../lib/evaluator/index.js', import.meta.url),
- ),
- },
- });
- ({ createNativeEvaluatorPort } = await import(output));
- const handler = new URL('../../.cache/hosted-native-evaluator/handler.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/evaluation-request.ts', import.meta.url))],
- outfile: fileURLToPath(handler),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ handleEvaluationRequest } = await import(handler));
-});
-
-test('native evaluation uses the fixed private route and the real versioned engine protocol', async () => {
- let calls = 0;
- const port = createNativeEvaluatorPort({
- fetch: async (request) => {
- calls++;
- assert.equal(request.url, 'http://kiln-evaluator.internal/evaluate');
- assert.equal(request.method, 'POST');
- assert.equal(request.redirect, 'error');
- assert.equal(request.credentials, 'omit');
- assert.deepEqual([...request.headers.keys()].sort(), [
- 'content-length',
- 'content-type',
- 'x-kiln-deadline-ms',
- 'x-kiln-max-response-bytes',
- ]);
- assert.equal(request.headers.get('x-kiln-deadline-ms'), '60000');
- assert.equal(request.headers.get('x-kiln-max-response-bytes'), String(8 * 1024 * 1024));
- // Fixed trusted fixture, not an isolation assertion. Production runs this in a fresh VM.
- return handleEvaluationRequest(request, {
- executionImage: () => `registry.cloudflare.com/fixture/kiln@${image}`,
- async run(bytes, controls) {
- const input = new TextDecoder().decode(bytes);
- assert.equal(JSON.parse(input).limits.maxGlbBytes, 4 * 1024 * 1024);
- assert.ok(controls.deadlineMs > 0 && controls.deadlineMs <= 60_000);
- assert.equal(controls.maxResponseBytes, 8 * 1024 * 1024);
- return new TextEncoder().encode(await evaluateEvaluatorRequestV2(input));
- },
- });
- },
- });
- const rendered = await port.render(
- source,
- {},
- {
- deadlineMs: 120000,
- maxGlbBytes: 16 * 1024 * 1024,
- maxResponseBytes: 32 * 1024 * 1024,
- },
- );
- assert.equal(calls, 1);
- assert.equal(Buffer.from(rendered.glb).subarray(0, 4).toString(), 'glTF');
- assert.equal(port.executionImage(rendered), image);
- assert.equal(port.executionImage({ ...rendered }), undefined);
-});
-
-test('native evaluation requires outside-controller identity with otherwise valid stdout', async () => {
- for (const header of [undefined, 'latest', `sha256:${'A'.repeat(64)}`, `${image}, ${image}`]) {
- const port = createNativeEvaluatorPort({
- fetch: async (request) => {
- const data = JSON.parse(await evaluateEvaluatorRequestV2(await request.text()));
- return Response.json(data, { headers: header ? { 'x-kiln-execution-image': header } : {} });
- },
- });
- await assert.rejects(port.render(source), (error) => error.code === 'WORKER_FAILED');
- }
-});
-
-test('native evaluation rejects forged response identity and invalid UTF-8', async () => {
- const forged = createNativeEvaluatorPort({
- fetch: async (request) => {
- const result = JSON.parse(await evaluateEvaluatorRequestV2(await request.text()));
- result.requestId = 'other-request';
- return Response.json(result, { headers: { 'x-kiln-execution-image': image } });
- },
- });
- await assert.rejects(forged.render(source), (error) => error.code === 'PROTOCOL_ERROR');
- const invalid = createNativeEvaluatorPort({
- fetch: async () =>
- new Response(new Uint8Array([0xff]), {
- headers: { 'x-kiln-execution-image': image },
- }),
- });
- await assert.rejects(invalid.render(source), (error) => error.code === 'WORKER_FAILED');
-});
-
-test('native evaluation bounds declared and streamed output and redacts upstream errors', async () => {
- for (const make of [
- () => new Response('PRIVATE_SOURCE_PATH', { status: 503 }),
- () => new Response('private', { headers: { 'content-length': '999999999' } }),
- () => new Response('x'.repeat(2049), { headers: { 'x-kiln-execution-image': image } }),
- ]) {
- const port = createNativeEvaluatorPort({ fetch: async () => make() });
- await assert.rejects(port.render(source, {}, { maxResponseBytes: 2048 }), (error) => {
- assert.doesNotMatch(error.message, /PRIVATE_SOURCE_PATH|private|x{20}/);
- return error.code === 'WORKER_FAILED';
- });
- }
-});
-
-test('overlapping evaluations retain their own controller image identity', async () => {
- let started,
- finish,
- calls = 0;
- const ready = new Promise((resolve) => {
- started = resolve;
- });
- const released = new Promise((resolve) => {
- finish = resolve;
- });
- const other = `sha256:${'b'.repeat(64)}`;
- const port = createNativeEvaluatorPort({
- fetch: async (request) => {
- const first = ++calls === 1;
- const output = new TextEncoder().encode(
- await evaluateEvaluatorRequestV2(await request.text()),
- );
- return new Response(
- new ReadableStream({
- async start(controller) {
- if (first) {
- started();
- await released;
- }
- controller.enqueue(output);
- controller.close();
- },
- }),
- { headers: { 'x-kiln-execution-image': first ? image : other } },
- );
- },
- });
- const first = port.render(source);
- await ready;
- const second = await port.render(source);
- finish();
- assert.equal(port.executionImage(await first), image);
- assert.equal(port.executionImage(second), other);
-});
-
-test('native evaluation cancellation reaches a pending response body', async () => {
- const controller = new AbortController();
- let signal,
- cancelled = false,
- started;
- const ready = new Promise((resolve) => {
- started = resolve;
- });
- const port = createNativeEvaluatorPort({
- fetch: async (request) => {
- signal = request.signal;
- return new Response(
- new ReadableStream({
- pull() {
- started();
- },
- cancel() {
- cancelled = true;
- },
- }),
- { headers: { 'x-kiln-execution-image': image } },
- );
- },
- });
- const pending = port.render(source, {}, { signal: controller.signal });
- await ready;
- controller.abort(new Error('PRIVATE_ABORT_REASON'));
- await assert.rejects(
- pending,
- (error) => error.code === 'CANCELLED' && !error.message.includes('PRIVATE'),
- );
- assert.equal(signal.aborted, true);
- await new Promise((resolve) => setImmediate(resolve));
- assert.equal(cancelled, true);
-});
-
-test('native evaluation has no local fallback on transport failure or deadline', async () => {
- let lateCancelled = false;
- const deadline = createNativeEvaluatorPort({
- fetch: async () => {
- await new Promise((resolve) => setTimeout(resolve, 80));
- return new Response(
- new ReadableStream({
- cancel() {
- lateCancelled = true;
- },
- }),
- );
- },
- });
- await assert.rejects(
- deadline.render(source, {}, { deadlineMs: 25 }),
- (error) => error.code === 'DEADLINE_EXCEEDED',
- );
- await new Promise((resolve) => setTimeout(resolve, 100));
- assert.equal(lateCancelled, true);
- const failed = createNativeEvaluatorPort({
- fetch: async () => {
- throw new Error('PRIVATE_NETWORK_PATH');
- },
- });
- await assert.rejects(
- failed.render(source),
- (error) => error.code === 'WORKER_FAILED' && !error.message.includes('PRIVATE'),
- );
-});
-
-test('invalid controls and already-cancelled calls cannot dispatch native evaluation', async () => {
- let calls = 0;
- const port = createNativeEvaluatorPort({
- fetch: async () => {
- calls++;
- throw new Error('Must not dispatch');
- },
- });
- for (const controls of [
- { deadlineMs: 0 },
- { maxGlbBytes: -1 },
- { maxResponseBytes: NaN },
- { signal: AbortSignal.abort() },
- ])
- await assert.rejects(port.render(source, {}, controls));
- assert.equal(calls, 0);
-});
diff --git a/hosting/test/native-host-entry.test.mjs b/hosting/test/native-host-entry.test.mjs
deleted file mode 100644
index 9e6d0dab..00000000
--- a/hosting/test/native-host-entry.test.mjs
+++ /dev/null
@@ -1,26 +0,0 @@
-import assert from 'node:assert/strict';
-import { spawnSync } from 'node:child_process';
-import { fileURLToPath } from 'node:url';
-import { test } from 'node:test';
-
-test('native host entry rejects invalid public origins before loading its runtime', () => {
- for (const origin of [
- '',
- 'http://kiln.example.com',
- 'https://user:[email protected]',
- 'https://kiln.example.com/path',
- ]) {
- const result = spawnSync(
- process.execPath,
- [fileURLToPath(new URL('../container/serve.mjs', import.meta.url))],
- {
- env: { KILN_PUBLIC_ORIGIN: origin },
- encoding: 'utf8',
- timeout: 5000,
- },
- );
- assert.equal(result.status, 1);
- assert.equal(result.stdout, '');
- assert.equal(result.stderr, 'Kiln native host startup failed.\n');
- }
-});
diff --git a/hosting/test/native-host.test.mjs b/hosting/test/native-host.test.mjs
deleted file mode 100644
index c6f02362..00000000
--- a/hosting/test/native-host.test.mjs
+++ /dev/null
@@ -1,177 +0,0 @@
-import assert from 'node:assert/strict';
-import { request as httpRequest } from 'node:http';
-import { before, test } from 'node:test';
-import { fileURLToPath } from 'node:url';
-import { build } from 'esbuild';
-
-let createNativeHttpServer;
-before(async () => {
- // Keep the fixture under the private package so Node resolves its pinned adapter.
- const output = new URL(
- '../node_modules/.cache/hosted-native-http-server/host.mjs',
- import.meta.url,
- );
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-host.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- packages: 'external',
- });
- ({ createNativeHttpServer } = await import(output));
-});
-
-async function listen(t, handler, options = {}) {
- const server = createNativeHttpServer(handler, options);
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
- t.after(async () => {
- await new Promise((resolve, reject) => {
- server.close((error) => (error ? reject(error) : resolve()));
- server.closeAllConnections();
- });
- });
- return server;
-}
-function request(server, { path = '/mcp', headers = {}, method = 'POST', body = '{}' } = {}) {
- return new Promise((resolve, reject) => {
- const req = httpRequest(
- {
- hostname: '127.0.0.1',
- port: server.address().port,
- path,
- method,
- headers: { host: 'kiln-native.internal', 'content-type': 'application/json', ...headers },
- },
- (res) => {
- const chunks = [];
- res.on('data', (c) => chunks.push(c));
- res.on('end', () =>
- resolve({
- status: res.statusCode,
- headers: res.headers,
- body: Buffer.concat(chunks).toString(),
- }),
- );
- res.on('error', reject);
- },
- );
- req.on('error', reject);
- req.end(body);
- });
-}
-
-test('native Node adapter serves the fixed internal origin and a minimal readiness route', async (t) => {
- let calls = 0;
- const server = await listen(t, {
- fetch: async (req) => {
- calls++;
- assert.equal(req.url, 'http://kiln-native.internal/mcp');
- assert.equal(await req.text(), '{}');
- return new Response('ok');
- },
- });
- assert.equal((await request(server)).body, 'ok');
- const ready = await request(server, { path: '/_ready', method: 'GET', body: '' });
- assert.equal(ready.status, 204);
- assert.equal(ready.body, '');
- assert.equal(ready.headers['cache-control'], 'no-store');
- assert.equal(calls, 1);
-});
-
-test('native Node adapter refuses foreign Host, absolute paths and oversized inputs before MCP dispatch', async (t) => {
- let calls = 0;
- const server = await listen(t, {
- fetch: async () => {
- calls++;
- return new Response('must not be reached');
- },
- });
- for (const [options, status] of [
- [{ headers: { host: 'attacker.example' } }, 421],
- [{ path: 'http://kiln-native.internal/mcp' }, 404],
- [{ path: '/mcp?token=private' }, 404],
- [{ headers: { 'content-length': String(1024 * 1024 + 1) }, body: '' }, 413],
- ])
- assert.equal((await request(server, options)).status, status);
- // For a chunked flood the SDK exits IncomingMessage's async iterator at the
- // byte cap, which can close the Node socket before its 413 can be delivered.
- const oversized = await request(server, { body: 'x'.repeat(1024 * 1024 + 1) }).catch((error) => {
- assert.equal(error.code, 'ECONNRESET');
- return { status: 'closed' };
- });
- assert.ok(oversized.status === 413 || oversized.status === 'closed');
- assert.equal(calls, 0);
-});
-
-test('client disconnect reaches the Fetch handler without exposing its abort reason', async (t) => {
- let entered, aborted;
- const started = new Promise((resolve) => {
- entered = resolve;
- });
- const cancelled = new Promise((resolve) => {
- aborted = resolve;
- });
- const server = await listen(t, {
- fetch: async (req) => {
- req.signal.addEventListener('abort', () => aborted(), { once: true });
- entered();
- await cancelled;
- return new Response('late');
- },
- });
- const req = httpRequest(
- {
- hostname: '127.0.0.1',
- port: server.address().port,
- path: '/mcp',
- method: 'POST',
- headers: { host: 'kiln-native.internal' },
- },
- (res) => res.resume(),
- );
- req.on('error', () => {});
- req.end('{}');
- await started;
- req.destroy();
- await Promise.race([
- cancelled,
- new Promise((_, reject) => {
- const timer = setTimeout(() => reject(Error('Disconnect did not reach host')), 2000);
- timer.unref();
- }),
- ]);
-});
-
-test('native Node adapter applies an upload timeout before the Fetch handler starts', async (t) => {
- let calls = 0;
- const server = await listen(
- t,
- {
- fetch: async () => {
- calls++;
- return new Response('unexpected');
- },
- },
- { requestTimeoutMs: 50 },
- );
- const result = await new Promise((resolve) => {
- const req = httpRequest(
- {
- hostname: '127.0.0.1',
- port: server.address().port,
- path: '/mcp',
- method: 'POST',
- headers: { host: 'kiln-native.internal', 'content-length': '20' },
- },
- (res) => {
- res.resume();
- res.on('end', () => resolve(res.statusCode));
- },
- );
- req.on('error', () => resolve('closed'));
- req.write('{');
- });
- assert.ok(result === 408 || result === 'closed');
- assert.equal(calls, 0);
-});
diff --git a/hosting/test/native-http.test.mjs b/hosting/test/native-http.test.mjs
deleted file mode 100644
index 03657deb..00000000
--- a/hosting/test/native-http.test.mjs
+++ /dev/null
@@ -1,119 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-
-let NativeHttpClient;
-before(async () => {
- const output = new URL('../../.cache/hosted-http-test/client.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-http.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ NativeHttpClient } = await import(output));
-});
-
-test('storage retains bytes when the response stream reuses its read buffer', async () => {
- const shared = new Uint8Array(1);
- let value = 0;
- const client = new NativeHttpClient({
- fetch: async () =>
- new Response(
- new ReadableStream(
- {
- pull(controller) {
- if (++value === 4) return controller.close();
- shared[0] = value;
- controller.enqueue(shared);
- },
- },
- { highWaterMark: 0 },
- ),
- ),
- });
- assert.deepEqual(
- await client.bytes('/internal/programs', { limit: 32 }),
- new Uint8Array([1, 2, 3]),
- );
-});
-
-test('a continuously readable body cannot starve the storage deadline timer', async (t) => {
- let now = 1000;
- t.mock.method(Date, 'now', () => now);
- let pulls = 0;
- let cancelled = false;
- const client = new NativeHttpClient({
- timeoutMs: 25,
- fetch: async () =>
- new Response(
- new ReadableStream({
- pull(controller) {
- now += 10;
- if (++pulls === 100) controller.close();
- else controller.enqueue(new Uint8Array());
- },
- cancel() {
- cancelled = true;
- },
- }),
- ),
- });
- await assert.rejects(
- client.bytes('/internal/programs', { limit: 32 }),
- (error) => error.status === 504 && error.message === 'Storage request timed out',
- );
- assert.ok(pulls < 100, 'Stop reading even while microtasks prevent timer delivery');
- assert.equal(cancelled, true);
-});
-
-test('a response arriving after the deadline cannot bypass it before timers run', async (t) => {
- let now = 1000;
- t.mock.method(Date, 'now', () => now);
- let signal;
- const client = new NativeHttpClient({
- timeoutMs: 25,
- fetch: async (request) => {
- signal = request.signal;
- now += 30;
- return new Response('ok');
- },
- });
- await assert.rejects(
- client.bytes('/internal/programs', { limit: 32 }),
- (error) => error.status === 504 && error.message === 'Storage request timed out',
- );
- assert.equal(signal.aborted, true);
-});
-
-test('fixed native services cannot cross routes or forward identity headers', async () => {
- let calls = 0;
- const options = {
- fetch: async () => {
- calls++;
- return new Response('ok');
- },
- };
- const storage = new NativeHttpClient(options);
- const evaluator = new NativeHttpClient(options, 'Evaluator', 'evaluator');
- assert.throws(() => new NativeHttpClient(options, 'Invalid', 'https://example.com'));
- for (const path of ['/evaluate', '//kiln-evaluator.internal/evaluate'])
- await assert.rejects(storage.bytes(path, { limit: 8 }));
- for (const path of [
- '/internal/programs',
- '/evaluate?x=1',
- '/evaluate#x',
- '//example.com/evaluate',
- ])
- await assert.rejects(evaluator.bytes(path, { limit: 8 }));
- for (const header of ['authorization', 'cookie', 'x-tenant', 'x-artifact-name'])
- await assert.rejects(
- evaluator.bytes('/evaluate', { limit: 8, headers: { [header]: 'private' } }),
- );
- await assert.rejects(
- storage.bytes('/internal/programs', { limit: 8, headers: { 'x-kiln-deadline-ms': '25' } }),
- );
- assert.equal(calls, 0);
-});
diff --git a/hosting/test/native-materials.test.mjs b/hosting/test/native-materials.test.mjs
deleted file mode 100644
index 4ed643fd..00000000
--- a/hosting/test/native-materials.test.mjs
+++ /dev/null
@@ -1,282 +0,0 @@
-import assert from 'node:assert/strict';
-import { mkdir } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-import { createMaterialRecordV1 } from '../../lib/material-library-node.js';
-
-let NativeMaterialLibrary, runtime, namespace, sample;
-before(async () => {
- const output = new URL('../../.cache/native-material-test/native-materials.mjs', import.meta.url);
- await mkdir(fileURLToPath(new URL('./', output)), { recursive: true });
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-materials.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- packages: 'external',
- alias: {
- '@instruktlabs/kiln/material-library': fileURLToPath(
- new URL('../../lib/material-library.js', import.meta.url),
- ),
- '@instruktlabs/kiln/material-library/node': fileURLToPath(
- new URL('../../lib/material-library-node.js', import.meta.url),
- ),
- },
- });
- ({ NativeMaterialLibrary } = await import(output));
- const worker = await build({
- entryPoints: [fileURLToPath(new URL('../src/tenant-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- name: 'native-materials',
- modules: true,
- script: worker.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- r2Buckets: ['ARTIFACTS'],
- durableObjects: { TENANTS: { className: 'KilnTenant', useSQLite: true } },
- bindings: {
- STORAGE_MAX_BYTES: '4194304',
- STORAGE_MAX_OBJECTS: '128',
- STORAGE_MAX_GROUPS: '64',
- },
- outboundService: async () => {
- throw Error('No network');
- },
- }),
- unsafeInspectDurableObjects: true,
- });
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
- sample = await fixture('hosted-stone');
-});
-
-function fixture(materialId) {
- return createMaterialRecordV1({
- materialId,
- name: 'Hosted stone',
- tileable: true,
- sources: [
- {
- id: 'authored',
- kind: 'procedural',
- provider: 'Kiln',
- creator: 'Fixture author',
- license: {
- spdx: 'CC0-1.0',
- url: 'https://creativecommons.org/publicdomain/zero/1.0/',
- attribution: '',
- },
- originalFiles: [],
- },
- ],
- maps: [
- {
- slot: 'baseColor',
- sourceId: 'authored',
- transforms: [],
- procedural: {
- schemaVersion: 2,
- size: 8,
- usage: 'albedo',
- layers: [
- { op: 'noise', colorA: 0x779944, colorB: 0xeeeecc, seed: 17, scale: 4, octaves: 2 },
- ],
- },
- },
- ],
- });
-}
-after(async () => runtime?.dispose());
-const stub = (owner) => namespace.getByName(owner);
-const storage = (owner) => async (request) => {
- assert.equal(new URL(request.url).origin, 'http://kiln-storage.internal');
- assert.equal(request.headers.get('authorization'), null);
- return stub(owner).fetch(
- new Request(`https://tenant.internal${new URL(request.url).pathname}`, request),
- );
-};
-const library = (owner) => new NativeMaterialLibrary({ fetch: storage(owner) });
-const usage = async (owner) =>
- (await stub(owner).fetch('https://tenant.internal/internal/usage')).json();
-const read = (lib) => lib.read(sample.manifest.materialId, sample.manifest.revisionId);
-
-test('material import, list and exact reads survive a fresh host and tenant eviction while other accounts are denied', async () => {
- const original = structuredClone(sample);
- assert.deepEqual(await library('persist').import([sample]), [sample.manifest]);
- assert.deepEqual(await library('persist').list(), [sample.manifest]);
- await runtime.unsafeEvictDurableObject('native-materials', 'KilnTenant', {
- id: namespace.idFromName('persist').toString(),
- });
- assert.deepEqual(await read(library('persist')), original);
- await assert.rejects(read(library('foreign')), /not found/);
- assert.equal((await usage('foreign')).objects, 0);
- const count = await usage('persist');
- assert.equal(count.objects, 2);
- assert.equal(count.groups, 1);
- assert.ok(count.metadataBytes > 0);
-});
-
-test('concurrent identical imports are idempotent and discard losing staged files', async () => {
- const results = await Promise.all(
- Array.from({ length: 5 }, () => library('race').import([sample])),
- );
- for (const result of results) assert.deepEqual(result, [sample.manifest]);
- assert.deepEqual(await read(library('race')), sample);
- const count = await usage('race');
- assert.equal(count.objects, 2);
- assert.equal(count.groups, 1);
-});
-
-test('invalid batches and path identities are rejected before any storage write', async () => {
- let calls = 0;
- const lib = new NativeMaterialLibrary({
- fetch: async (request) => {
- calls++;
- return storage('invalid')(request);
- },
- });
- const bad = await fixture('bad-stone');
- bad.files['baseColor.png'][bad.files['baseColor.png'].length - 1] ^= 1;
- await assert.rejects(lib.import([sample, bad]), /integrity|hash|PNG/);
- for (const [id, revision] of [
- ['../victim', sample.manifest.revisionId],
- [sample.manifest.materialId, `${sample.manifest.revisionId}\n`],
- ])
- await assert.rejects(lib.read(id, revision));
- await assert.rejects(lib.import([]));
- await assert.rejects(lib.import(Array(101).fill(sample)));
- await assert.rejects(lib.import([sample, sample]), /Duplicate/);
- assert.equal(calls, 0);
- assert.equal((await usage('invalid')).objects, 0);
-});
-
-test('imports snapshot caller-owned records before asynchronous verification', async () => {
- const input = structuredClone(sample);
- const importing = library('snapshot').import([input]);
- input.manifest.name = 'Mutated caller manifest';
- input.files['baseColor.png'].fill(0);
- assert.deepEqual(await importing, [sample.manifest]);
- assert.deepEqual(await read(library('snapshot')), sample);
-});
-
-test('quota failure preserves earlier atomic imports and catalogue paging has no duplicates or omissions', async () => {
- const records = await Promise.all(
- Array.from({ length: 65 }, (_, index) => fixture(`paged-${String(index).padStart(3, '0')}`)),
- );
- const lib = library('paged');
- await assert.rejects(lib.import(records), /quota reached/);
- const manifests = records.slice(0, 64).map((record) => record.manifest);
- assert.deepEqual(await lib.list(), manifests);
- const count = await usage('paged');
- assert.equal(count.groups, 64);
- assert.equal(count.objects, 128);
- // Idempotent reads/imports still work at the storage limit.
- assert.deepEqual(await lib.import([records[0]]), [records[0].manifest]);
-});
-
-test('partial staging failure cleans acknowledged files without storing a material', async () => {
- let uploads = 0;
- const lib = new NativeMaterialLibrary({
- fetch: async (request) => {
- if (new URL(request.url).pathname === '/internal/artifacts' && ++uploads === 2)
- return new Response('fixture upload unavailable', { status: 503 });
- return storage('staged-failure')(request);
- },
- });
- await assert.rejects(lib.import([sample]), /unavailable/);
- assert.deepEqual(await library('staged-failure').list(), []);
- assert.equal((await usage('staged-failure')).objects, 0);
-});
-
-test('lost commit acknowledgement cannot remove pinned material bytes', async () => {
- const lib = new NativeMaterialLibrary({
- fetch: async (request) => {
- const response = await storage('lost')(request);
- if (new URL(request.url).pathname === '/internal/materials/commit') {
- assert.equal(response.status, 201);
- await response.body?.cancel();
- return new Response('fixture lost acknowledgement', { status: 503 });
- }
- return response;
- },
- });
- await assert.rejects(lib.import([sample]), /unavailable/);
- assert.deepEqual(await read(library('lost')), sample);
- assert.equal((await usage('lost')).objects, 2);
-});
-
-test('material retention shares artifact quotas and corrupted objects cannot be read', async () => {
- await library('integrity').import([sample]);
- const db = await runtime.unsafeGetDurableObjectStorage('native-materials', 'KilnTenant', {
- id: namespace.idFromName('integrity').toString(),
- });
- await db.exec('UPDATE artifacts SET expires_at=1');
- await stub('integrity').fetch('https://tenant.internal/internal/maintenance', { method: 'POST' });
- assert.deepEqual(await read(library('integrity')), sample);
- const rows = await db.exec("SELECT object_key FROM artifacts WHERE filename='baseColor.png'");
- await (await runtime.getR2Bucket('ARTIFACTS')).put(rows[0].object_key, 'corrupt');
- await assert.rejects(read(library('integrity')), /integrity|unavailable/);
-});
-
-test('material index rejects arbitrary storage keys, extra filenames, foreign file IDs and malformed pagination', async () => {
- await library('indexed').import([sample]);
- const encoded = sample.manifest.revisionId.slice(7);
- const record = await (
- await stub('indexed').fetch(
- `https://tenant.internal/internal/materials/${sample.manifest.materialId}/${encoded}`,
- )
- ).json();
- for (const input of [
- {
- materialId: sample.manifest.materialId,
- revisionId: sample.manifest.revisionId,
- files: record.files,
- key: 'assets/project/victim',
- },
- { materialId: '../victim', revisionId: sample.manifest.revisionId, files: record.files },
- {
- materialId: sample.manifest.materialId,
- revisionId: sample.manifest.revisionId,
- files: { ...record.files, 'asset.glb': record.files['manifest.json'] },
- },
- ])
- assert.equal(
- (
- await stub('indexed').fetch('https://tenant.internal/internal/materials/commit', {
- method: 'POST',
- body: JSON.stringify(input),
- })
- ).status,
- 400,
- );
- assert.equal(
- (
- await stub('foreign-index').fetch('https://tenant.internal/internal/materials/commit', {
- method: 'POST',
- body: JSON.stringify({
- materialId: sample.manifest.materialId,
- revisionId: sample.manifest.revisionId,
- files: record.files,
- }),
- })
- ).status,
- 404,
- );
- assert.equal(
- (
- await stub('indexed').fetch('https://tenant.internal/internal/materials/list', {
- method: 'POST',
- body: JSON.stringify({ after: 'assets/project/elsewhere' }),
- })
- ).status,
- 400,
- );
-});
diff --git a/hosting/test/native-mcp.test.mjs b/hosting/test/native-mcp.test.mjs
deleted file mode 100644
index 07831766..00000000
--- a/hosting/test/native-mcp.test.mjs
+++ /dev/null
@@ -1,1040 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { mkdir, readFile } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-import { createKilnMcpServer, kilnMcpToolDefs } from '../../dist/mcp-engine.mjs';
-import { renderGLB } from '../../lib/render.js';
-import { evaluateEvaluatorRequestV2 } from '../../lib/evaluator/index.js';
-import { encodePng } from '../../lib/views/png.js';
-
-const publicOrigin = 'https://kiln.example.com';
-const source =
- "function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#aaaaaa'),{parent:r});return r;}";
-let createNativeMcpHandler;
-let loadNativeMcpRuntime;
-let loadContainerMcpRuntime;
-let createNativeEvaluatorPort;
-let runtime;
-let namespace;
-let runIntegratedOnce, integratedSource;
-let runLifecycleOnce, lifecycleCases, lifecycleBudget;
-let routeEdgeMcp;
-const handlers = [];
-before(async () => {
- const outfile = fileURLToPath(
- new URL('../../.cache/hosted-mcp-test/native-mcp.mjs', import.meta.url),
- );
- await mkdir(fileURLToPath(new URL('../../.cache/hosted-mcp-test/', import.meta.url)), {
- recursive: true,
- });
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-mcp.ts', import.meta.url))],
- outfile,
- bundle: true,
- format: 'esm',
- platform: 'node',
- packages: 'external',
- alias: Object.fromEntries(
- [
- ['assets', 'assets'],
- ['assets/node', 'assets-node'],
- ['material-library/node', 'material-library-node'],
- ['material-library', 'material-library'],
- ['workspace', 'workspace'],
- ['evaluator', 'evaluator/index'],
- ['composer', 'composer/index'],
- ].map(([name, file]) => [
- `@instruktlabs/kiln/${name}`,
- fileURLToPath(new URL(`../../lib/${file}.js`, import.meta.url)),
- ]),
- ),
- });
- ({ createNativeMcpHandler, loadNativeMcpRuntime, loadContainerMcpRuntime } = await import(
- new URL('../../.cache/hosted-mcp-test/native-mcp.mjs', import.meta.url)
- ));
- const evaluatorOutput = new URL(
- '../../.cache/hosted-mcp-test/native-evaluator.mjs',
- import.meta.url,
- );
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-evaluator.ts', import.meta.url))],
- outfile: fileURLToPath(evaluatorOutput),
- bundle: true,
- format: 'esm',
- platform: 'node',
- packages: 'external',
- alias: {
- '@instruktlabs/kiln/evaluator': fileURLToPath(
- new URL('../../lib/evaluator/index.js', import.meta.url),
- ),
- },
- });
- ({ createNativeEvaluatorPort } = await import(evaluatorOutput));
- const worker = await build({
- entryPoints: [fileURLToPath(new URL('../src/tenant-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: worker.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- r2Buckets: ['ARTIFACTS'],
- durableObjects: { TENANTS: { className: 'KilnTenant', useSQLite: true } },
- bindings: {
- STORAGE_MAX_BYTES: String(16 * 1024 * 1024),
- STORAGE_MAX_OBJECTS: '256',
- STORAGE_MAX_GROUPS: '64',
- },
- outboundService: async () => {
- throw new Error('No external requests');
- },
- }),
- );
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
- const trial = new URL('../../.cache/hosted-mcp-test/integrated-run.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../probe/integrated-run.ts', import.meta.url))],
- outfile: fileURLToPath(trial),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ runIntegratedOnce, integratedSource } = await import(trial));
- const lifecycle = new URL('../../.cache/hosted-mcp-test/lifecycle-run.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../probe/lifecycle-run.ts', import.meta.url))],
- outfile: fileURLToPath(lifecycle),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ runLifecycleOnce, lifecycleCases, lifecycleBudget } = await import(lifecycle));
- const edge = new URL('../../.cache/hosted-mcp-test/edge.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/edge-mcp.ts', import.meta.url))],
- outfile: fileURLToPath(edge),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ routeEdgeMcp } = await import(edge));
-});
-after(async () => {
- for (const handler of handlers) await handler.close();
- await runtime?.dispose();
-});
-
-function host(
- owner,
- options = {},
- evaluator = {
- render: async (code, renderOptions) => {
- // Explicit fixed trusted fixture only; this port is never in a production bundle.
- assert.equal(code, source);
- return renderGLB(code, renderOptions);
- },
- },
- viewRenderPort,
-) {
- const handler = createNativeMcpHandler(
- { createServer: createKilnMcpServer, evaluatorPort: evaluator, viewRenderPort },
- {
- publicOrigin,
- storage: {
- fetch: async (request) => {
- assert.equal(new URL(request.url).origin, 'http://kiln-storage.internal');
- assert.equal(request.headers.get('authorization'), null);
- return namespace
- .get(namespace.idFromName(owner))
- .fetch(new Request(`https://tenant.internal${new URL(request.url).pathname}`, request));
- },
- },
- ...options,
- },
- );
- handlers.push(handler);
- return handler;
-}
-function request(method, params = {}, { modern = true, headers = {}, signal, id = 1 } = {}) {
- const meta = modern
- ? {
- _meta: {
- 'io.modelcontextprotocol/protocolVersion': '2026-07-28',
- 'io.modelcontextprotocol/clientInfo': { name: 'hosted-fixture', version: '1' },
- 'io.modelcontextprotocol/clientCapabilities': {},
- },
- }
- : {};
- return new Request('http://kiln-native.internal/mcp', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- ...(modern
- ? {
- 'mcp-protocol-version': '2026-07-28',
- 'mcp-method': method,
- ...(params.name || params.uri ? { 'mcp-name': params.name ?? params.uri } : {}),
- }
- : { 'mcp-protocol-version': '2025-11-25' }),
- ...headers,
- },
- body: JSON.stringify({ jsonrpc: '2.0', id, method, params: { ...params, ...meta } }),
- signal,
- });
-}
-async function message(response) {
- const body = await response.text();
- if (response.headers.get('content-type')?.includes('text/event-stream')) {
- const events = body
- .split('\n')
- .filter((line) => line.startsWith('data:'))
- .map((line) => JSON.parse(line.slice(5)));
- return events.findLast((event) => event.id !== undefined);
- }
- return JSON.parse(body);
-}
-async function rpc(handler, method, params, options) {
- const response = await handler.fetch(request(method, params, options));
- assert.equal(response.status, 200);
- assert.equal(response.headers.get('cache-control'), 'no-store');
- const value = await message(response);
- assert.equal(value.error, undefined, JSON.stringify(value.error));
- return value.result;
-}
-async function tool(handler, name, args, options) {
- const value = await rpc(handler, 'tools/call', { name, arguments: args }, options);
- assert.notEqual(value.isError, true, JSON.stringify(value.content));
- return JSON.parse(value.content.find((item) => item.type === 'text').text);
-}
-
-test('HTTP serves both protocol eras and exactly the engine registry surface', async () => {
- const handler = host('protocol');
- const expected = kilnMcpToolDefs({
- programStore: {},
- assetLibrary: {},
- materialLibrary: {},
- workspace: {},
- })
- .map((def) => def.name)
- .sort();
- const current = await rpc(handler, 'tools/list');
- assert.deepEqual(current.tools.map((item) => item.name).sort(), expected);
- const manifest = JSON.parse(
- await readFile(new URL('../src/generated/edge-manifest.json', import.meta.url), 'utf8'),
- );
- assert.deepEqual(current.tools, manifest.tools);
- for (const [method, key] of [
- ['resources/list', 'resources'],
- ['resources/templates/list', 'resourceTemplates'],
- ]) {
- assert.deepEqual((await rpc(handler, method))[key], manifest[key]);
- }
- assert.equal(current.resultType, 'complete');
- for (const version of ['2025-03-26', '2025-06-18', '2025-11-25']) {
- const initialized = await rpc(
- handler,
- 'initialize',
- { protocolVersion: version, capabilities: {}, clientInfo: { name: 'legacy', version: '1' } },
- { modern: false },
- );
- assert.equal(initialized.protocolVersion, version);
- assert.equal(initialized.instructions, manifest.instructions);
- assert.deepEqual(initialized.serverInfo, manifest.serverInfo);
- assert.deepEqual(initialized.capabilities, manifest.capabilities);
- const legacy = await rpc(
- handler,
- 'tools/list',
- {},
- { modern: false, headers: { 'mcp-protocol-version': version } },
- );
- assert.deepEqual(legacy.tools.map((item) => item.name).sort(), expected);
- }
- const mismatch = await handler.fetch(
- request('tools/list', {}, { headers: { 'mcp-method': 'tools/call' } }),
- );
- assert.equal(mismatch.status, 400);
- assert.ok((await message(mismatch)).error);
-});
-
-test('real HTTP tools validate, render, save, restore and read exact source after reconnect', async () => {
- let evaluations = 0;
- const port = createNativeEvaluatorPort({
- fetch: async (request) => {
- assert.equal(request.url, 'http://kiln-evaluator.internal/evaluate');
- assert.equal(request.headers.get('authorization'), null);
- const json = await request.text();
- // Fixed trusted fixture only. Actual VM dispatch and cleanup require provider qualification.
- assert.equal(JSON.parse(json).code, source);
- evaluations++;
- return new Response(await evaluateEvaluatorRequestV2(json), {
- headers: { 'x-kiln-execution-image': `sha256:${'a'.repeat(64)}` },
- });
- },
- });
- const first = host('lifecycle', {}, port);
- const validated = await tool(first, 'kiln_validate', { code: source });
- const rendered = await rpc(first, 'tools/call', {
- name: 'kiln_render',
- arguments: { programRef: validated.programRef, capture: { preset: '1x1' } },
- });
- assert.equal(rendered.isError, undefined);
- assert.ok(rendered.content.some((item) => item.type === 'image'));
- assert.ok(evaluations > 0, 'Real MCP render must cross the versioned private transport');
- const saved = await tool(first, 'kiln_save', {
- programRef: validated.programRef,
- collection: 'project',
- name: 'HTTP box',
- });
- assert.equal(saved.asset.build.engine, `cloudflare-container:sha256:${'a'.repeat(64)}`);
- assert.match(
- saved.downloadUrls['asset.glb'],
- /^https:\/\/kiln\.example\.com\/downloads\/[a-f0-9]{64}\/asset\.glb$/,
- );
- const link = new URL(saved.downloadUrls['source.kiln.js']);
- const browserBytes = await namespace
- .getByName('lifecycle')
- .fetch(`https://tenant.internal/internal${link.pathname}`);
- assert.equal(await browserBytes.text(), source);
- await first.close();
- const second = host('lifecycle');
- const restored = await tool(second, 'kiln_assets', {
- action: 'restore',
- collection: 'project',
- assetId: saved.asset.assetId,
- revisionId: saved.asset.revisionId,
- });
- assert.equal(restored.programRef, validated.programRef);
- const uri = `kiln://assets/project/${saved.asset.assetId}/${saved.asset.revisionId}/source.kiln.js`;
- assert.equal((await rpc(second, 'resources/read', { uri })).contents[0].text, source);
- const savedManifest = JSON.parse(
- (
- await rpc(second, 'resources/read', {
- uri: uri.replace('source.kiln.js', 'manifest.json'),
- })
- ).contents[0].text,
- );
- assert.equal(savedManifest.build.engine, `cloudflare-container:sha256:${'a'.repeat(64)}`);
- const other = await rpc(host('other'), 'tools/call', {
- name: 'kiln_source',
- arguments: { programRef: restored.programRef },
- });
- assert.equal(other.isError, true);
- assert.ok(!JSON.stringify(other).includes(source));
-});
-
-test('render, save, restore and export work with a fresh native host for every MCP request', async () => {
- const owner = 'one-request-per-vm';
- const call = async (name, args) => {
- const handler = host(owner);
- try {
- return await tool(handler, name, args);
- } finally {
- await handler.close();
- }
- };
- const rendered = await call('kiln_render', { code: source, capture: { preset: '1x1' } });
- const saved = await call('kiln_save', {
- programRef: rendered.programRef,
- collection: 'project',
- name: 'Fresh host fixture',
- });
- const restored = await call('kiln_assets', {
- action: 'restore',
- collection: 'project',
- assetId: saved.asset.assetId,
- revisionId: saved.asset.revisionId,
- });
- assert.equal(restored.programRef, rendered.programRef);
- const original = await call('kiln_source', { programRef: restored.programRef });
- assert(JSON.stringify(original).includes('createRoot'));
- const exported = await call('kiln_export', {
- collection: 'project',
- assetId: saved.asset.assetId,
- revisionId: saved.asset.revisionId,
- });
- assert(exported);
-});
-
-test('durable materials bind exact revisions across fresh MCP hosts, save their closure and deny foreign accounts', async () => {
- const owner = 'material-lifecycle';
- let evaluations = 0,
- expectedSource;
- const port = createNativeEvaluatorPort({
- fetch: async (request) => {
- const json = await request.text();
- const input = JSON.parse(json);
- assert.equal(input.code, expectedSource);
- assert.equal(input.options.materialResources.records.length, 1);
- evaluations++;
- return new Response(await evaluateEvaluatorRequestV2(json), {
- headers: { 'x-kiln-execution-image': `sha256:${'b'.repeat(64)}` },
- });
- },
- });
- const call = async (name, args, account = owner, raw = false) => {
- const handler = host(account, {}, port);
- try {
- return raw
- ? await rpc(handler, 'tools/call', { name, arguments: args })
- : await tool(handler, name, args);
- } finally {
- await handler.close();
- }
- };
- const created = await call('kiln_material', {
- action: 'create-procedural',
- draft: {
- materialId: 'mcp-stone',
- name: 'MCP stone',
- tileable: true,
- sources: [
- {
- id: 'authored',
- kind: 'procedural',
- provider: 'Kiln',
- creator: 'Fixture author',
- license: {
- spdx: 'CC0-1.0',
- url: 'https://creativecommons.org/publicdomain/zero/1.0/',
- attribution: '',
- },
- originalFiles: [],
- },
- ],
- maps: [
- {
- slot: 'baseColor',
- sourceId: 'authored',
- transforms: [],
- procedural: {
- schemaVersion: 2,
- size: 8,
- usage: 'albedo',
- layers: [
- { op: 'noise', colorA: 0x779944, colorB: 0xeeeecc, seed: 17, scale: 4, octaves: 2 },
- ],
- },
- },
- ],
- },
- });
- const { material, portableSpec } = created;
- const { materialId, revisionId } = material;
- assert.equal(
- (await call('kiln_material', { action: 'list' })).materials[0].revisionId,
- revisionId,
- );
- assert.deepEqual(
- (await call('kiln_material', { action: 'get', materialId, revisionId })).material,
- material,
- );
- const materialDependencies = [{ resourceId: materialId, revisionId, sha256: revisionId }];
- expectedSource = `async function build(){const r=createRoot('Root');const m=await compilePortableMaterialSpecV2(${JSON.stringify(portableSpec)});createPart('Body',boxGeo(1,1,1),m,{parent:r});return r;}`;
- const rendered = await call('kiln_render', {
- code: expectedSource,
- materialDependencies,
- capture: { preset: '1x1' },
- });
- const saved = await call('kiln_save', {
- programRef: rendered.programRef,
- materialDependencies,
- collection: 'project',
- name: 'Material box',
- });
- assert.ok(saved.downloadUrls['materials.kiln.json']);
- const path = new URL(saved.downloadUrls['materials.kiln.json']).pathname;
- const closure = await (
- await namespace.getByName(owner).fetch(`https://tenant.internal/internal${path}`)
- ).json();
- assert.deepEqual(closure.records[0].manifest, material);
- const exportResult = await call('kiln_export', {
- collection: 'project',
- assetId: saved.asset.assetId,
- revisionId: saved.asset.revisionId,
- });
- assert(exportResult);
- const before = evaluations;
- const foreign = await call(
- 'kiln_render',
- { code: expectedSource, materialDependencies, capture: { preset: '1x1' } },
- 'material-foreign',
- true,
- );
- assert.equal(foreign.isError, true);
- assert.match(JSON.stringify(foreign), /Locked material unavailable/);
- assert.equal(evaluations, before, 'Foreign material denial occurs before native evaluation');
- assert.deepEqual(
- (await call('kiln_material', { action: 'list' }, 'material-foreign')).materials,
- [],
- );
- // A saved asset's editable closure is independent of the live material library.
- const tenant = namespace.getByName(owner);
- const indexed = await (
- await tenant.fetch(
- `https://tenant.internal/internal/materials/${materialId}/${revisionId.slice(7)}`,
- )
- ).json();
- assert.equal(
- (
- await tenant.fetch(`https://tenant.internal/internal/groups/${indexed.id}`, {
- method: 'DELETE',
- })
- ).status,
- 200,
- );
- assert.deepEqual((await call('kiln_material', { action: 'list' })).materials, []);
- const imported = await call('kiln_import', {
- sourceCollection: 'project',
- collection: 'library',
- assetId: saved.asset.assetId,
- revisionId: saved.asset.revisionId,
- });
- assert.deepEqual(
- (await call('kiln_material', { action: 'get', materialId, revisionId })).material,
- material,
- );
- const originalGlb = await (
- await tenant.fetch(
- `https://tenant.internal/internal${new URL(saved.downloadUrls['asset.glb']).pathname}`,
- )
- ).arrayBuffer();
- const importedGlb = await (
- await tenant.fetch(
- `https://tenant.internal/internal${new URL(imported.downloadUrls['asset.glb']).pathname}`,
- )
- ).arrayBuffer();
- assert.deepEqual(Buffer.from(importedGlb), Buffer.from(originalGlb));
- const rebuilt = await call('kiln_render', {
- programRef: rendered.programRef,
- materialDependencies,
- capture: { preset: '1x1' },
- });
- assert.equal(rebuilt.programRef, rendered.programRef);
-});
-
-test('the complete fixed provider sequence matches real fresh-host MCP and private asset contracts', async () => {
- const values = new Map();
- let count = 0,
- paused = false;
- const store = {
- get: async (key) => structuredClone(values.get(key)),
- put: async (key, value) => values.set(key, structuredClone(value)),
- transaction: async (fn) => fn(store),
- };
- const receipts = [];
- const result = await runIntegratedOnce(store, {
- open: async () => {},
- close: async () => {},
- pause: async () => {
- paused = true;
- },
- status: async () => ({ paused, activeRequests: 0, pendingCleanup: 0, maxConcurrent: 1 }),
- retain: async (name, bytes) => {
- receipts.push({ name, bytes });
- },
- dispatch: async (owner, request) => {
- if (++count > 9) return new Response('quota', { status: 429 });
- const handler = host(
- owner,
- {},
- {
- render: async (code, options) => {
- assert.equal(code, integratedSource);
- return renderGLB(code, options);
- },
- },
- async (request) => {
- const size = request.size ?? request.width;
- return {
- ok: true,
- rendererId: 'dawn-vulkan:software-fixture',
- viewsPng: (request.viewDirs ?? request.cameras).map(() =>
- encodePng(new Uint8Array(size * size * 3).fill(128), size, size),
- ),
- derivativeFidelity: {
- materialFaithful: true,
- inputGlbSha256: `sha256:${createHash('sha256').update(request.glb).digest('hex')}`,
- },
- };
- },
- );
- const response = await handler.fetch(new Request('http://kiln-native.internal/mcp', request));
- const bytes = await response.arrayBuffer();
- await handler.close();
- return new Response(bytes, { status: response.status, headers: response.headers });
- },
- });
- assert.equal(result.passed, true, JSON.stringify(result));
- assert.equal(result.results.length, 10);
- assert.equal(receipts.length, 10);
-});
-
-test('private lifecycle trial qualifies fresh hosts, editable materials, exact downloads and pinned provenance', async () => {
- const values = new Map();
- const store = {
- get: async (key) => structuredClone(values.get(key)),
- put: async (key, value) => values.set(key, structuredClone(value)),
- transaction: async (fn) => fn(store),
- };
- const fixtureOrigin = 'https://kiln-private-qualification.invalid';
- const expectedImage = `sha256:${'b'.repeat(64)}`;
- let calls = 0,
- evaluations = 0,
- renders = 0,
- paused = true,
- opened = 0,
- closed = 0;
- const evidence = [];
- const ownerName = (account) => `full-lifecycle-${account}`;
- const evaluator = createNativeEvaluatorPort({
- fetch: async (request) => {
- const json = await request.text();
- const input = JSON.parse(json);
- assert.equal(input.options.materialResources.records.length, 1);
- assert.equal(
- input.options.materialResources.records[0].manifest.materialId,
- 'qualification-stone',
- );
- evaluations++;
- return new Response(await evaluateEvaluatorRequestV2(json), {
- headers: { 'x-kiln-execution-image': expectedImage },
- });
- },
- });
- const ports = {
- expectedImage,
- open: async () => {
- opened++;
- paused = false;
- },
- close: async () => {
- closed++;
- },
- pause: async () => {
- paused = true;
- },
- status: async () => ({ paused, activeRequests: 0, pendingCleanup: 0 }),
- retain: async (name, bytes) => {
- evidence.push({ name, bytes: Buffer.from(bytes) });
- },
- mcp: async (account, request) => {
- assert.equal(request.headers.get('authorization'), null);
- assert.equal(request.headers.get('cookie'), null);
- const routed = await routeEdgeMcp(request);
- if (routed instanceof Response) return routed;
- if (++calls > lifecycleBudget.coordinator) return new Response('quota', { status: 429 });
- const handler = host(
- ownerName(account),
- { publicOrigin: fixtureOrigin },
- evaluator,
- async (input) => {
- renders++;
- const size = input.size ?? input.width;
- return {
- ok: true,
- rendererId: 'dawn-vulkan:software-fixture',
- viewsPng: (input.viewDirs ?? input.cameras).map(() =>
- encodePng(new Uint8Array(size * size * 3).fill(128), size, size),
- ),
- derivativeFidelity: {
- materialFaithful: true,
- inputGlbSha256: `sha256:${createHash('sha256').update(input.glb).digest('hex')}`,
- },
- };
- },
- );
- const response = await handler.fetch(new Request('http://kiln-native.internal/mcp', routed));
- const bytes = await response.arrayBuffer();
- await handler.close();
- return new Response(bytes, { status: response.status, headers: response.headers });
- },
- download: async (account, path, signal) => {
- if (account === 'anonymous') return new Response(null, { status: 401 });
- return namespace
- .getByName(ownerName(account))
- .fetch(`https://tenant.internal/internal${path}`, { signal });
- },
- dropMaterial: async (materialId, revisionId) => {
- const tenant = namespace.getByName(ownerName('owner'));
- const group = await (
- await tenant.fetch(
- `https://tenant.internal/internal/materials/${materialId}/${revisionId.slice(7)}`,
- )
- ).json();
- assert.equal(
- (
- await tenant.fetch(`https://tenant.internal/internal/groups/${group.id}`, {
- method: 'DELETE',
- })
- ).status,
- 200,
- );
- },
- };
- const result = await runLifecycleOnce(store, ports);
- assert.equal(result.passed, true, JSON.stringify(result));
- assert.equal(result.results.length, 21);
- assert.deepEqual(
- result.results.map((value) => value.name),
- lifecycleCases,
- );
- assert.equal(calls, 15);
- assert.equal(evaluations, 3);
- assert.equal(renders, 3);
- assert.equal(opened, 1);
- assert.equal(closed, 1);
- assert.equal(paused, true);
- assert.equal(
- result.results.find((value) => value.name === 'manifest').savedEngine,
- `cloudflare-container:${expectedImage}`,
- );
- assert.equal(evidence.length, 20);
- assert.deepEqual(await runLifecycleOnce(store, ports), result);
- assert.equal(calls, 15);
- assert.equal(opened, 1);
- assert.equal(closed, 1);
- // Reuse actual engine responses to attack the trial's acceptance checks.
- const recorded = new Map(evidence.map((item) => [item.name, item.bytes]));
- const sourceMessage = JSON.parse(recorded.get('source').toString());
- const source = JSON.parse(
- sourceMessage.result.content.find((item) => item.type === 'text').text,
- ).code;
- const attacks = [
- ['foreign-download', () => Buffer.from(source)],
- ['anonymous-download', () => Buffer.from(source)],
- [
- 'manifest',
- (bytes) => {
- const message = JSON.parse(bytes.toString());
- const manifest = JSON.parse(message.result.contents[0].text);
- manifest.build.engine = 'unverified';
- message.result.contents[0].text = JSON.stringify(manifest);
- return Buffer.from(JSON.stringify(message));
- },
- ],
- [
- 'glb-download',
- (bytes) => {
- const changed = Buffer.from(bytes);
- changed[changed.length - 1] ^= 1;
- return changed;
- },
- ],
- [
- 'foreign-source',
- (bytes) => {
- const message = JSON.parse(bytes.toString());
- message.debug = { source };
- return Buffer.from(JSON.stringify(message));
- },
- ],
- [
- 'foreign-source',
- (bytes) => {
- const message = JSON.parse(bytes.toString());
- message.debug = { text: JSON.stringify({ code: source }) };
- return Buffer.from(JSON.stringify(message));
- },
- ],
- [
- 'foreign-material',
- (bytes) => {
- const message = JSON.parse(bytes.toString());
- const materialMessage = JSON.parse(recorded.get('material-get').toString());
- message.debug = JSON.parse(
- materialMessage.result.content.find((item) => item.type === 'text').text,
- ).material;
- return Buffer.from(JSON.stringify(message));
- },
- ],
- ];
- for (const [failedCase, mutate] of attacks) {
- let index = 0,
- sealed = false,
- halted = false;
- const replayStoreValues = new Map();
- const replayStore = {
- get: async (key) => structuredClone(replayStoreValues.get(key)),
- put: async (key, value) => {
- replayStoreValues.set(key, structuredClone(value));
- },
- transaction: async (fn) => fn(replayStore),
- };
- const response = () => {
- const name = lifecycleCases[index++];
- const original = recorded.get(name);
- assert(original, name);
- const bytes = name === failedCase ? mutate(original) : original;
- return new Response(bytes, {
- status: result.results.find((item) => item.name === name).status,
- headers: { 'cache-control': 'no-store' },
- });
- };
- const failed = await runLifecycleOnce(replayStore, {
- expectedImage,
- open: async () => {},
- close: async () => {
- sealed = true;
- },
- pause: async () => {
- halted = true;
- },
- status: async () => ({ paused: halted, activeRequests: 0, pendingCleanup: 0 }),
- mcp: async () => response(),
- download: async () => response(),
- retain: async () => {},
- dropMaterial: async () => {
- index++;
- },
- });
- assert.equal(failed.passed, false, failedCase);
- assert.equal(failed.results.at(-1).name, failedCase);
- assert.equal(failed.results.at(-1).passed, false);
- assert.equal(index, lifecycleCases.indexOf(failedCase) + 1);
- assert.equal(sealed && halted, true);
- }
-});
-
-test('native MCP uses the material-view port and retains truthful CPU fallback', async () => {
- const metal =
- 'function build(){return new THREE.Mesh(boxGeo(1,1,1),pbrMaterial({albedo:0x8899aa,metalness:0.5,roughness:0.5}));}';
- let views = 0;
- const evaluate = {
- render: async (code, options) => {
- assert.equal(code, metal);
- return renderGLB(code, options);
- },
- };
- const handler = host('material', {}, evaluate, async (request, execution) => {
- views++;
- assert(execution.signal);
- assert.equal(execution.signal.aborted, false);
- const size = request.size ?? request.width;
- return {
- ok: true,
- rendererId: 'dawn-vulkan:software-fixture',
- viewsPng: (request.viewDirs ?? request.cameras).map(() =>
- encodePng(new Uint8Array(size * size * 3).fill(128), size, size),
- ),
- derivativeFidelity: {
- materialFaithful: true,
- inputGlbSha256: `sha256:${createHash('sha256').update(request.glb).digest('hex')}`,
- },
- };
- });
- const result = await rpc(handler, 'tools/call', {
- name: 'kiln_render',
- arguments: { code: metal, capture: { preset: '1x1' } },
- });
- assert.equal(result.isError, undefined);
- assert.equal(views, 1);
- assert.ok(result.content.some((value) => value.type === 'image'));
- assert.match(JSON.stringify(result), /full-material/);
- const unavailable = host('material-fallback', {}, evaluate, async () => ({
- ok: false,
- rendererId: 'unavailable',
- error: 'Hosted software rendering is unavailable',
- }));
- const fallback = await rpc(unavailable, 'tools/call', {
- name: 'kiln_render',
- arguments: { code: metal, capture: { preset: '1x1' } },
- });
- assert.equal(fallback.isError, undefined);
- assert.ok(fallback.content.some((value) => value.type === 'image'));
- assert.match(JSON.stringify(fallback), /geometry-flat/);
-});
-
-test('native HTTP validates its private route, Origin, body and credentials before engine dispatch', async () => {
- const handler = host('requests');
- for (const [url, status] of [
- ['http://foreign.internal/mcp', 421],
- ['http://kiln-native.internal/private', 404],
- ['http://kiln-native.internal/mcp?token=secret', 400],
- ]) {
- const result = await handler.fetch(new Request(url));
- assert.equal(result.status, status);
- await result.body?.cancel();
- }
- for (const headers of [
- { origin: 'https://foreign.example' },
- { authorization: 'Bearer forbidden' },
- { cookie: 'forbidden' },
- { 'x-kiln-tenant': 'forged' },
- ]) {
- const result = await handler.fetch(request('tools/list', {}, { headers }));
- assert.equal(result.status, 403);
- assert.ok(!(await result.text()).includes('forbidden'));
- }
- const oversized = await handler.fetch(
- new Request('http://kiln-native.internal/mcp', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: 'x'.repeat(1024 * 1024 + 1),
- }),
- );
- assert.equal(oversized.status, 413);
- await oversized.body?.cancel();
- const allowed = await rpc(handler, 'tools/list', {}, { headers: { origin: publicOrigin } });
- assert.ok(allowed.tools.length);
-});
-
-test('request cancellation reaches native evaluation and holds admission until the evaluator settles', async () => {
- let entered;
- const started = new Promise((resolve) => {
- entered = resolve;
- });
- let settle;
- let executionSignal;
- const handler = host(
- 'cancel',
- {},
- {
- render: async (_code, _options, controls) => {
- executionSignal = controls.signal;
- entered();
- return new Promise((_resolve, reject) => {
- settle = () => reject(new Error('fixture cancelled'));
- });
- },
- },
- );
- const abort = new AbortController();
- const pending = handler.fetch(
- request(
- 'tools/call',
- { name: 'kiln_render', arguments: { code: source } },
- { signal: abort.signal },
- ),
- );
- await started;
- abort.abort('private cancellation detail');
- const stopped = await pending;
- assert.equal(stopped.status, 499);
- assert.ok(!(await stopped.text()).includes('private cancellation detail'));
- assert.equal(executionSignal.aborted, true);
- const busy = await handler.fetch(request('tools/list'));
- assert.equal(busy.status, 429);
- await busy.body?.cancel();
- settle();
- await new Promise((resolve) => setImmediate(resolve));
- assert.ok((await rpc(handler, 'tools/list')).tools.length);
-});
-
-test('production runtime refuses an unqualified host and never selects a trusted fallback', async () => {
- assert.throws(
- () => createNativeMcpHandler({ createServer: createKilnMcpServer }, { publicOrigin }),
- /evaluator/i,
- );
- await assert.rejects(
- loadNativeMcpRuntime({ bwrapPath: '/kiln-fixture-no-such-executable' }),
- /isolation readiness/i,
- );
-});
-
-test('explicit container runtime loads the installed engine and fails closed when its remote evaluator is unavailable', async () => {
- let calls = 0;
- const runtime = await loadContainerMcpRuntime({
- fetch: async () => {
- calls++;
- throw new Error('PRIVATE_NETWORK_ERROR');
- },
- });
- assert.equal(typeof runtime.createServer, 'function');
- const handler = host('remote-failure', {}, runtime.evaluatorPort);
- const result = await rpc(handler, 'tools/call', {
- name: 'kiln_render',
- arguments: { code: source },
- });
- assert.equal(result.isError, true);
- assert.ok(!result.content.some((item) => item.type === 'image'));
- assert.doesNotMatch(JSON.stringify(result), /PRIVATE_NETWORK_ERROR/);
- assert.ok(calls > 0);
-});
-
-test('slow request bodies expire, cancel their stream and release admission', async () => {
- let cancelled = false;
- const handler = host('slow-body', { requestTimeoutMs: 30 });
- const response = await handler.fetch(
- new Request('http://kiln-native.internal/mcp', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- duplex: 'half',
- body: new ReadableStream({
- cancel() {
- cancelled = true;
- },
- }),
- }),
- );
- assert.equal(response.status, 504);
- await response.body?.cancel();
- assert.equal(cancelled, true);
- const next = await handler.fetch(new Request('http://kiln-native.internal/mcp'));
- assert.equal(next.status, 405);
- await next.body?.cancel();
-});
-
-test('an already-cancelled request returns a redacted result without unhandled rejection', async () => {
- const handler = host('already-cancelled');
- const abort = new AbortController();
- abort.abort('sensitive reason');
- const response = await handler.fetch(request('tools/list', {}, { signal: abort.signal }));
- assert.equal(response.status, 499);
- assert.ok(!(await response.text()).includes('sensitive reason'));
- await new Promise((resolve) => setImmediate(resolve));
- assert.ok((await rpc(handler, 'tools/list')).tools.length);
-});
-
-test('response size limits stop streaming, and closing the host prevents further work', async () => {
- const handler = host('response-limit', { maxResponseBytes: 128 });
- const response = await handler.fetch(request('tools/list'));
- await assert.rejects(response.text(), /size limit/);
- await handler.close();
- const closed = await handler.fetch(request('tools/list'));
- assert.equal(closed.status, 503);
- await closed.body?.cancel();
-});
-
-test('closing a legacy SSE response cancels its evaluator and keeps its occupied slot', async () => {
- let entered;
- const started = new Promise((resolve) => {
- entered = resolve;
- });
- let settle;
- let executionSignal;
- const handler = host(
- 'legacy-cancel',
- {},
- {
- render: async (_code, _options, controls) => {
- executionSignal = controls.signal;
- entered();
- return new Promise((_resolve, reject) => {
- settle = () => reject(new Error('fixture cancelled'));
- });
- },
- },
- );
- const response = await handler.fetch(
- request('tools/call', { name: 'kiln_render', arguments: { code: source } }, { modern: false }),
- );
- assert.match(response.headers.get('content-type'), /text\/event-stream/);
- await started;
- await response.body.cancel();
- assert.equal(executionSignal.aborted, true);
- const busy = await handler.fetch(request('tools/list'));
- assert.equal(busy.status, 429);
- await busy.body?.cancel();
- settle();
- await new Promise((resolve) => setImmediate(resolve));
- assert.ok((await rpc(handler, 'tools/list')).tools.length);
-});
diff --git a/hosting/test/native-programs.test.mjs b/hosting/test/native-programs.test.mjs
deleted file mode 100644
index 3eb312ba..00000000
--- a/hosting/test/native-programs.test.mjs
+++ /dev/null
@@ -1,280 +0,0 @@
-import assert from 'node:assert/strict';
-import { AsyncLocalStorage } from 'node:async_hooks';
-import { createHash } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-import { createKilnToolHost } from '../../dist/mcp-engine.mjs';
-
-let NativeProgramStore;
-let runtime;
-let namespace;
-const canonical = (source) => `sha256:${createHash('sha256').update(source).digest('hex')}`;
-before(async () => {
- const client = await build({
- entryPoints: [fileURLToPath(new URL('../src/native-programs.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'node',
- });
- ({ NativeProgramStore } = await import(
- `data:text/javascript;base64,${Buffer.from(`${client.outputFiles[0].text}\n//# sourceURL=kiln-native-programs-test.mjs`).toString('base64')}`
- ));
- const worker = await build({
- entryPoints: [fileURLToPath(new URL('../src/tenant-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- name: 'native-programs',
- modules: true,
- script: worker.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- r2Buckets: ['ARTIFACTS'],
- durableObjects: { TENANTS: { className: 'KilnTenant', useSQLite: true } },
- bindings: {
- STORAGE_MAX_BYTES: String(4 * 1024 * 1024),
- STORAGE_MAX_OBJECTS: '32',
- STORAGE_MAX_GROUPS: '8',
- },
- outboundService: async () => {
- throw new Error('Storage must not fetch externally');
- },
- }),
- unsafeInspectDurableObjects: true,
- });
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
-});
-after(async () => runtime?.dispose());
-
-function store(owner, options = {}) {
- return new NativeProgramStore({
- ...options,
- fetch: async (request) => {
- const url = new URL(request.url);
- assert.equal(url.origin, 'http://kiln-storage.internal');
- assert.equal(request.redirect, 'error');
- assert.equal(request.credentials, 'omit');
- assert.deepEqual(
- [...request.headers.keys()].sort(),
- request.method === 'POST' ? ['content-length', 'content-type'] : [],
- );
- // Test transport only. Production must bind this owner outside the container.
- return namespace
- .get(namespace.idFromName(owner))
- .fetch(new Request(`https://tenant.internal${url.pathname}`, request));
- },
- });
-}
-
-test('native source client retains exact bytes and resolves durable references after restart', async () => {
- const source = '\ufeff// Café 🏠\r\nfunction build() { return createRoot("Home"); }';
- const first = store('bytes');
- const ref = await first.put(source);
- assert.equal(ref, canonical(source));
- const handle = await first.shortRef(ref);
- assert.equal(handle, `p_${ref.slice(7)}`);
- assert.equal(await first.get(handle), source);
- await runtime.unsafeEvictDurableObject('native-programs', 'KilnTenant', {
- id: namespace.idFromName('bytes').toString(),
- });
- const second = store('bytes');
- assert.equal(await second.get(handle), source);
- assert.equal(await second.put(source), ref);
- const stats = await second.stats();
- assert.equal(stats.entries, 1);
- assert.equal(stats.bytes, Buffer.byteLength(source));
- assert.equal(stats.maxSourceBytes, 1024 * 1024);
- await assert.rejects(store('other').get(ref), /Program not found.*Send the source again/s);
- await assert.rejects(store('other').shortRef(ref), /Program not found/);
-});
-
-test('invalid source and references are rejected before any storage request', async () => {
- let requests = 0;
- const client = new NativeProgramStore({
- fetch: async () => {
- requests++;
- throw new Error();
- },
- });
- for (const source of ['\ud800', 'a'.repeat(1024 * 1024 + 1)]) {
- await assert.rejects(client.put(source), /Unicode|1 MiB/);
- }
- for (const ref of ['../../keys', 'https://other.example/source', `sha256:${'a'.repeat(64)}\n`]) {
- await assert.rejects(client.get(ref), /Invalid program reference/);
- }
- await assert.rejects(client.get(`p_${'a'.repeat(12)}`), /Program not found/);
- assert.equal(requests, 0);
-});
-
-test('native client rejects corrupt, oversized, redirected and malformed storage responses', async () => {
- const ref = canonical('original');
- const cases = [
- () => new Response('changed'),
- () => new Response(Buffer.from([0xff])),
- () => new Response('a'.repeat(1024 * 1024 + 1)),
- () => new Response(null, { status: 302, headers: { location: 'https://external.example/' } }),
- () => new Response('fixture-sensitive-response', { status: 500 }),
- ];
- for (const response of cases) {
- const client = new NativeProgramStore({ fetch: async () => response() });
- await assert.rejects(client.get(ref), (error) => {
- assert.doesNotMatch(error.message, /fixture-sensitive|changed|external\.example/);
- return /integrity|limit|unavailable|response/.test(error.message);
- });
- }
- const wrong = new NativeProgramStore({
- fetch: async () =>
- Response.json(
- {
- programRef: canonical('different'),
- shortRef: `p_${'a'.repeat(64)}`,
- artifactId: '0'.repeat(32),
- },
- { status: 201 },
- ),
- });
- await assert.rejects(wrong.put('original'), /response/);
- const badStats = new NativeProgramStore({
- fetch: async () =>
- Response.json({
- entries: -1,
- bytes: 0,
- maxSourceBytes: 1024 * 1024,
- eviction: 'none',
- }),
- });
- await assert.rejects(badStats.stats(), /response/);
- const full = new NativeProgramStore({
- fetch: async () => new Response('private detail', { status: 507 }),
- });
- await assert.rejects(full.put('source'), /quota/);
- const missingBody = new NativeProgramStore({
- fetch: async () =>
- new Response(null, {
- headers: { 'content-length': '1' },
- }),
- });
- await assert.rejects(missingBody.get(canonical('')), /response/);
-});
-
-test('a storage deadline covers stalled headers and bodies and cancels the response stream', async () => {
- const ref = canonical('source');
- let sentSignal;
- const stalled = new NativeProgramStore({
- timeoutMs: 25,
- fetch: (request) => {
- sentSignal = request.signal;
- return new Promise(() => {});
- },
- });
- await assert.rejects(stalled.get(ref), /timed out/);
- assert.equal(sentSignal.aborted, true);
- let cancelled = false;
- const body = new NativeProgramStore({
- timeoutMs: 25,
- fetch: async () =>
- new Response(
- new ReadableStream({
- cancel() {
- cancelled = true;
- },
- }),
- ),
- });
- await assert.rejects(body.get(ref), /timed out/);
- assert.equal(cancelled, true);
-});
-
-test('request cancellation is scoped per call and never leaks a supplied abort reason', async () => {
- const signals = new AsyncLocalStorage();
- const a = new AbortController();
- const b = new AbortController();
- const seen = [];
- const client = new NativeProgramStore({
- signal: () => signals.getStore(),
- fetch: (request) => {
- seen.push(request.signal);
- if (seen.length === 2) return Promise.resolve(new Response('source'));
- return new Promise(() => {});
- },
- });
- const pending = signals.run(a.signal, () => client.get(canonical('source')));
- await Promise.resolve();
- a.abort(new Error('fixture-sensitive-abort-reason'));
- await assert.rejects(pending, (error) => error.message === 'Source storage request cancelled');
- assert.equal(await signals.run(b.signal, () => client.get(canonical('source'))), 'source');
- assert.equal(seen[0].aborted, true);
- assert.equal(seen[1].aborted, false);
- await assert.rejects(
- signals.run(a.signal, () => client.get(canonical('source'))),
- /cancelled/,
- );
- assert.equal(seen.length, 2);
-});
-
-test('real engine tools validate, read, edit and CPU-render durable source across hosts', async () => {
- const source = `const meta = { name: 'Post' };\nfunction build() { const r = createRoot('Post'); createPart('Body', boxGeo(1, 2, 1), gameMaterial(0x888888), { parent: r, position: [0, 1, 0] }); return r; }\n`;
- const make = (owner) =>
- createKilnToolHost({
- programStore: store(owner),
- // Only this fixed trusted fixture may use the local evaluator. This is not
- // a hosted execution entrypoint or evidence of provider isolation.
- evaluatorProfile: 'trusted-local',
- });
- const invoke = async (host, name, args) => {
- const result = await host.callTool(name, args, { signal: new AbortController().signal });
- assert.notEqual(result.isError, true, JSON.stringify(result.content));
- return { result, data: JSON.parse(result.content.find((item) => item.type === 'text').text) };
- };
- const first = make('engine');
- const { data: initial } = await invoke(first, 'kiln_validate', { code: source });
- assert.match(initial.programRef, /^p_[a-f0-9]{64}$/);
- assert.equal(
- (await invoke(first, 'kiln_source', { programRef: initial.programRef })).data.code,
- source,
- );
- const { result: edited, data } = await invoke(first, 'kiln_edit', {
- programRef: initial.programRef,
- edits: [{ oldString: 'boxGeo(1, 2, 1)', newString: 'boxGeo(1, 3, 1)' }],
- capture: { preset: '1x1' },
- });
- assert.equal(data.ok, true);
- assert.equal(data.parentRef, initial.programRef);
- assert.notEqual(data.programRef, initial.programRef);
- const image = edited.content.find((item) => item.type === 'image');
- assert.ok(image, 'Actual edit must produce an image');
- assert.equal(Buffer.from(image.data, 'base64').subarray(1, 4).toString(), 'PNG');
- await runtime.unsafeEvictDurableObject('native-programs', 'KilnTenant', {
- id: namespace.idFromName('engine').toString(),
- });
- const restarted = make('engine');
- assert.equal(
- (await invoke(restarted, 'kiln_source', { programRef: initial.programRef })).data.code,
- source,
- );
- assert.equal(
- (await invoke(restarted, 'kiln_source', { programRef: data.programRef })).data.code,
- source.replace('boxGeo(1, 2, 1)', 'boxGeo(1, 3, 1)'),
- );
- const render = await invoke(restarted, 'kiln_render', {
- programRef: data.programRef,
- capture: { preset: '1x1' },
- });
- assert.equal(render.data.ok, true);
- assert.ok(render.result.content.some((item) => item.type === 'image'));
- const denied = await make('another-engine').callTool(
- 'kiln_source',
- { programRef: data.programRef },
- { signal: new AbortController().signal },
- );
- assert.equal(denied.isError, true);
- assert.match(denied.content[0].text, /Program not found/);
- assert.equal((await store('engine').stats()).entries, 2);
-});
diff --git a/hosting/test/native-render.test.mjs b/hosting/test/native-render.test.mjs
deleted file mode 100644
index 1a3b8e8c..00000000
--- a/hosting/test/native-render.test.mjs
+++ /dev/null
@@ -1,224 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, test } from 'node:test';
-import { fileURLToPath } from 'node:url';
-import { build } from 'esbuild';
-import { copyFile } from 'node:fs/promises';
-import { spawnSync } from 'node:child_process';
-import { renderGLB } from '../../lib/render.js';
-import { encodePng } from '../../lib/views/png.js';
-import { captureViewPngsViaPort } from '../../lib/views/port.js';
-
-let createNativeRenderPort, encodeRenderRequest, decodeRenderRequest, encodeRenderResult;
-let glb;
-const rendererId = 'dawn-vulkan:llvmpipe-fixture';
-const request = () => ({ glb, viewDirs: [[1, 0.4, 1]], size: 32, backdrop: 'dark' });
-const png = () => encodePng(new Uint8Array(32 * 32 * 3).fill(100), 32, 32);
-before(async () => {
- const output = new URL('../../.cache/hosted-native-render/native-render.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-render.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- packages: 'external',
- alias: {
- '@instruktlabs/kiln/composer': fileURLToPath(
- new URL('../../lib/composer/index.js', import.meta.url),
- ),
- },
- });
- ({ createNativeRenderPort, encodeRenderRequest, decodeRenderRequest, encodeRenderResult } =
- await import(output));
- ({ glb } = await renderGLB(
- 'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}',
- ));
-});
-function success(input, extra = {}) {
- return encodeRenderResult(input, {
- rendererId,
- backend: 'vulkan',
- software: true,
- views: [png()],
- ...extra,
- });
-}
-test('software transport binds exact GLB bytes and uses only the fixed private route', async () => {
- let calls = 0;
- const port = createNativeRenderPort({
- fetch: async (incoming) => {
- calls++;
- assert.equal(incoming.url, 'http://kiln-renderer.internal/render');
- assert.equal(incoming.redirect, 'error');
- assert.equal(incoming.credentials, 'omit');
- assert.equal(incoming.headers.get('x-kiln-deadline-ms'), '30000');
- assert.equal(incoming.headers.get('authorization'), null);
- const input = decodeRenderRequest(new Uint8Array(await incoming.arrayBuffer()));
- assert.deepEqual(input.request.glb, glb);
- assert.equal(input.request.backdrop, 'dark');
- return new Response(success(input));
- },
- });
- const result = await port(request());
- assert.equal(calls, 1);
- assert.equal(result.ok, true);
- assert.equal(result.rendererId, rendererId);
- assert.deepEqual(result.viewsPng[0], png());
- assert.equal(result.derivativeFidelity.materialFaithful, true);
-});
-test('camera mode preserves exact cameras, dimensions and presentation identity', async () => {
- const camera = {
- position: [3, 2, 4],
- target: [0, 0, 0],
- up: [0, 1, 0],
- fovDeg: 50,
- aspect: 1,
- near: 0.1,
- far: 100,
- };
- const input = {
- glb,
- cameras: [camera],
- width: 32,
- height: 32,
- lightingPresetId: 'review-neutral-v1',
- };
- const port = createNativeRenderPort({
- fetch: async (req) => {
- const parsed = decodeRenderRequest(new Uint8Array(await req.arrayBuffer()));
- assert.deepEqual(parsed.request.cameras, [camera]);
- return new Response(
- success(parsed, {
- cameras: [camera],
- width: 32,
- height: 32,
- lightingPresetId: 'review-neutral-v1',
- }),
- );
- },
- });
- const result = await port(input);
- assert.equal(result.ok, true);
- assert.deepEqual(result.cameras, [camera]);
- assert.equal(result.width, 32);
-});
-test('input limits reject unknown authority, invalid cameras, excessive pixels and oversized GLBs before transport', async () => {
- let calls = 0;
- const port = createNativeRenderPort({
- fetch: async () => {
- calls++;
- throw Error('must not run');
- },
- });
- for (const value of [
- { ...request(), tenant: 'other' },
- { ...request(), viewDirs: [[0, 0, 0]] },
- { ...request(), size: 2048 },
- { ...request(), viewDirs: Array.from({ length: 12 }, () => [1, 0, 0]), size: 1024 },
- { ...request(), glb: new Uint8Array(4 * 1024 * 1024 + 1) },
- ]) {
- assert.equal((await port(value)).ok, false);
- }
- assert.equal(calls, 0);
- const wire = JSON.parse(new TextDecoder().decode(encodeRenderRequest(request()).bytes));
- for (const value of [
- { ...wire, tenant: 'other' },
- { ...wire, glbBase64: '!!!' },
- { ...wire, options: { ...wire.options, glb: 'replace' } },
- { ...wire, version: 'future' },
- ]) {
- assert.throws(() => decodeRenderRequest(new TextEncoder().encode(JSON.stringify(value))));
- }
-});
-test('forged result identity, GPU claims, dimensions and excessive output fail closed without echoing diagnostics', async () => {
- for (const change of [
- (r) => ({ ...r, requestId: 'other' }),
- (r) => ({ ...r, inputGlbSha256: `sha256:${'a'.repeat(64)}` }),
- (r) => ({ ...r, software: false }),
- (r) => ({ ...r, viewsBase64: [] }),
- (r) => ({ ...r, viewsBase64: ['!!!!'] }),
- (r) => ({ ...r, unknown: 'PRIVATE_SOURCE' }),
- ]) {
- const port = createNativeRenderPort({
- fetch: async (req) => {
- const input = decodeRenderRequest(new Uint8Array(await req.arrayBuffer()));
- return Response.json(change(JSON.parse(new TextDecoder().decode(success(input)))));
- },
- });
- const result = await port(request());
- assert.equal(result.ok, false);
- assert.ok(!JSON.stringify(result).includes('PRIVATE_SOURCE'));
- }
- for (const respond of [
- () => new Response('PRIVATE_PATH', { status: 503 }),
- () => new Response('x', { headers: { 'content-length': '999999999' } }),
- ]) {
- const result = await createNativeRenderPort({ fetch: async () => respond() })(request());
- assert.equal(result.ok, false);
- assert.ok(!JSON.stringify(result).includes('PRIVATE_PATH'));
- }
-});
-test('the engine still owns PNG validation and failed-render fallback', async () => {
- const port = createNativeRenderPort({
- fetch: async (req) => {
- const input = decodeRenderRequest(new Uint8Array(await req.arrayBuffer()));
- return new Response(success(input, { views: [Buffer.from('invalid PNG')] }));
- },
- });
- const result = await captureViewPngsViaPort(port, glb, 1000, [[1, 0.4, 1]], 32);
- assert.equal(result.ok, false);
-});
-test('execution cancellation aborts the transport and disposes a late response', async () => {
- let entered,
- finish,
- cancelled = false;
- const started = new Promise((resolve) => {
- entered = resolve;
- });
- const waiting = new Promise((resolve) => {
- finish = resolve;
- });
- let signal;
- const port = createNativeRenderPort({
- fetch: async (req) => {
- signal = req.signal;
- entered();
- return waiting;
- },
- });
- const abort = new AbortController();
- const pending = port(request(), { signal: abort.signal });
- await started;
- abort.abort();
- assert.equal((await pending).ok, false);
- assert.equal(signal.aborted, true);
- finish(
- new Response(
- new ReadableStream({
- cancel() {
- cancelled = true;
- },
- }),
- ),
- );
- await new Promise((resolve) => setImmediate(resolve));
- assert.equal(cancelled, true);
-});
-
-test('one-shot renderer rejects malformed input before loading a graphics device', async () => {
- const entry = new URL('../../.cache/hosted-native-render/render.mjs', import.meta.url);
- await copyFile(new URL('../container/render.mjs', import.meta.url), entry);
- for (const input of [
- Buffer.from('{'),
- Buffer.from(encodeRenderRequest({ ...request(), glb: Buffer.from('not a GLB') }).bytes),
- ]) {
- const result = spawnSync(process.execPath, [fileURLToPath(entry)], {
- input,
- timeout: 10000,
- maxBuffer: 1024 * 1024,
- });
- assert.equal(result.status, 1);
- assert.equal(result.stdout.length, 0);
- assert.equal(result.stderr.toString(), 'Kiln software render input or execution failed.\n');
- }
-});
diff --git a/hosting/test/native-workspace.test.mjs b/hosting/test/native-workspace.test.mjs
deleted file mode 100644
index e840f3a1..00000000
--- a/hosting/test/native-workspace.test.mjs
+++ /dev/null
@@ -1,185 +0,0 @@
-import assert from 'node:assert/strict';
-import { mkdir } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-import { createMaterialRecordV1 } from '../../lib/material-library-node.js';
-
-let NativeMaterialWorkspace, first, second;
-before(async () => {
- const output = new URL('../../.cache/native-workspace-test/workspace.mjs', import.meta.url);
- await mkdir(fileURLToPath(new URL('./', output)), { recursive: true });
- await build({
- entryPoints: [fileURLToPath(new URL('../src/native-workspace.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- packages: 'external',
- alias: Object.fromEntries(
- [
- ['workspace', 'workspace'],
- ['material-library', 'material-library'],
- ['material-library/node', 'material-library-node'],
- ].map(([name, file]) => [
- `@instruktlabs/kiln/${name}`,
- fileURLToPath(new URL(`../../lib/${file}.js`, import.meta.url)),
- ]),
- ),
- });
- ({ NativeMaterialWorkspace } = await import(output));
- const create = (seed) =>
- createMaterialRecordV1({
- materialId: 'stone',
- name: 'Stone',
- tileable: true,
- sources: [
- {
- id: 'authored',
- kind: 'procedural',
- provider: 'Kiln',
- creator: 'Test author',
- license: {
- spdx: 'CC0-1.0',
- url: 'https://creativecommons.org/publicdomain/zero/1.0/',
- attribution: '',
- },
- originalFiles: [],
- },
- ],
- maps: [
- {
- slot: 'baseColor',
- sourceId: 'authored',
- transforms: [],
- procedural: {
- schemaVersion: 2,
- size: 8,
- usage: 'albedo',
- layers: [
- { op: 'noise', colorA: 0x779944, colorB: 0xeeeecc, seed, scale: 4, octaves: 2 },
- ],
- },
- },
- ],
- });
- [first, second] = await Promise.all([create(17), create(18)]);
-});
-const pin = (record) => ({
- resourceId: record.manifest.materialId,
- revisionId: record.manifest.revisionId,
- sha256: record.manifest.revisionId,
-});
-const library = {
- read: async (id, rev) => {
- const record = [first, second].find(
- (r) => r.manifest.materialId === id && r.manifest.revisionId === rev,
- );
- if (!record) throw Error('not found');
- return structuredClone(record);
- },
-};
-const deferred = () => {
- let resolve;
- const promise = new Promise((done) => {
- resolve = done;
- });
- return { promise, resolve };
-};
-
-test('material binding stays isolated across overlapping operations and disappears outside them', async () => {
- const workspace = new NativeMaterialWorkspace(library);
- const firstReady = deferred(),
- secondReady = deferred();
- const run = (record, ready, other) =>
- workspace.run({ materialDependencies: [pin(record)] }, async () => {
- ready.resolve();
- await other.promise;
- assert.deepEqual(workspace.current().materialDependencies, [pin(record)]);
- assert.deepEqual(workspace.current().materialResources.records[0].manifest, record.manifest);
- assert.equal(workspace.current().project, undefined);
- return record.manifest.revisionId;
- });
- assert.equal(workspace.current(), undefined);
- const results = await Promise.all([
- run(first, firstReady, secondReady),
- run(second, secondReady, firstReady),
- ]);
- assert.deepEqual(results, [first.manifest.revisionId, second.manifest.revisionId]);
- assert.equal(workspace.current(), undefined);
-});
-
-test('nested operations inherit pins, explicitly replace revisions and can select standalone without inherited pins', async () => {
- const workspace = new NativeMaterialWorkspace(library);
- await workspace.run({ materialDependencies: [pin(first)] }, async () => {
- const binding = workspace.current();
- await workspace.run({}, async () => assert.equal(workspace.current(), binding));
- await workspace.run({ materialDependencies: [pin(second)] }, async () => {
- assert.deepEqual(workspace.current().materialDependencies, [pin(second)]);
- });
- await workspace.run({ projectId: null }, async () => {
- assert.deepEqual(workspace.current().materialDependencies, []);
- assert.deepEqual(workspace.current().materialResources.records, []);
- });
- assert.equal(workspace.current(), binding);
- });
-});
-
-test('invalid identities, hashes, oversized pin sets and unsupported projects fail before loading material bytes', async () => {
- let reads = 0,
- executions = 0;
- const workspace = new NativeMaterialWorkspace({
- read: async (...args) => {
- reads++;
- return library.read(...args);
- },
- });
- for (const selection of [
- { projectId: 'local-only' },
- { projectRevision: `r_0000000001_${'a'.repeat(64)}` },
- { materialDependencies: [{ ...pin(first), resourceId: '../escape' }] },
- { materialDependencies: [{ ...pin(first), revisionId: `${first.manifest.revisionId}\n` }] },
- {
- materialDependencies: [
- pin(first),
- { ...pin(second), resourceId: 'other', sha256: first.manifest.revisionId },
- ],
- },
- {
- materialDependencies: Array.from({ length: 17 }, (_, i) => ({
- ...pin(first),
- resourceId: `resource-${i}`,
- })),
- },
- ])
- await assert.rejects(
- workspace.run(selection, async () => {
- executions++;
- }),
- );
- assert.equal(reads, 0);
- assert.equal(executions, 0);
-});
-
-test('missing and identity-swapped library records cannot enter an evaluation binding', async () => {
- const missing = new NativeMaterialWorkspace({
- read: async () => {
- throw Error('private transport detail');
- },
- });
- await assert.rejects(
- missing.run({ materialDependencies: [pin(first)] }, async () =>
- assert.fail('must not execute'),
- ),
- (error) =>
- /Locked material unavailable/.test(error.message) &&
- !error.message.includes('private transport detail'),
- );
- const swapped = new NativeMaterialWorkspace({ read: async () => second });
- await assert.rejects(
- swapped.run({ materialDependencies: [pin(first)] }, async () =>
- assert.fail('must not execute'),
- ),
- /identity/,
- );
-});
diff --git a/hosting/test/operations-worker.ts b/hosting/test/operations-worker.ts
deleted file mode 100644
index dabe2f01..00000000
--- a/hosting/test/operations-worker.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import gateway, { type Env } from '../src/worker';
-import { readOperationalHealth } from '../src/operations';
-
-// Captured datapoints and faults are confined to this local fixture.
-const points: AnalyticsEngineDataPoint[] = [];
-export default {
- async fetch(request: Request, bindings: Env, ctx: ExecutionContext) {
- const url = new URL(request.url);
- const env = {
- ...bindings,
- OPERATIONS: {
- writeDataPoint(point: AnalyticsEngineDataPoint) {
- if (request.headers.has('x-fixture-metrics-failure'))
- throw new Error('private-metrics-error');
- points.push(point);
- },
- },
- NATIVE_COMPUTE: {
- async health() {
- return { paused: false, activeRequests: 0, pendingCleanup: 0, maxConcurrent: 2 };
- },
- },
- } as unknown as Env;
- if (request.headers.has('x-fixture-database-failure'))
- env.ACCOUNTS = {
- withSession() {
- throw new Error('private-database-error');
- },
- } as unknown as D1Database;
- if (url.pathname === '/fixture/points') return Response.json(points.splice(0));
- if (url.pathname === '/fixture/health')
- return Response.json(await readOperationalHealth(env, 1000000));
- if (url.pathname === '/fixture/scheduled') {
- try {
- await gateway.scheduled(
- { cron: '* * * * *', scheduledTime: Date.now(), noRetry() {} },
- env,
- );
- return new Response('ok');
- } catch {
- return new Response('unavailable', { status: 503 });
- }
- }
- return gateway.fetch(request, env, ctx);
- },
-};
diff --git a/hosting/test/operations.test.mjs b/hosting/test/operations.test.mjs
deleted file mode 100644
index 3dc51af9..00000000
--- a/hosting/test/operations.test.mjs
+++ /dev/null
@@ -1,236 +0,0 @@
-import assert from 'node:assert/strict';
-import { before, after, test } from 'node:test';
-import { build } from 'esbuild';
-import { mkdir } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-import { migrateAccounts } from './database.mjs';
-import { rateLimitBindings } from './rate-limit-bindings.mjs';
-
-let recordResponse, recordHealth, readOperationalHealth, runtime, database;
-before(async () => {
- const output = new URL('../../.cache/operations-tests/operations.mjs', import.meta.url);
- await mkdir(fileURLToPath(new URL('.', output)), { recursive: true });
- await build({
- entryPoints: [fileURLToPath(new URL('../src/operations.ts', import.meta.url))],
- bundle: true,
- format: 'esm',
- platform: 'node',
- outfile: fileURLToPath(output),
- });
- ({ recordResponse, recordHealth, readOperationalHealth } = await import(output));
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./operations-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['global_fetch_strictly_public'],
- bindings: { PUBLIC_ORIGIN: 'https://kiln.example.com' },
- d1Databases: ['ACCOUNTS'],
- kvNamespaces: ['OAUTH_KV'],
- ratelimits: rateLimitBindings,
- outboundService: () => {
- throw new Error('External I/O forbidden');
- },
- }),
- );
- database = await runtime.getD1Database('ACCOUNTS');
- await migrateAccounts(database);
-});
-after(async () => runtime?.dispose());
-const send = (path, options) => runtime.dispatchFetch(`https://kiln.example.com${path}`, options);
-function fixture() {
- const points = [];
- return { points, env: { OPERATIONS: { writeDataPoint: (point) => points.push(point) } } };
-}
-const healthy = {
- deletion: { pending: 2, oldestPendingMs: 1000, overdue: 0 },
- compute: { paused: false, activeRequests: 1, pendingCleanup: 0, maxConcurrent: 2 },
-};
-test('response observations emit only a fixed class, validated status and finite elapsed time', () => {
- const f = fixture();
- recordResponse(f.env, '/downloads/private-capability/source.kiln.js', 429, 123.7);
- assert.deepEqual(f.points, [
- { indexes: ['http'], blobs: ['kiln.ops.v1', 'http', 'download', '429'], doubles: [1, 124] },
- ]);
- for (const [path, status, duration] of [
- ['/private-identity', 200, 4],
- ['/oauth/google/callback', 303, 5],
- ])
- recordResponse(f.env, path, status, duration);
- assert(!JSON.stringify(f.points).includes('private'));
- assert.equal(f.points[1].blobs[2], 'other');
- assert.equal(f.points[2].blobs[2], 'callback');
- for (const status of [NaN, Infinity, 200.5, 99, 600]) recordResponse(f.env, '/', status, 1);
- for (const duration of [NaN, Infinity, -1]) recordResponse(f.env, '/', 200, duration);
- assert.equal(f.points.length, 3);
-});
-test('health observations contain aggregate values only and unknown is never healthy zero', () => {
- const f = fixture();
- recordHealth(
- f.env,
- { ...healthy, account: 'private-identity', exception: 'private-secret' },
- true,
- );
- assert.deepEqual(f.points, [
- {
- indexes: ['health:deletion'],
- blobs: ['kiln.ops.v1', 'health', 'deletion', 'ok'],
- doubles: [1, 2, 1000, 0, 1],
- },
- {
- indexes: ['health:compute'],
- blobs: ['kiln.ops.v1', 'health', 'compute', 'ok'],
- doubles: [1, 0, 1, 0, 2],
- },
- ]);
- recordHealth(f.env, { deletion: null, compute: null }, false);
- assert.deepEqual(f.points[2], {
- indexes: ['health:deletion'],
- blobs: ['kiln.ops.v1', 'health', 'deletion', 'unavailable'],
- doubles: [1, -1, -1, -1, 0],
- });
- assert.deepEqual(f.points[3], {
- indexes: ['health:compute'],
- blobs: ['kiln.ops.v1', 'health', 'compute', 'unavailable'],
- doubles: [1, -1, -1, -1, -1],
- });
- assert(!JSON.stringify(f.points).includes('private'));
-});
-test('missing or failing telemetry never throws or serializes provider errors', () => {
- for (const env of [
- {},
- {
- OPERATIONS: {
- writeDataPoint() {
- throw new Error('private-secret');
- },
- },
- },
- ]) {
- assert.doesNotThrow(() => recordResponse(env, '/mcp', 200, 12));
- assert.doesNotThrow(() => recordHealth(env, healthy, true));
- }
-});
-test('a failed compute check does not discard deletion health and vice versa', async () => {
- const database = (value) => ({
- withSession(mode) {
- assert.equal(mode, 'first-primary');
- return {
- prepare() {
- return {
- bind(now, overdueBefore) {
- assert.equal(now, 1000000);
- assert.equal(overdueBefore, 100000);
- return { first: async () => value };
- },
- };
- },
- };
- },
- });
- const env = {
- ACCOUNTS: database(healthy.deletion),
- NATIVE_COMPUTE: {
- health: async () => {
- throw new Error('private-secret');
- },
- },
- };
- assert.deepEqual(await readOperationalHealth(env, 1000000), {
- deletion: healthy.deletion,
- compute: null,
- });
- env.ACCOUNTS = {
- withSession() {
- throw new Error('private-secret');
- },
- };
- env.NATIVE_COMPUTE.health = async () => healthy.compute;
- assert.deepEqual(await readOperationalHealth(env, 1000000), {
- deletion: null,
- compute: healthy.compute,
- });
- env.NATIVE_COMPUTE.health = async () => ({ ...healthy.compute, activeRequests: 'private' });
- assert.deepEqual(await readOperationalHealth(env, 1000000), { deletion: null, compute: null });
-});
-test('health collection has a bounded deadline and reports stalled reads as unavailable', async () => {
- const env = {
- ACCOUNTS: {
- withSession() {
- throw new Error('offline');
- },
- },
- NATIVE_COMPUTE: { health: () => new Promise(() => {}) },
- };
- assert.deepEqual(await readOperationalHealth(env), { deletion: null, compute: null });
-});
-
-test('primary-D1 deletion health counts pending jobs and age without exposing rows or completed receipts', async () => {
- const empty = await (await send('/fixture/health')).json();
- assert.deepEqual(empty.deletion, { pending: 0, oldestPendingMs: 0, overdue: 0 });
- for (const [id, phase, created] of [
- ['private-old', 'storage', 10000],
- ['private-new', 'grants', 999000],
- ['private-completed', 'complete', 1],
- ])
- await database
- .prepare(
- 'INSERT INTO kiln_deletions (id,receipt_hash,phase,created_at,updated_at,retry_at) VALUES (?,?,?,?,?,?)',
- )
- .bind(id, id, phase, created, created, created)
- .run();
- const response = await send('/fixture/health');
- const text = await response.text();
- assert(!text.includes('private'));
- assert.deepEqual(JSON.parse(text).deletion, { pending: 2, oldestPendingMs: 990000, overdue: 1 });
- await database.exec('DELETE FROM kiln_deletions');
-});
-
-test('actual gateway emits one sanitized response point and keeps telemetry errors out of responses', async () => {
- for (const broken of [false, true]) {
- const response = await send('/unknown-private-name?code=private-code', {
- headers: {
- authorization: 'Bearer private-token',
- cookie: 'private-cookie',
- ...(broken ? { 'x-fixture-metrics-failure': '1' } : {}),
- },
- });
- assert.equal(response.status, 404);
- assert.equal(await response.text(), 'Not found');
- const points = await (await send('/fixture/points')).json();
- assert.equal(points.length, broken ? 0 : 1);
- if (!broken) {
- assert.deepEqual(points[0].blobs, ['kiln.ops.v1', 'http', 'other', '404']);
- assert.equal(points[0].doubles[0], 1);
- assert(Number.isSafeInteger(points[0].doubles[1]));
- }
- assert(!JSON.stringify(points).includes('private'));
- }
-});
-
-test('actual scheduled recovery emits both health components and reports a primary outage as unavailable', async () => {
- assert.equal((await send('/fixture/scheduled')).status, 200);
- let points = await (await send('/fixture/points')).json();
- assert.equal(points.length, 2);
- assert.deepEqual(points[0].doubles, [1, 0, 0, 0, 1]);
- assert.deepEqual(points[1].doubles, [1, 0, 0, 0, 2]);
- assert.equal(
- (await send('/fixture/scheduled', { headers: { 'x-fixture-database-failure': '1' } })).status,
- 503,
- );
- points = await (await send('/fixture/points')).json();
- assert.equal(points[0].blobs[3], 'unavailable');
- assert.deepEqual(points[0].doubles, [1, -1, -1, -1, 0]);
- assert.equal(points[1].blobs[3], 'ok');
- assert(!JSON.stringify(points).includes('private'));
-});
diff --git a/hosting/test/probe-observation.test.mjs b/hosting/test/probe-observation.test.mjs
deleted file mode 100644
index 069300c3..00000000
--- a/hosting/test/probe-observation.test.mjs
+++ /dev/null
@@ -1,58 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-
-let observeContainer;
-before(async () => {
- const output = new URL('../../.cache/hosted-probe-test/observe.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../probe/observe-container.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ observeContainer } = await import(output));
-});
-
-test('probe observation retains only the first failed native operation, never exception text', async () => {
- const actual = {
- start() {
- assert.equal(this, actual);
- },
- async exec() {
- throw new Error('private runtime diagnostic');
- },
- async destroy() {
- throw new Error('later cleanup diagnostic');
- },
- };
- const observed = observeContainer(actual);
- observed.container.start();
- await assert.rejects(observed.container.exec([]));
- await assert.rejects(observed.container.destroy());
- assert.equal(observed.failure(), 'exec');
- assert.equal(JSON.stringify(observed.failure()).includes('private'), false);
-});
-
-test('probe fixture substitution retains native exec options and observes synchronous failure', () => {
- const options = { user: '1000:1000', stdin: 'pipe' };
- const observed = observeContainer(
- {
- exec(command, received) {
- assert.deepEqual(command, [
- '/usr/local/bin/node',
- '--input-type=module',
- '-e',
- 'fixed fixture',
- ]);
- assert.equal(received, options);
- throw new Error('native synchronous failure');
- },
- },
- 'fixed fixture',
- );
- assert.throws(() => observed.container.exec(['original'], options));
- assert.equal(observed.failure(), 'exec');
-});
diff --git a/hosting/test/programs.test.mjs b/hosting/test/programs.test.mjs
deleted file mode 100644
index fd4efa01..00000000
--- a/hosting/test/programs.test.mjs
+++ /dev/null
@@ -1,187 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-let runtime;
-let namespace;
-const canonical = (source) => `sha256:${createHash('sha256').update(source).digest('hex')}`;
-before(async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('../src/tenant-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- name: 'programs',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- r2Buckets: ['ARTIFACTS'],
- durableObjects: { TENANTS: { className: 'KilnTenant', useSQLite: true } },
- bindings: {
- STORAGE_MAX_BYTES: String(4 * 1024 * 1024),
- STORAGE_MAX_OBJECTS: '32',
- STORAGE_MAX_GROUPS: '8',
- },
- outboundService: async () => {
- throw new Error('Program storage must not use outbound fetch');
- },
- }),
- unsafeInspectDurableObjects: true,
- });
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
-});
-after(async () => runtime?.dispose());
-const send = (owner, path, init) =>
- namespace.get(namespace.idFromName(owner)).fetch(`https://tenant.internal${path}`, init);
-const put = (owner, body) =>
- send(owner, '/internal/programs', {
- method: 'POST',
- body,
- headers: { 'content-type': 'application/javascript' },
- });
-const get = (owner, ref) => send(owner, `/internal/programs/${encodeURIComponent(ref)}`);
-const usage = async (owner) => (await send(owner, '/internal/usage')).json();
-async function db(owner) {
- return runtime.unsafeGetDurableObjectStorage('programs', 'KilnTenant', {
- id: namespace.idFromName(owner).toString(),
- });
-}
-
-test('source retains the engine hash and exact UTF-8 bytes, including a leading BOM', async () => {
- const source = '\ufeffconst name = "Café 🏠"; return name;';
- const response = await put('unicode', source);
- assert.equal(response.status, 201);
- const record = await response.json();
- assert.equal(record.programRef, canonical(source));
- assert.equal(record.shortRef, `p_${record.programRef.slice(7)}`);
- for (const ref of [record.programRef, record.shortRef]) {
- const result = await get('unicode', ref);
- assert.equal(result.status, 200);
- assert.deepEqual(Buffer.from(await result.arrayBuffer()), Buffer.from(source));
- }
- assert.equal((await get('another-tenant', record.programRef)).status, 404);
- const stats = await (await send('unicode', '/internal/programs')).json();
- assert.equal(stats.entries, 1);
- assert.equal(stats.bytes, Buffer.byteLength(source));
- assert.equal(stats.maxSourceBytes, 1024 * 1024);
- assert.match(stats.retention, /seven days/);
-});
-
-test('same-source concurrent puts and reconnects share one artifact and preserve its expiry', async () => {
- const source = 'return new THREE.Group();';
- const results = await Promise.all(Array.from({ length: 8 }, () => put('dedupe', source)));
- for (const response of results) assert.equal(response.status, 201);
- const records = await Promise.all(results.map((response) => response.json()));
- assert.equal(new Set(records.map((record) => record.artifactId)).size, 1);
- assert.equal((await usage('dedupe')).objects, 1);
- const database = await db('dedupe');
- const expiry = (await database.exec('SELECT expires_at FROM artifacts'))[0].expires_at;
- await runtime.unsafeEvictDurableObject('programs', 'KilnTenant', {
- id: namespace.idFromName('dedupe').toString(),
- });
- const again = await (await put('dedupe', source)).json();
- assert.equal(again.artifactId, records[0].artifactId);
- const freshDb = await db('dedupe');
- assert.equal((await freshDb.exec('SELECT expires_at FROM artifacts'))[0].expires_at, expiry);
- assert.equal((await usage('dedupe')).objects, 1);
- assert.equal(await (await get('dedupe', again.shortRef)).text(), source);
-});
-
-test('unknown and unissued short handles deny access with source-recovery guidance', async () => {
- const record = await (await put('references', 'return "source";')).json();
- const guessed = record.shortRef.slice(0, 14);
- const missing = await get('references', guessed);
- assert.equal(missing.status, 404);
- assert.match(await missing.text(), /Send the source again with kiln_validate or kiln_render/);
- assert.equal((await get('references', `sha256:${'0'.repeat(64)}`)).status, 404);
- assert.equal((await get('references', 'sha256:bad')).status, 400);
-});
-
-test('unsaved expiry denies source before cleanup; saved source remains resolvable', async () => {
- const unsaved = await (await put('retention', 'return "unsaved";')).json();
- const saved = await (await put('retention', 'return "saved";')).json();
- const group = await send('retention', '/internal/groups', {
- method: 'POST',
- body: JSON.stringify({
- key: 'asset/revision',
- files: { 'source.kiln.js': saved.artifactId },
- metadata: {},
- }),
- });
- assert.equal(group.status, 201);
- const groupId = (await group.json()).id;
- await (await db('retention')).exec('UPDATE artifacts SET expires_at = 1');
- assert.equal((await get('retention', unsaved.programRef)).status, 404);
- assert.equal((await get('retention', saved.shortRef)).status, 200);
- await send('retention', '/internal/maintenance', { method: 'POST' });
- const stats = await (await send('retention', '/internal/programs')).json();
- assert.equal(stats.entries, 1);
- await send('retention', `/internal/groups/${groupId}`, { method: 'DELETE' });
- assert.equal((await get('retention', saved.programRef)).status, 404);
- assert.equal((await usage('retention')).objects, 0);
-});
-
-test('invalid UTF-8 and oversized source consume no quota; the exact source limit works', async () => {
- assert.equal((await put('source-limits', Buffer.from([0xff]))).status, 400);
- assert.equal((await put('source-limits', 'a'.repeat(1024 * 1024 + 1))).status, 413);
- assert.equal((await usage('source-limits')).objects, 0);
- const empty = await (await put('source-limits', '')).json();
- assert.equal(empty.programRef, canonical(''));
- const response = await put('source-limits', 'a'.repeat(1024 * 1024));
- assert.equal(response.status, 201);
- const record = await response.json();
- assert.equal(
- (await (await get('source-limits', record.shortRef)).arrayBuffer()).byteLength,
- 1024 * 1024,
- );
-});
-
-test('corrupt stored source cannot be accepted by get or an idempotent put', async () => {
- const source = 'return "original";';
- const record = await (await put('source-integrity', source)).json();
- const bucket = await runtime.getR2Bucket('ARTIFACTS');
- const key = `tenants/${namespace.idFromName('source-integrity')}/artifacts/${record.artifactId}`;
- await bucket.put(key, 'different source');
- assert.equal((await get('source-integrity', record.programRef)).status, 502);
- assert.equal((await put('source-integrity', source)).status, 502);
- assert.equal((await usage('source-integrity')).objects, 1);
-});
-
-test('source shares artifact quota, never evicts existing work and can retry after cleanup', async () => {
- const bytes = Buffer.alloc(4 * 1024 * 1024, 1);
- const upload = await send('shared-quota', '/internal/artifacts', {
- method: 'POST',
- body: bytes,
- headers: {
- 'content-type': 'application/octet-stream',
- 'content-length': String(bytes.length),
- 'x-artifact-name': 'asset.glb',
- 'x-artifact-sha256': createHash('sha256').update(bytes).digest('hex'),
- },
- });
- assert.equal(upload.status, 201);
- const blob = await upload.json();
- const source = 'return "quota retry";';
- const failures = await Promise.all([put('shared-quota', source), put('shared-quota', source)]);
- for (const response of failures) assert.equal(response.status, 507);
- assert.equal(
- (await send('shared-quota', `/mcp/artifacts/${blob.id}`, { method: 'HEAD' })).status,
- 200,
- );
- assert.equal((await usage('shared-quota')).objects, 1);
- await (await db('shared-quota')).exec('UPDATE artifacts SET expires_at = 1');
- await send('shared-quota', '/internal/maintenance', { method: 'POST' });
- const retry = await put('shared-quota', source);
- assert.equal(retry.status, 201);
- const record = await retry.json();
- assert.equal(await (await get('shared-quota', record.programRef)).text(), source);
- assert.equal((await usage('shared-quota')).bytes, Buffer.byteLength(source));
-});
diff --git a/hosting/test/provider-probe-worker.ts b/hosting/test/provider-probe-worker.ts
deleted file mode 100644
index 52e70d31..00000000
--- a/hosting/test/provider-probe-worker.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import worker, { KilnProbeRun, KilnProbeJob } from '../probe/worker';
-export { KilnProbeRun, KilnProbeJob };
-export default {
- async fetch(request: Request, _env: unknown, ctx: ExecutionContext) {
- if (new URL(request.url).pathname === '/test-trigger') {
- const bindings = ctx.exports as unknown as {
- KilnProbeRun: DurableObjectNamespace<KilnProbeRun>;
- };
- const runs = bindings.KilnProbeRun;
- return Response.json(await runs.getByName('test').run());
- }
- return worker.fetch();
- },
-};
diff --git a/hosting/test/provider-probe.test.mjs b/hosting/test/provider-probe.test.mjs
deleted file mode 100644
index 79e0128f..00000000
--- a/hosting/test/provider-probe.test.mjs
+++ /dev/null
@@ -1,204 +0,0 @@
-import assert from 'node:assert/strict';
-import { readFile } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-let runProbeOnce;
-let probeCases;
-test('the manifest qualification has no public route or automatic trigger and pins the proven runtime image', async () => {
- const config = JSON.parse(
- await readFile(new URL('../probe/qualification.wrangler.jsonc', import.meta.url), 'utf8'),
- );
- assert.equal(config.workers_dev, false);
- assert.equal(config.preview_urls, false);
- assert.deepEqual(config.routes, []);
- assert.equal(config.triggers, undefined);
- assert.equal(config.main, './worker.ts');
- assert.equal(config.containers.length, 1);
- assert.equal(config.containers[0].scheduling_policy, 'durable_object');
- assert.equal(config.containers[0].class_name, 'KilnProbeJob');
- assert.equal(config.containers[0].observability.logs.enabled, false);
- assert.equal(
- config.containers[0].images.kiln.image,
- 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8',
- );
- assert.deepEqual(config.exports, {
- KilnProbeControl: { type: 'worker' },
- KilnProbeRun: { type: 'durable-object', storage: 'sqlite' },
- KilnProbeJob: { type: 'durable-object', storage: 'sqlite' },
- });
-});
-before(async () => {
- const output = new URL('../../.cache/hosted-probe-test/run-once.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../probe/run-once.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ runProbeOnce, probeCases } = await import(output));
-});
-
-function storage() {
- const records = new Map();
- let tail = Promise.resolve();
- const store = {
- async get(key) {
- return structuredClone(records.get(key));
- },
- async put(key, value) {
- records.set(key, structuredClone(value));
- },
- transaction(callback) {
- const result = tail.then(() => callback(store));
- tail = result.catch(() => {});
- return result;
- },
- };
- return store;
-}
-
-test('private probe claims its fixed budget once across concurrent and later triggers', async () => {
- const store = storage();
- const called = [];
- const execute = async (name) => {
- called.push(name);
- return { name, passed: true };
- };
- await Promise.all([runProbeOnce(store, execute), runProbeOnce(store, execute)]);
- const final = await runProbeOnce(store, execute);
- // The fixed candidate has four cases. Any new deployment requires its own
- // approval; this code cannot reset the exhausted earlier trial allowance.
- assert.deepEqual(probeCases, ['engine-a', 'network', 'write-marker', 'read-marker']);
- assert.deepEqual(called, probeCases);
- assert.equal(final.state, 'finished');
- assert.equal(final.results.length, 4);
-});
-
-test('private probe stops after a failed case and does not spend again on retry', async () => {
- const store = storage();
- let count = 0;
- const execute = async (name) => {
- count++;
- return { name, passed: false, reason: 'CHECK_FAILED' };
- };
- assert.equal((await runProbeOnce(store, execute)).results[0].passed, false);
- await runProbeOnce(store, execute);
- assert.equal(count, 1);
-});
-
-test('an interrupted claim is not silently replayed and exceptions do not disclose details', async () => {
- const store = storage();
- await store.put('run', { state: 'running', results: [] });
- await runProbeOnce(store, async () => {
- throw new Error('must never run');
- });
- const failure = await runProbeOnce(storage(), async () => {
- throw new Error('private diagnostic');
- });
- assert.deepEqual(failure.results, [{ name: 'engine-a', passed: false, reason: 'PROBE_FAILED' }]);
-});
-
-test('the private Worker exposes no HTTP execution and its loopback namespaces fail closed without a container', async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./provider-probe-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- const runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['enable_ctx_exports'],
- durableObjects: {
- RUN: { className: 'KilnProbeRun', useSQLite: true },
- JOB: { className: 'KilnProbeJob', useSQLite: true },
- },
- outboundService: async () => {
- throw new Error('No external requests');
- },
- }),
- );
- try {
- const denied = await runtime.dispatchFetch('http://localhost/execute', {
- method: 'POST',
- body: '{"code":"arbitrary"}',
- });
- assert.equal(denied.status, 404);
- const first = await (await runtime.dispatchFetch('http://localhost/test-trigger')).json();
- assert.equal(first.state, 'finished');
- assert.deepEqual(first.results, [
- { name: 'engine-a', passed: false, reason: 'CONTAINER_UNAVAILABLE' },
- ]);
- const second = await (await runtime.dispatchFetch('http://localhost/test-trigger')).json();
- assert.deepEqual(second, first);
- } finally {
- await runtime.dispose();
- }
-});
-
-test('private service RPC can trigger only the fixed retained probe and exposes no HTTP execution', async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('../probe/worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- const runtime = new Miniflare(
- convertV4MiniflareOptions({
- workers: [
- {
- name: 'private-probe',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['enable_ctx_exports'],
- durableObjects: {
- RUN: { className: 'KilnProbeRun', useSQLite: true },
- JOB: { className: 'KilnProbeJob', useSQLite: true },
- },
- },
- {
- name: 'operator',
- modules: true,
- compatibilityDate: '2026-10-06',
- serviceBindings: {
- PROBE: { name: 'private-probe', entrypoint: 'KilnProbeControl' },
- },
- script: `export default {
- async fetch(request, env) {
- if (new URL(request.url).pathname === '/denied') return env.PROBE.fetch(request);
- return Response.json(await env.PROBE.runFixed());
- }
- }`,
- },
- ],
- }),
- );
- try {
- const operator = await runtime.getWorker('operator');
- const denied = await operator.fetch('http://localhost/denied', {
- method: 'POST',
- body: '{}',
- });
- assert.equal(denied.status, 404);
- const first = await (await operator.fetch('http://localhost/run')).json();
- assert.deepEqual(first, {
- state: 'finished',
- results: [{ name: 'engine-a', passed: false, reason: 'CONTAINER_UNAVAILABLE' }],
- });
- const second = await (await operator.fetch('http://localhost/run')).json();
- assert.deepEqual(second, first);
- } finally {
- await runtime.dispose();
- }
-});
diff --git a/hosting/test/public-pages.test.mjs b/hosting/test/public-pages.test.mjs
deleted file mode 100644
index 8e2f41ff..00000000
--- a/hosting/test/public-pages.test.mjs
+++ /dev/null
@@ -1,100 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-import { rateLimitBindings } from './rate-limit-bindings.mjs';
-
-const origin = 'https://kiln.example.com';
-let runtime;
-let outgoing = 0;
-before(async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('../src/worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- ratelimits: rateLimitBindings,
- bindings: { PUBLIC_ORIGIN: origin },
- // Deliberately no accounts, OAuth KV, provider credentials, storage or compute.
- outboundService: async () => {
- outgoing++;
- throw new Error('Public information must not contact another service');
- },
- }),
- );
-});
-after(async () => runtime?.dispose());
-
-test('home and policy pages are available before sign-in without credentials or storage', async () => {
- for (const path of ['/', '/privacy', '/support', '/terms']) {
- const response = await runtime.dispatchFetch(origin + path);
- assert.equal(response.status, 200, path);
- assert.match(response.headers.get('content-type'), /text\/html/);
- assert.equal(response.headers.get('set-cookie'), null);
- assert.equal(response.headers.get('cache-control'), 'no-store');
- assert.equal(response.headers.get('referrer-policy'), 'no-referrer');
- const html = await response.text();
- const nonce = html.match(/<style nonce="([a-f0-9]+)">/)[1];
- const csp = response.headers.get('content-security-policy');
- assert.ok(csp.includes(`style-src 'nonce-${nonce}'`));
- assert.match(csp, /default-src 'none'/);
- assert.match(csp, /frame-ancestors 'none'/);
- assert.doesNotMatch(html, /<script|<iframe|<link[^>]+href="https?:/i);
- for (const link of ['/privacy', '/support', '/terms', '/account'])
- assert.ok(html.includes(`href="${link}"`));
- }
- assert.equal(outgoing, 0);
-});
-
-test('public content explains hosted data access, retention, notices and private support', async () => {
- const home = await (await runtime.dispatchFetch(`${origin}/`)).text();
- assert.match(home, /JavaScript/);
- assert.match(home, /free within/i);
- assert.ok(home.includes(`${origin}/mcp`));
- const privacy = await (await runtime.dispatchFetch(`${origin}/privacy`)).text();
- for (const fact of [
- 'Google',
- 'GitHub',
- 'Cloudflare',
- 'seven days',
- '30 days',
- 'three months',
- 'in-app',
- 'retirement records',
- ])
- assert.ok(privacy.includes(fact), fact);
- assert.match(privacy, /support@instruktlabs\.com/);
- const support = await (await runtime.dispatchFetch(`${origin}/support`)).text();
- assert.match(support, /mailto:support@instruktlabs\.com/);
- assert.match(support, /public issues/i);
- assert.match(support, /passwords|tokens/);
-});
-
-test('information pages allow HEAD but reject mutation methods and query reflection', async () => {
- for (const path of ['/', '/privacy', '/support', '/terms']) {
- const head = await runtime.dispatchFetch(origin + path, { method: 'HEAD' });
- assert.equal(head.status, 200);
- assert.equal(await head.text(), '');
- const post = await runtime.dispatchFetch(origin + path, {
- method: 'POST',
- body: 'private-value',
- });
- assert.equal(post.status, 405);
- assert.equal(post.headers.get('allow'), 'GET, HEAD');
- const query = await runtime.dispatchFetch(`${origin}${path}?private-value=%3Cscript%3E`);
- assert.equal(query.status, 400);
- assert.doesNotMatch(await query.text(), /private-value|<script>/);
- }
- assert.equal((await runtime.dispatchFetch('https://foreign.example/privacy')).status, 421);
- assert.equal(outgoing, 0);
-});
diff --git a/hosting/test/public-tools.test.mjs b/hosting/test/public-tools.test.mjs
deleted file mode 100644
index f8ae378e..00000000
--- a/hosting/test/public-tools.test.mjs
+++ /dev/null
@@ -1,83 +0,0 @@
-import assert from 'node:assert/strict';
-import { readFile } from 'node:fs/promises';
-import { test } from 'node:test';
-import { createPublicTools, HOSTED_TOOL_SURFACE, hostedInstructions } from '../src/public-tools.ts';
-
-const { tools: engine } = JSON.parse(
- await readFile(new URL('../src/generated/edge-manifest.json', import.meta.url), 'utf8'),
-);
-
-test('every reviewed engine operation has a separate hosted name and registry-derived fields', () => {
- const before = structuredClone(engine);
- const surface = createPublicTools(engine);
- assert.equal(HOSTED_TOOL_SURFACE, 'kiln.hosted-tools.v1');
- assert.equal(surface.tools.length, 26);
- for (const tool of engine) {
- const actions = tool.inputSchema.properties.action?.enum;
- const variants = actions
- ? actions.map((action) => [`${tool.name}_${action.replaceAll('-', '_')}`, { action }])
- : tool.name === 'kiln_discover'
- ? [
- ['kiln_discover', {}],
- ['kiln_capabilities', { capabilities: true }],
- ]
- : [[tool.name, {}]];
- for (const [name, fixed] of variants) {
- const publicTool = surface.tools.find((tool) => tool.name === name);
- assert.ok(publicTool, name);
- assert.deepEqual(surface.resolve(name, {}), { name: tool.name, arguments: fixed });
- assert.equal(publicTool.inputSchema.additionalProperties, false);
- assert.equal(publicTool.inputSchema.properties.action, undefined);
- assert.equal(publicTool.inputSchema.properties.capabilities, undefined);
- for (const [field, schema] of Object.entries(publicTool.inputSchema.properties))
- assert.deepEqual(schema, tool.inputSchema.properties[field], `${name}.${field}`);
- for (const key of ['readOnlyHint', 'destructiveHint', 'openWorldHint'])
- assert.equal(typeof publicTool.annotations[key], 'boolean');
- assert.equal(publicTool.annotations.readOnlyHint, name === 'kiln_discover');
- assert.equal(publicTool.annotations.destructiveHint, false);
- assert.equal(publicTool.annotations.openWorldHint, false);
- }
- if (actions) assert.equal(surface.resolve(tool.name, { action: actions[0] }), undefined);
- }
- assert.deepEqual(engine, before, 'the installed engine manifest must not be mutated');
- assert.doesNotMatch(hostedInstructions, /render-service\/|dist\/|read the matching SKILL/);
-});
-
-test('registry drift cannot silently expose an unreviewed operation or drop a mapped input', () => {
- const more = structuredClone(engine);
- more
- .find((tool) => tool.name === 'kiln_material')
- .inputSchema.properties.action.enum.push('delete');
- assert.throws(() => createPublicTools(more), /Unreviewed engine actions/);
- assert.throws(
- () => createPublicTools([...engine, { name: 'new_operation', inputSchema: {} }]),
- /Unreviewed engine tool/,
- );
- assert.throws(() => createPublicTools(engine.slice(1)), /Missing engine tools/);
- const missingField = structuredClone(engine);
- delete missingField.find((tool) => tool.name === 'kiln_material').inputSchema.properties.draft;
- assert.throws(() => createPublicTools(missingField), /Missing engine field/);
- assert.throws(() => createPublicTools([...engine, engine[0]]), /Duplicate engine tool/);
-});
-
-test('action selection and argument widening cannot turn reads into another engine operation', () => {
- const surface = createPublicTools(engine);
- for (const name of ['kiln_material_get', 'kiln_assets_get', 'kiln_renderer_status']) {
- for (const args of [
- { action: 'import' },
- { payload: {} },
- JSON.parse('{"__proto__":{"action":"import"}}'),
- ])
- assert.equal(surface.resolve(name, args), undefined);
- }
- for (const name of [
- 'constructor',
- '__proto__',
- 'kiln_material_delete',
- 'kiln_project',
- 'kiln_review',
- ])
- assert.equal(surface.resolve(name, {}), undefined);
- assert.equal(surface.resolve('kiln_discover', { capabilities: true }), undefined);
- assert.equal(surface.resolve('kiln_capabilities', { ids: ['box'] }), undefined);
-});
diff --git a/hosting/test/rate-limit-bindings.mjs b/hosting/test/rate-limit-bindings.mjs
deleted file mode 100644
index dc98e7b5..00000000
--- a/hosting/test/rate-limit-bindings.mjs
+++ /dev/null
@@ -1,6 +0,0 @@
-// Real local bindings. Ordinary auth/storage fixtures have generous limits so
-// unrelated tests stay independent; request-limits.test.mjs tests exhaustion.
-export const rateLimitBindings = {
- EDGE_REQUEST_LIMIT: { namespace_id: '1001', simple: { limit: 1000000, period: 60 } },
- ACCOUNT_REQUEST_LIMIT: { namespace_id: '1002', simple: { limit: 1000000, period: 60 } },
-};
diff --git a/hosting/test/request-job.test.mjs b/hosting/test/request-job.test.mjs
deleted file mode 100644
index be43b274..00000000
--- a/hosting/test/request-job.test.mjs
+++ /dev/null
@@ -1,678 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-
-let NativeRequestJob;
-before(async () => {
- const output = new URL('../../.cache/hosted-request-test/job.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../src/request-job.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ NativeRequestJob } = await import(output));
-});
-
-const tenant = 'a'.repeat(43);
-const image = `registry.cloudflare.com/fixture/coordinator@sha256:${'b'.repeat(64)}`;
-const request = (extra = {}) =>
- new Request('https://tenant.internal/mcp', {
- method: 'POST',
- body: '{}',
- headers: { 'content-type': 'application/json' },
- ...extra,
- });
-const evaluation = () =>
- new Request('http://kiln-evaluator.internal/evaluate', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'content-length': '2',
- 'x-kiln-deadline-ms': '60000',
- 'x-kiln-max-response-bytes': '1024',
- },
- body: '{}',
- });
-const deferred = () => {
- let resolve;
- const promise = new Promise((done) => {
- resolve = done;
- });
- return { promise, resolve };
-};
-const rendering = () =>
- new Request('http://kiln-renderer.internal/render', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'content-length': '2',
- 'x-kiln-deadline-ms': '30000',
- 'x-kiln-max-response-bytes': '20971520',
- },
- body: '{}',
- });
-const turn = () => new Promise((resolve) => setImmediate(resolve));
-
-function fixture(options = {}) {
- const values = new Map(),
- events = [],
- children = new Map(),
- storageCalls = [];
- let alarmAt,
- transactionTail = Promise.resolve(),
- failChildren = !!options.failChildren;
- const exited = deferred();
- const storage = {
- async get(key) {
- return structuredClone(values.get(key));
- },
- async put(key, value) {
- values.set(key, structuredClone(value));
- },
- async setAlarm(value) {
- alarmAt = Number(value);
- events.push('alarm');
- },
- async deleteAlarm() {
- alarmAt = undefined;
- },
- transaction(callback) {
- const pending = transactionTail.then(() => callback(storage));
- transactionTail = pending.catch(() => {});
- return pending;
- },
- };
- let job;
- const container = {
- images: { coordinator: options.image ?? image },
- running: false,
- async interceptOutboundHttp(host, binding) {
- events.push(`intercept:${host}`);
- assert(binding);
- await options.intercept?.();
- },
- start(settings) {
- events.push('start');
- this.settings = settings;
- this.running = true;
- },
- monitor() {
- return exited.promise;
- },
- async setInactivityTimeout() {},
- async inspect() {
- return this.running ? { image: options.observedImage ?? image } : null;
- },
- async destroy() {
- events.push('destroy');
- await options.destroy?.();
- this.running = false;
- exited.resolve();
- },
- getTcpPort(port) {
- assert.equal(port, 3000);
- return {
- fetch: async (input) => {
- const req = input instanceof Request ? input : new Request(input);
- if (req.url.endsWith('/_ready')) return new Response(null, { status: 204 });
- events.push('mcp');
- return options.native ? options.native(req, job) : Response.json({ ok: true });
- },
- };
- },
- };
- const ports = {
- publicOrigin: 'https://kiln.example.com',
- storageInterceptor: {},
- evaluationInterceptor: {},
- renderInterceptor: {},
- async storage(owner, req) {
- storageCalls.push({ owner, url: req.url, headers: Object.fromEntries(req.headers) });
- return new Response('source bytes');
- },
- async evaluate(id, req) {
- assert(
- values
- .get('request')
- .children.some((child) => child.id === id && child.kind === 'evaluation'),
- 'child must be durable before dispatch',
- );
- assert.equal(children.has(id), false);
- children.set(id, true);
- events.push(`child:${id}`);
- return options.evaluate ? options.evaluate(id, req) : Response.json({ fixture: true });
- },
- async cancelEvaluation(id) {
- events.push(`cancel:${id}`);
- if (failChildren) throw new Error('PRIVATE_CHILD_FAILURE');
- children.set(id, false);
- },
- async render(id, req) {
- assert(
- values.get('request').children.some((child) => child.id === id && child.kind === 'render'),
- );
- assert.equal(children.has(id), false);
- children.set(id, true);
- events.push(`render:${id}`);
- return options.render ? options.render(id, req) : Response.json({ rendered: true });
- },
- async cancelRender(id) {
- events.push(`cancel-render:${id}`);
- if (failChildren) throw new Error('PRIVATE_RENDER_FAILURE');
- children.set(id, false);
- },
- };
- const context = { storage, container };
- job = new NativeRequestJob(context, ports);
- return {
- job,
- context,
- ports,
- values,
- events,
- children,
- storageCalls,
- get alarmAt() {
- return alarmAt;
- },
- repair() {
- failChildren = false;
- },
- run(req = request()) {
- return job.run(tenant, req, Date.now() + 2000);
- },
- };
-}
-
-test('render children are durable, separately routed, and share the parent execution limit', async () => {
- const f = fixture({
- native: async (_, job) => {
- for (let i = 0; i < 8; i++) {
- if (i % 2) await job.evaluateRequest(evaluation());
- else await job.renderRequest(rendering());
- }
- await assert.rejects(job.renderRequest(rendering()), (error) => error.status === 429);
- await assert.rejects(job.evaluateRequest(evaluation()), (error) => error.status === 429);
- return Response.json({ ok: true });
- },
- });
- await f.run();
- const children = f.values.get('request').children;
- assert.equal(new Set(children.map((child) => child.id)).size, 8);
- assert.equal(children.filter((child) => child.kind === 'render').length, 4);
- assert.equal([...f.children.values()].some(Boolean), false);
- for (const child of children) {
- const prefix = child.kind === 'render' ? 'cancel-render:' : 'cancel:';
- assert(f.events.includes(prefix + child.id));
- assert(!f.events.includes((child.kind === 'render' ? 'cancel:' : 'cancel-render:') + child.id));
- }
-});
-
-test('a pending render excludes evaluation until its cleanup acknowledgement', async () => {
- const entered = deferred(),
- finish = deferred(),
- renderStarted = deferred(),
- renderFinish = deferred();
- const f = fixture({
- native: async () => {
- entered.resolve();
- await finish.promise;
- return Response.json({ ok: true });
- },
- render: async (_id, req) => {
- assert(Number(req.headers.get('x-kiln-deadline-ms')) <= 2000);
- renderStarted.resolve();
- await renderFinish.promise;
- return Response.json({ ok: true });
- },
- });
- const run = f.run();
- await entered.promise;
- const rendered = f.job.renderRequest(rendering());
- await renderStarted.promise;
- await assert.rejects(f.job.evaluateRequest(evaluation()), (error) => error.status === 429);
- await assert.rejects(f.job.renderRequest(rendering()), (error) => error.status === 429);
- renderFinish.resolve();
- await rendered;
- await f.job.evaluateRequest(evaluation());
- finish.resolve();
- await run;
-});
-
-test('render cleanup failure retains parent admission state and recovery routes by persisted kind', async () => {
- const f = fixture({
- failChildren: true,
- native: async (_, job) => {
- await job.renderRequest(rendering());
- return Response.json({ ok: true });
- },
- });
- await assert.rejects(f.run(), (error) => error.code === 'CLEANUP_FAILED');
- assert.equal(f.values.get('request').state, 'closing');
- const child = f.values.get('request').children[0];
- assert.equal(child.kind, 'render');
- f.repair();
- await new NativeRequestJob(f.context, f.ports).alarm();
- assert.equal(f.values.get('request').state, 'finished');
- assert(f.events.includes(`cancel-render:${child.id}`));
- assert(!f.events.includes(`cancel:${child.id}`));
-});
-
-test('render route rejects caller-selected authority and fails after parent cancellation', async () => {
- const f = fixture({
- native: async (_, job) => {
- await assert.rejects(job.renderRequest(evaluation()), (error) => error.status === 400);
- await assert.rejects(
- job.renderRequest(new Request(rendering(), { headers: { 'x-tenant': 'other' } })),
- (error) => error.status === 400,
- );
- return Response.json({ ok: true });
- },
- });
- await f.run();
- await assert.rejects(f.job.renderRequest(rendering()));
- assert.equal(f.values.get('request').children.length, 0);
-});
-
-test('request host binds storage outside its offline VM and stops the whole job tree before returning', async () => {
- const f = fixture({
- native: async (req, job) => {
- assert.equal(req.url, 'http://kiln-native.internal/mcp');
- assert.equal(req.headers.has('authorization'), false);
- assert.equal(
- await (
- await job.storageRequest(new Request('http://kiln-storage.internal/internal/programs'))
- ).text(),
- 'source bytes',
- );
- await (await job.evaluateRequest(evaluation())).arrayBuffer();
- return Response.json({ ok: true }, { headers: { 'set-cookie': 'PRIVATE_FIXTURE=1' } });
- },
- });
- const result = await f.run();
- assert.deepEqual(await result.json(), { ok: true });
- assert.equal(result.headers.has('set-cookie'), false);
- assert.equal(f.context.container.settings.enableInternet, false);
- assert.deepEqual(f.context.container.settings.env, {
- KILN_PUBLIC_ORIGIN: 'https://kiln.example.com',
- });
- assert.equal(f.context.container.settings.image, image);
- assert.deepEqual(
- f.events.filter((v) => v.startsWith('intercept:')),
- [
- 'intercept:kiln-storage.internal',
- 'intercept:kiln-evaluator.internal',
- 'intercept:kiln-renderer.internal',
- ],
- );
- assert.ok(f.events.indexOf('alarm') < f.events.indexOf('start'));
- assert.deepEqual(f.storageCalls, [
- { owner: tenant, url: 'https://tenant.internal/internal/programs', headers: {} },
- ]);
- assert.equal(f.context.container.running, false);
- assert.equal([...f.children.values()].some(Boolean), false);
- assert.equal(f.values.get('request').state, 'finished');
- assert.equal(f.alarmAt, undefined);
-});
-
-test('storage interceptor refuses supplied identity, foreign origins and administrative routes', async () => {
- const entered = deferred(),
- finish = deferred();
- const f = fixture({
- native: async () => {
- entered.resolve();
- await finish.promise;
- return Response.json({ ok: true });
- },
- });
- const run = f.run();
- await entered.promise;
- for (const req of [
- new Request('http://kiln-storage.internal/internal/programs', {
- headers: { 'x-tenant': 'victim' },
- }),
- new Request('http://kiln-storage.internal/internal/programs', {
- headers: { authorization: 'Bearer PRIVATE' },
- }),
- new Request('http://kiln-storage.internal/internal/programs?tenant=victim'),
- new Request('http://attacker.example/internal/programs'),
- new Request('http://kiln-storage.internal/internal/maintenance', { method: 'POST' }),
- new Request('http://kiln-storage.internal/internal/account-deletion', { method: 'POST' }),
- ])
- await assert.rejects(f.job.storageRequest(req));
- assert.equal(f.storageCalls.length, 0);
- finish.resolve();
- await run;
- await assert.rejects(
- f.job.storageRequest(new Request('http://kiln-storage.internal/internal/programs')),
- );
-});
-
-test('material storage routes stay bound to the parent tenant and reject arbitrary paths or identity headers', async () => {
- const f = fixture({
- native: async (_req, job) => {
- for (const [path, method] of [
- ['/internal/materials/list', 'POST'],
- ['/internal/materials/commit', 'POST'],
- [`/internal/materials/stone/${'a'.repeat(64)}`, 'GET'],
- ]) {
- const response = await job.storageRequest(
- new Request(`http://kiln-storage.internal${path}`, {
- method,
- ...(method === 'POST'
- ? { body: '{}', headers: { 'content-type': 'application/json' } }
- : {}),
- }),
- );
- await response.text();
- }
- for (const path of [
- '/internal/materials/stone/invalid',
- '/internal/materials/list?tenant=victim',
- '/internal/materials/delete',
- ])
- await assert.rejects(
- job.storageRequest(new Request(`http://kiln-storage.internal${path}`)),
- (error) => error.status === 400,
- );
- await assert.rejects(
- job.storageRequest(
- new Request('http://kiln-storage.internal/internal/materials/list', {
- method: 'POST',
- body: '{}',
- headers: { 'x-kiln-tenant': 'victim' },
- }),
- ),
- (error) => error.status === 400,
- );
- return Response.json({ ok: true });
- },
- });
- await f.run();
- assert.equal(f.storageCalls.length, 3);
- assert(f.storageCalls.every((call) => call.owner === tenant));
-});
-
-test('native download ticket issuance stays bound to the active parent tenant without browser redemption authority', async () => {
- const f = fixture({
- native: async (_req, job) => {
- const response = await job.storageRequest(
- new Request('http://kiln-storage.internal/internal/downloads', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ collection: 'project', assetId: 'a_box', revisionId: 'r_one' }),
- }),
- );
- assert.equal(await response.text(), 'source bytes');
- await assert.rejects(
- job.storageRequest(
- new Request(
- `http://kiln-storage.internal/internal/downloads/${'a'.repeat(64)}/asset.glb`,
- ),
- ),
- );
- return Response.json({ ok: true });
- },
- });
- await (await f.run()).arrayBuffer();
- assert.equal(f.storageCalls.length, 1);
- assert.equal(f.storageCalls[0].owner, tenant);
- assert.equal(f.storageCalls[0].url, 'https://tenant.internal/internal/downloads');
- await assert.rejects(
- f.job.storageRequest(
- new Request('http://kiln-storage.internal/internal/downloads', { method: 'POST' }),
- ),
- );
-});
-
-test('a cancelled parent refuses a late request after reconstruction without starting a VM', async () => {
- const f = fixture();
- await f.job.cancel();
- const restored = new NativeRequestJob(f.context, f.ports);
- await assert.rejects(restored.run(tenant, request(), Date.now() + 2000));
- assert.equal(f.events.includes('start'), false);
- assert.equal(f.values.get('request').state, 'finished');
-});
-
-test('cancellation during interceptor registration prevents late VM startup', async () => {
- const entered = deferred(),
- finish = deferred();
- const f = fixture({
- intercept: async () => {
- entered.resolve();
- await finish.promise;
- },
- });
- const rejected = assert.rejects(f.run());
- await entered.promise;
- await f.job.cancel();
- finish.resolve();
- await rejected;
- await turn();
- assert.equal(f.events.includes('start'), false);
- assert.equal(f.values.get('request').state, 'finished');
-});
-
-test('only one child runs at a time and subsequent evaluations get fresh IDs', async () => {
- const entered = deferred(),
- finish = deferred(),
- childStarted = deferred(),
- childFinish = deferred();
- const f = fixture({
- native: async () => {
- entered.resolve();
- await finish.promise;
- return Response.json({ ok: true });
- },
- evaluate: async () => {
- childStarted.resolve();
- await childFinish.promise;
- return Response.json({ ok: true });
- },
- });
- const run = f.run();
- await entered.promise;
- const first = f.job.evaluateRequest(evaluation());
- await childStarted.promise;
- await assert.rejects(f.job.evaluateRequest(evaluation()), (error) => error.status === 429);
- childFinish.resolve();
- await first;
- await f.job.evaluateRequest(evaluation());
- assert.equal(new Set(f.values.get('request').children.map((child) => child.id)).size, 2);
- finish.resolve();
- await run;
- assert.equal([...f.children.values()].some(Boolean), false);
-});
-
-test('failed child cleanup suppresses the host response and survives eviction for alarm recovery', async () => {
- const f = fixture({
- failChildren: true,
- native: async (_, job) => {
- await job.evaluateRequest(evaluation());
- return Response.json({ ok: true });
- },
- });
- await assert.rejects(f.run(), (error) => error.code === 'CLEANUP_FAILED');
- assert.notEqual(f.values.get('request').state, 'finished');
- assert.ok(Number.isSafeInteger(f.alarmAt));
- assert.equal(f.context.container.running, false);
- f.repair();
- await new NativeRequestJob(f.context, f.ports).alarm();
- assert.equal(f.values.get('request').state, 'finished');
- assert.equal([...f.children.values()].some(Boolean), false);
- assert.equal(f.alarmAt, undefined);
-});
-
-test('a response cannot escape while coordinator destruction is still pending', async () => {
- const entered = deferred(),
- finish = deferred();
- const f = fixture({
- destroy: async () => {
- entered.resolve();
- await finish.promise;
- },
- });
- let returned = false;
- const run = f.run().then((response) => {
- returned = true;
- return response;
- });
- await entered.promise;
- assert.equal(returned, false);
- finish.resolve();
- await run;
- assert.equal(f.context.container.running, false);
-});
-
-test('invalid coordinator configuration or forwarded authority starts no VM', async () => {
- for (const [f, req] of [
- [fixture({ image: 'registry.example/coordinator:latest' }), request()],
- [fixture(), request({ headers: { authorization: 'Bearer PRIVATE' } })],
- ]) {
- await assert.rejects(f.run(req));
- assert.equal(f.events.includes('start'), false);
- }
-});
-
-test('a durable claim that finishes after the request deadline cannot start compute', async () => {
- const f = fixture();
- const transaction = f.context.storage.transaction;
- let first = true;
- f.context.storage.transaction = (callback) =>
- transaction(async (tx) => {
- if (first) {
- first = false;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- return callback(tx);
- });
- await assert.rejects(
- f.job.run(tenant, request(), Date.now() + 20),
- (error) => error.status === 504,
- );
- assert.equal(f.events.includes('start'), false);
-});
-
-test('storage uploads preserve bytes while stripping transport-only headers', async () => {
- const f = fixture({
- native: async (_, job) => {
- await job.storageRequest(
- new Request('http://kiln-storage.internal/internal/programs', {
- method: 'POST',
- headers: {
- 'content-type': 'application/javascript',
- 'content-length': '2',
- host: 'kiln-storage.internal',
- },
- body: '{}',
- }),
- );
- return Response.json({ ok: true });
- },
- });
- f.ports.storage = async (owner, req) => {
- assert.equal(owner, tenant);
- assert.equal(await req.text(), '{}');
- assert.equal(req.headers.has('host'), false);
- return new Response('saved');
- };
- await f.run();
-});
-
-test('an unexpected coordinator image is destroyed before it receives the MCP body', async () => {
- const f = fixture({ observedImage: `registry.example/other@sha256:${'c'.repeat(64)}` });
- await assert.rejects(f.run());
- assert.equal(f.events.includes('mcp'), false);
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('request').state, 'finished');
-});
-
-test('deadline timer expiry stays a timeout when the wall clock is one millisecond behind', async (t) => {
- let now = 1_000_000;
- t.mock.method(Date, 'now', () => now);
- t.mock.timers.enable({ apis: ['setTimeout'] });
- const entered = deferred(),
- result = deferred();
- const f = fixture({
- native: async () => {
- entered.resolve();
- return result.promise;
- },
- });
- const rejected = assert.rejects(
- f.job.run(tenant, request(), now + 50),
- (error) => error.status === 504,
- );
- await entered.promise;
- now += 49;
- t.mock.timers.tick(50);
- await rejected;
- let cancelled = false;
- result.resolve(
- new Response(
- new ReadableStream({
- cancel() {
- cancelled = true;
- },
- }),
- ),
- );
- await turn();
- assert.equal(cancelled, true);
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('request').state, 'finished');
-});
-
-test('a timed-out native response cannot revive work or leak a late body', async () => {
- const entered = deferred(),
- result = deferred();
- const f = fixture({
- native: async () => {
- entered.resolve();
- return result.promise;
- },
- });
- const rejected = assert.rejects(
- f.job.run(tenant, request(), Date.now() + 50),
- (error) => error.status === 504,
- );
- await entered.promise;
- await rejected;
- let cancelled = false;
- result.resolve(
- new Response(
- new ReadableStream({
- cancel() {
- cancelled = true;
- },
- }),
- ),
- );
- await turn();
- assert.equal(cancelled, true);
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('request').state, 'finished');
-});
-
-test('one admitted request cannot spawn more than eight child evaluations', async () => {
- const f = fixture({
- native: async (_, job) => {
- for (let i = 0; i < 8; i++) await (await job.evaluateRequest(evaluation())).arrayBuffer();
- await assert.rejects(job.evaluateRequest(evaluation()), (error) => error.status === 429);
- return Response.json({ ok: true });
- },
- });
- await f.run();
- assert.equal(f.values.get('request').children.length, 8);
- assert.equal([...f.children.values()].some(Boolean), false);
-});
-
-test('an oversized native response is discarded and coordinator cleanup is still required', async () => {
- const f = fixture({ native: async () => new Response(new Uint8Array(32 * 1024 * 1024 + 1)) });
- await assert.rejects(f.run(), (error) => error.status === 413);
- assert.equal(f.context.container.running, false);
- assert.equal(f.values.get('request').state, 'finished');
-});
diff --git a/hosting/test/request-limits-worker.ts b/hosting/test/request-limits-worker.ts
deleted file mode 100644
index 21a6c5fd..00000000
--- a/hosting/test/request-limits-worker.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import gateway from '../src/worker';
-import { forwardTenant } from '../src/gateway';
-import { browserDownload } from '../src/browser-download';
-import { D1BrowserSessions } from '../src/browser-sessions';
-
-// Test-only I/O observations and identities. This module never enters production.
-let calls = { auth: 0, storage: 0, compute: 0 };
-export default {
- async fetch(request: Request, env: Parameters<typeof gateway.fetch>[1], ctx: ExecutionContext) {
- const url = new URL(request.url);
- if (url.pathname === '/fixture/stats') return Response.json(calls);
- if (url.pathname === '/fixture/reset') {
- calls = { auth: 0, storage: 0, compute: 0 };
- return new Response('reset');
- }
- if (url.pathname === '/fixture/session') {
- const session = await new D1BrowserSessions(env.ACCOUNTS, env.PUBLIC_ORIGIN).issue({
- issuer: 'https://github.com',
- subject: await request.text(),
- });
- return Response.json(
- { accountId: session.account.id },
- { headers: { 'set-cookie': session.cookie } },
- );
- }
- if (request.headers.has('x-fixture-ingress')) {
- const forbidden = new Proxy(
- {},
- {
- get() {
- calls.auth++;
- throw new Error('Unexpected auth I/O');
- },
- },
- );
- const deny = {
- async limit() {
- return { success: false };
- },
- };
- const limited = {
- ...env,
- ACCOUNTS: forbidden,
- OAUTH_KV: forbidden,
- EDGE_REQUEST_LIMIT:
- request.headers.get('x-fixture-ingress') === 'missing' ? undefined : deny,
- };
- return gateway.fetch(request, limited as unknown as typeof env, ctx);
- }
- const downstream = {
- ...env,
- TENANTS: {
- getByName() {
- calls.storage++;
- return {
- async fetch() {
- return new Response('saved bytes');
- },
- };
- },
- },
- NATIVE_COMPUTE: {
- async dispatch() {
- calls.compute++;
- return new Response('computed');
- },
- },
- } as unknown as typeof env;
- if (url.pathname === '/fixture/mcp') {
- const incoming = new Request(`${env.PUBLIC_ORIGIN}/mcp`, request);
- return forwardTenant(
- incoming,
- downstream,
- {
- auth: { userId: request.headers.get('x-fixture-account')!, scope: ['kiln:use'] },
- } as Parameters<typeof forwardTenant>[2],
- env.PUBLIC_ORIGIN,
- );
- }
- if (url.pathname.startsWith('/downloads/'))
- return browserDownload(request, downstream, env.PUBLIC_ORIGIN);
- return gateway.fetch(request, env, ctx);
- },
-};
diff --git a/hosting/test/request-limits.test.mjs b/hosting/test/request-limits.test.mjs
deleted file mode 100644
index 3fe7b418..00000000
--- a/hosting/test/request-limits.test.mjs
+++ /dev/null
@@ -1,264 +0,0 @@
-import assert from 'node:assert/strict';
-import { test, before, after } from 'node:test';
-import { build } from 'esbuild';
-import { mkdir } from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
-import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
-import { migrateAccounts } from './database.mjs';
-
-let limitIngress, limitAccount, runtime;
-const origin = 'https://kiln.example.com';
-const request = (path, options) => new Request(`${origin}${path}`, options);
-const account = `ka_${'a'.repeat(32)}`;
-function fixture(outcome = { success: true }) {
- const keys = [];
- const binding = {
- async limit({ key }) {
- keys.push(key);
- if (outcome instanceof Error) throw outcome;
- return outcome;
- },
- };
- return { keys, env: { EDGE_REQUEST_LIMIT: binding, ACCOUNT_REQUEST_LIMIT: binding } };
-}
-before(async () => {
- const output = new URL('../../.cache/request-limit-tests/limits.mjs', import.meta.url);
- await mkdir(fileURLToPath(new URL('.', output)), { recursive: true });
- await build({
- entryPoints: [fileURLToPath(new URL('../src/request-limits.ts', import.meta.url))],
- bundle: true,
- format: 'esm',
- platform: 'node',
- outfile: fileURLToPath(output),
- });
- ({ limitIngress, limitAccount } = await import(output));
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('./request-limits-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- conditions: ['workerd'],
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare(
- convertV4MiniflareOptions({
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['global_fetch_strictly_public'],
- bindings: { PUBLIC_ORIGIN: origin },
- d1Databases: ['ACCOUNTS'],
- kvNamespaces: ['OAUTH_KV'],
- ratelimits: {
- EDGE_REQUEST_LIMIT: { namespace_id: '1001', simple: { limit: 2, period: 60 } },
- ACCOUNT_REQUEST_LIMIT: { namespace_id: '1002', simple: { limit: 2, period: 60 } },
- },
- outboundService: () => {
- throw new Error('External I/O forbidden');
- },
- }),
- );
- await migrateAccounts(await runtime.getD1Database('ACCOUNTS'));
-});
-after(async () => runtime?.dispose());
-
-test('all caller variations of one route share a bounded ingress bucket without private data', async () => {
- const f = fixture();
- for (const path of ['/register', '/register?client_id=private-name&code=private-code']) {
- assert.equal(
- await limitIngress(
- request(path, {
- method: 'POST',
- headers: {
- authorization: 'Bearer private-token',
- cookie: 'private-cookie',
- 'x-tenant': 'arbitrary',
- 'cf-connecting-ip': '192.0.2.1',
- },
- body: 'private-source',
- }),
- f.env,
- origin,
- ),
- undefined,
- );
- }
- assert.equal(f.keys.length, 2);
- assert.equal(f.keys[0], f.keys[1]);
- assert(!f.keys.some((key) => /private-|192\.0|arbitrary/.test(key)));
- for (const path of ['/mcp', '/mcp/artifacts/a', '/mcp/artifacts/b?code=secret'])
- await limitIngress(request(path), f.env, origin);
- assert.equal(new Set(f.keys.slice(2)).size, 1);
- assert.notEqual(f.keys[0], f.keys[2]);
- for (const path of ['/oauth/google/callback?state=a', '/oauth/github/callback?state=b'])
- await limitIngress(request(path), f.env, origin);
- assert.equal(f.keys[5], f.keys[6]);
- for (const path of ['/arbitrary-one', '/arbitrary-two', '/oauth/token/anything'])
- await limitIngress(request(path), f.env, origin);
- assert.equal(f.keys[7], f.keys[8]);
- assert.notEqual(f.keys[7], f.keys[9]);
-});
-
-test('a stalled limiter fails closed at the real one-second deadline', async () => {
- const f = fixture();
- f.env.EDGE_REQUEST_LIMIT = { limit: () => new Promise(() => {}) };
- const result = await limitIngress(request('/mcp'), f.env, origin);
- assert.equal(result.status, 503);
- assert.equal(await result.text(), 'Service temporarily unavailable');
-});
-
-test('gateway refuses exhausted or missing limits before OAuth, database or provider I/O', async () => {
- await runtime.dispatchFetch(`${origin}/fixture/reset`);
- for (const mode of ['deny', 'missing']) {
- for (const path of [
- '/register',
- '/oauth/token',
- '/authorize',
- '/oauth/google/callback',
- '/oauth/github/callback',
- '/account',
- '/account/delete',
- '/downloads/private/file.glb',
- '/mcp',
- '/mcp/artifacts/private',
- '/.well-known/oauth-authorization-server',
- ]) {
- const response = await runtime.dispatchFetch(`${origin}${path}`, {
- headers: {
- 'x-fixture-ingress': mode,
- authorization: 'Bearer private-token',
- cookie: 'private-cookie',
- },
- });
- assert.equal(response.status, mode === 'deny' ? 429 : 503, `${mode} ${path}`);
- }
- }
- assert.deepEqual(await (await runtime.dispatchFetch(`${origin}/fixture/stats`)).json(), {
- auth: 0,
- storage: 0,
- compute: 0,
- });
-});
-
-test('real local edge binding exhausts a route bucket without unbounded caller keys', async () => {
- // No auth/storage access for unknown paths; 404 confirms the admitted branch.
- const statuses = [];
- for (let i = 0; i < 3; i++) {
- const response = await runtime.dispatchFetch(`${origin}/unknown-${i}?ignored=${i}`);
- statuses.push(response.status);
- await response.text();
- }
- assert.deepEqual(statuses, [404, 404, 429]);
- const discovery = await runtime.dispatchFetch(`${origin}/.well-known/oauth-authorization-server`);
- assert.equal(discovery.status, 200);
- assert.equal((await discovery.json()).issuer, origin);
-});
-
-test('real account binding shares MCP and browser attempts while isolating another account', async () => {
- await runtime.dispatchFetch(`${origin}/fixture/reset`);
- const session = async (subject) => {
- const response = await runtime.dispatchFetch(`${origin}/fixture/session`, {
- method: 'POST',
- body: subject,
- });
- return { ...(await response.json()), cookie: response.headers.get('set-cookie').split(';')[0] };
- };
- const alice = await session('rate-alice'),
- bob = await session('rate-bob');
- const invoke = async (identity, method) =>
- runtime.dispatchFetch(`${origin}/fixture/mcp`, {
- method: 'POST',
- headers: {
- 'x-fixture-account': identity.accountId,
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method,
- params:
- method === 'tools/call'
- ? { name: 'kiln_validate', arguments: { code: 'function build(){}' } }
- : {},
- }),
- });
- assert.equal((await invoke(alice, 'tools/list')).status, 200);
- const download = (identity) =>
- runtime.dispatchFetch(`${origin}/downloads/${'a'.repeat(64)}/asset.glb`, {
- headers: { cookie: identity.cookie },
- });
- assert.equal((await download(alice)).status, 200);
- const blocked = await invoke(alice, 'tools/call');
- assert.equal(blocked.status, 429);
- assert.equal(blocked.headers.get('retry-after'), '60');
- assert.equal((await download(alice)).status, 429);
- assert.equal((await download(bob)).status, 200);
- assert.deepEqual(await (await runtime.dispatchFetch(`${origin}/fixture/stats`)).json(), {
- auth: 0,
- storage: 2,
- compute: 0,
- });
-});
-
-test('ingress rejection cancels the unread body and returns a retryable private response', async () => {
- const f = fixture({ success: false });
- let cancelled = false;
- const body = new ReadableStream({
- cancel() {
- cancelled = true;
- },
- });
- const response = await limitIngress(
- request('/register', { method: 'POST', body, duplex: 'half' }),
- f.env,
- origin,
- );
- assert.equal(response.status, 429);
- assert.equal(response.headers.get('retry-after'), '60');
- assert.equal(response.headers.get('cache-control'), 'no-store');
- assert.equal(cancelled, true);
-});
-
-test('missing, broken and malformed limiter results fail closed without exposing their data', async () => {
- for (const outcome of [new Error('private-provider-secret'), {}, { success: 'true' }, null]) {
- const f = fixture(outcome);
- const result = await limitIngress(request('/oauth/token'), f.env, origin);
- assert.equal(result.status, 503);
- assert(!/secret|provider/.test(await result.text()));
- }
- for (const env of [{}, { EDGE_REQUEST_LIMIT: fixture().env.EDGE_REQUEST_LIMIT }])
- assert.equal((await limitIngress(request('/mcp'), env, origin)).status, 503);
-});
-
-test('account limits use verified permanent ownership across tokens, apps and network addresses', async () => {
- const f = fixture();
- for (const [path, token, ip] of [
- ['/mcp', 'one', '192.0.2.1'],
- ['/downloads/two/file.glb', 'two', '192.0.2.2'],
- ])
- assert.equal(
- await limitAccount(
- request(path, { headers: { authorization: `Bearer ${token}`, 'cf-connecting-ip': ip } }),
- f.env,
- origin,
- account,
- ),
- undefined,
- );
- assert.equal(f.keys.length, 2);
- assert.equal(f.keys[0], f.keys[1]);
- assert(!f.keys[0].includes(account));
- await limitAccount(request('/mcp'), f.env, origin, `ka_${'b'.repeat(32)}`);
- assert.notEqual(f.keys[0], f.keys[2]);
- await limitAccount(request('/mcp'), f.env, 'https://other.example.com', account);
- assert.notEqual(f.keys[0], f.keys[3]);
- const denied = fixture({ success: false });
- assert.equal((await limitAccount(request('/mcp'), denied.env, origin, account)).status, 429);
- assert.equal(
- (await limitAccount(request('/mcp'), denied.env, origin, 'caller-selected-user')).status,
- 401,
- );
- assert.equal(denied.keys.length, 1);
-});
diff --git a/hosting/test/request-worker.test.mjs b/hosting/test/request-worker.test.mjs
deleted file mode 100644
index fe721db9..00000000
--- a/hosting/test/request-worker.test.mjs
+++ /dev/null
@@ -1,159 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-let runtime, namespace;
-before(async () => {
- const result = await build({
- stdin: {
- contents: `
- import production from './src/request-worker';
- import {KilnNativeRequest} from './src/request-worker';
- import {DurableObject} from 'cloudflare:workers';
- import {handleRenderRequest} from './src/evaluation-request';
- export * from './src/request-worker';
- export {KilnTenant} from './src/tenant';
- export class RequestFixture extends KilnNativeRequest {
- async fixtureSeed(tenant) { await this.ctx.storage.put('request', {state:'running',tenant,deadlineAt:Date.now()+60000,children:[]}); }
- async fixtureRecord() { return this.ctx.storage.get('request'); }
- async fixtureClose() { const record=await this.ctx.storage.get('request'); await this.ctx.storage.put('request',{...record,state:'finished'}); }
- }
- export class RenderFixture extends DurableObject {
- fetch(request) { return handleRenderRequest(request,{run:async(bytes)=>{
- if(await this.ctx.storage.get('used')) throw Error('duplicate');
- await this.ctx.storage.put('used',true); return bytes;
- }}); }
- async cancel(){await this.ctx.storage.put('cancelled',true);}
- async fixtureRecord(){return {used:await this.ctx.storage.get('used'),cancelled:await this.ctx.storage.get('cancelled')};}
- }
- export default {async fetch(request, env, ctx) {
- const url = new URL(request.url);
- if (url.pathname === '/public') return production.fetch(request);
- const requestId = env.REQUESTS.idFromName(url.searchParams.get('owner')).toString();
- const stub = env.REQUESTS.get(env.REQUESTS.idFromString(requestId));
- if (url.pathname === '/fixture-seed') { await stub.fixtureSeed(await request.text()); return new Response('seeded'); }
- if (url.pathname === '/fixture-record') return Response.json(await stub.fixtureRecord());
- if (url.pathname === '/fixture-close') {await stub.fixtureClose();return new Response('closed');}
- if (url.pathname === '/fixture-render-record') {const record=await stub.fixtureRecord();return Response.json(await env.RENDERS.getByName(record.children.at(-1).id).fixtureRecord());}
- if (url.pathname === '/cancel') { await stub.cancel(); return new Response('cancelled'); }
- const render=url.pathname==='/render';
- const service = render ? ctx.exports.KilnNativeRender({props: {requestId}}) : ctx.exports.KilnNativeStorage({props: {requestId}});
- // The fixture enters through a public test listener; real VM loopback
- // requests do not carry Miniflare's public ingress client-IP header.
- const headers = new Headers(request.headers); headers.delete('cf-connecting-ip');
- return service.fetch(new Request((render?'http://kiln-renderer.internal':'http://kiln-storage.internal')+url.pathname, new Request(request,{headers})));
- }};`,
- resolveDir: fileURLToPath(new URL('../', import.meta.url)),
- loader: 'ts',
- },
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- name: 'request-fixture',
- modules: true,
- script: result.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- durableObjects: {
- REQUESTS: { className: 'RequestFixture', useSQLite: true },
- TENANTS: { className: 'KilnTenant', useSQLite: true },
- RENDERS: { className: 'RenderFixture', useSQLite: true },
- },
- bindings: {
- PUBLIC_ORIGIN: 'https://kiln.example.com',
- STORAGE_MAX_BYTES: '1048576',
- STORAGE_MAX_OBJECTS: '32',
- STORAGE_MAX_GROUPS: '8',
- },
- r2Buckets: ['ARTIFACTS'],
- outboundService: async () => {
- throw Error('No external fetch in private fixture');
- },
- }),
- unsafeInspectDurableObjects: true,
- });
- namespace = await runtime.getDurableObjectNamespace('REQUESTS');
-});
-after(async () => runtime?.dispose());
-const send = (owner, path, init) =>
- runtime.dispatchFetch(`https://fixture.invalid${path}?owner=${owner}`, init);
-async function active(owner, tenant) {
- assert.equal((await send(owner, '/fixture-seed', { method: 'POST', body: tenant })).status, 200);
-}
-
-test('private request Worker exposes no default public service', async () => {
- assert.equal((await send('no-owner', '/public')).status, 404);
-});
-
-test('actual loopback props and DO RPC route storage using the outside durable tenant record', async () => {
- await active('alice', 'a'.repeat(43));
- await active('bob', 'b'.repeat(43));
- const source = '// private Alice source\nfunction build(){return createRoot();}';
- const saved = await send('alice', '/internal/programs', {
- method: 'POST',
- headers: { 'content-type': 'application/javascript' },
- body: source,
- });
- assert.equal(saved.status, 201);
- const { programRef } = await saved.json();
- const path = `/internal/programs/${encodeURIComponent(programRef)}`;
- assert.equal(await (await send('alice', path)).text(), source);
- assert.equal((await send('bob', path)).status, 404);
- assert.equal((await send('bob', path, { headers: { 'x-tenant': 'a'.repeat(43) } })).status, 400);
- await runtime.unsafeEvictDurableObject('request-fixture', 'RequestFixture', {
- id: namespace.idFromName('alice').toString(),
- });
- assert.equal(await (await send('alice', path)).text(), source);
-});
-
-test('actual cancellation RPC writes a persistent pre-arrival fence and rejects storage afterward', async () => {
- assert.equal((await send('cancelled', '/cancel')).status, 200);
- assert.equal((await (await send('cancelled', '/fixture-record')).json()).state, 'finished');
- await runtime.unsafeEvictDurableObject('request-fixture', 'RequestFixture', {
- id: namespace.idFromName('cancelled').toString(),
- });
- assert.equal((await send('cancelled', '/internal/programs')).status, 409);
-});
-
-test('actual renderer loopback uses host-owned props and a fresh durable child, then acknowledges cancellation', async () => {
- const owner = 'render-owner';
- await active(owner, 'r'.repeat(43));
- const init = {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'x-kiln-deadline-ms': '30000',
- 'x-kiln-max-response-bytes': '20971520',
- },
- body: '{}',
- };
- const result = await send(owner, '/render', init);
- assert.equal(result.status, 200);
- assert.equal(await result.text(), '{}');
- const record = await (await send(owner, '/fixture-record')).json();
- assert.equal(record.children.length, 1);
- assert.equal(record.children[0].kind, 'render');
- assert.match(record.children[0].id, /^[a-f0-9-]{36}$/);
- assert.equal(record.activeChild, undefined);
- assert.deepEqual(await (await send(owner, '/fixture-render-record')).json(), {
- used: true,
- cancelled: true,
- });
- const forged = await send(owner, '/render', {
- ...init,
- headers: { ...init.headers, 'x-request-id': 'other', 'x-tenant': 'other' },
- });
- assert.equal(forged.status, 400);
- await send(owner, '/fixture-close', { method: 'POST' });
- await runtime.unsafeEvictDurableObject('request-fixture', 'RequestFixture', {
- id: namespace.idFromName(owner).toString(),
- });
- assert.equal((await send(owner, '/render', init)).status, 409);
- assert.equal((await (await send(owner, '/fixture-record')).json()).children.length, 1);
-});
diff --git a/hosting/test/resilience.test.mjs b/hosting/test/resilience.test.mjs
deleted file mode 100644
index 2f21daec..00000000
--- a/hosting/test/resilience.test.mjs
+++ /dev/null
@@ -1,456 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-import { readFile } from 'node:fs/promises';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-let runResilienceOnce,
- resilienceCases,
- observeResilience,
- checkResilienceResult,
- ResilienceExecution,
- resilienceImage;
-before(async () => {
- for (const module of [
- 'resilience-run',
- 'resilience-observation',
- 'resilience-result',
- 'resilience-execution',
- ]) {
- const output = new URL(`../../.cache/resilience-test/${module}.mjs`, import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL(`../probe/${module}.ts`, import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- const value = await import(output);
- if (module === 'resilience-run') ({ runResilienceOnce, resilienceCases } = value);
- if (module === 'resilience-observation') ({ observeResilience } = value);
- if (module === 'resilience-result') ({ checkResilienceResult } = value);
- if (module === 'resilience-execution') ({ ResilienceExecution, resilienceImage } = value);
- }
-});
-
-function runningFixture() {
- const store = storage();
- let alarmAt;
- store.setAlarm = async (time) => {
- alarmAt = time;
- };
- store.deleteAlarm = async () => {
- alarmAt = undefined;
- };
- let exited, stopped, stdout;
- const monitor = new Promise((resolve) => {
- stopped = resolve;
- });
- const exitCode = new Promise((resolve) => {
- exited = resolve;
- });
- const calls = [];
- const container = {
- images: { kiln: resilienceImage },
- running: false,
- start() {
- calls.push('start');
- this.running = true;
- },
- async setInactivityTimeout() {},
- monitor() {
- return monitor;
- },
- async inspect() {
- return this.running ? { image: resilienceImage } : null;
- },
- async exec() {
- calls.push('exec');
- return {
- stdin: new WritableStream({
- write() {
- calls.push('input');
- },
- }),
- stdout: new ReadableStream({
- start(c) {
- stdout = c;
- c.enqueue(new TextEncoder().encode('KILN_PROBE_READY\n'));
- },
- }),
- stderr: new ReadableStream({
- start(c) {
- c.close();
- },
- }),
- exitCode,
- };
- },
- async destroy() {
- calls.push('destroy');
- this.running = false;
- stdout?.close();
- exited(0);
- stopped();
- },
- };
- return { context: { container, storage: store }, calls, alarmAt: () => alarmAt };
-}
-
-test('native cancellation begins after readiness, destroys once and retains the outcome', async (t) => {
- t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1_000_000 });
- const f = runningFixture();
- const execution = new ResilienceExecution(f.context);
- const pending = execution.run('native-cancel');
- await new Promise((resolve) => setImmediate(resolve));
- assert.ok(f.calls.includes('input'));
- assert.equal(f.calls.includes('destroy'), false);
- t.mock.timers.tick(251);
- const result = await pending;
- assert.equal(result.passed, true);
- assert.equal(result.reason, 'CANCELLED');
- assert.equal(result.ready, true);
- assert.equal(result.stopped, true);
- assert.deepEqual(await execution.run('native-cancel'), result);
- assert.equal(f.calls.filter((c) => c === 'start').length, 1);
- assert.equal(f.calls.filter((c) => c === 'destroy').length, 1);
- assert.equal(f.alarmAt(), undefined);
-});
-
-test('recovery requires the durable deadline callback; a new controller cannot reexecute the claim', async (t) => {
- t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 2_000_000 });
- const f = runningFixture();
- const pending = new ResilienceExecution(f.context).run('alarm-recovery');
- await new Promise((resolve) => setImmediate(resolve));
- t.mock.timers.tick(251);
- const waiting = await pending;
- assert.equal(waiting.pendingAlarm, true);
- assert.equal(waiting.passed, false);
- assert.equal(f.context.container.running, true);
- const restarted = new ResilienceExecution(f.context);
- assert.deepEqual(await restarted.run('alarm-recovery'), waiting);
- await restarted.alarm();
- assert.equal((await restarted.read()).passed, false);
- assert.equal(f.context.container.running, true);
- t.mock.timers.tick(15_000);
- await restarted.alarm();
- const recovered = await restarted.read();
- assert.equal(recovered.passed, true);
- assert.equal(recovered.reason, 'ALARM_RECOVERED');
- assert.equal(recovered.stopped, true);
- assert.equal(recovered.pendingAlarm, false);
- assert.equal(f.alarmAt(), undefined);
- assert.equal(f.calls.filter((c) => c === 'start').length, 1);
-});
-
-test('operator teardown after missing alarm never converts failure to a qualification pass', async (t) => {
- t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 3_000_000 });
- const f = runningFixture();
- const execution = new ResilienceExecution(f.context);
- const pending = execution.run('alarm-recovery');
- await new Promise((resolve) => setImmediate(resolve));
- t.mock.timers.tick(251);
- await pending;
- const stopped = await execution.stopUnconfirmed();
- assert.equal(stopped.passed, false);
- assert.equal(stopped.stopped, true);
- assert.equal(stopped.reason, 'ALARM_NOT_OBSERVED');
- t.mock.timers.tick(15_000);
- // A later real alarm can finish cleanup, but cannot overwrite the failed proof.
- f.context.container.destroy = async () => {
- f.context.container.running = false;
- };
- await execution.alarm();
- assert.deepEqual(await execution.read(), stopped);
-});
-
-function storage() {
- const records = new Map();
- let tail = Promise.resolve();
- const result = {
- async get(key) {
- return structuredClone(records.get(key));
- },
- async put(key, value) {
- records.set(key, structuredClone(value));
- },
- transaction(fn) {
- const next = tail.then(() => fn(result));
- tail = next.catch(() => {});
- return next;
- },
- };
- return result;
-}
-
-test('resilience allowance is fixed, claimed once and sequential even under concurrent invocations', async () => {
- const store = storage();
- const calls = [];
- let active = 0;
- const execute = async (name) => {
- assert.equal(active++, 0);
- calls.push(name);
- await new Promise((resolve) => setImmediate(resolve));
- active--;
- return { name, passed: true, stopped: true };
- };
- await Promise.all([runResilienceOnce(store, execute), runResilienceOnce(store, execute)]);
- const retained = await runResilienceOnce(store, execute);
- assert.deepEqual(resilienceCases, [
- 'cpu-preview',
- 'software-views',
- 'network',
- 'write-marker',
- 'read-marker',
- 'native-deadline',
- 'native-cancel',
- 'stdout-flood',
- 'stderr-flood',
- 'memory-limit',
- 'alarm-recovery',
- 'engine-after',
- ]);
- assert.deepEqual(calls, resilienceCases);
- assert.equal(retained.state, 'finished');
- assert.equal(retained.results.length, 12);
-});
-
-test('failure or interruption never authorizes another batch or exposes arbitrary errors', async () => {
- const store = storage();
- let calls = 0;
- const execute = async () => {
- calls++;
- throw new Error('PRIVATE_DIAGNOSTIC');
- };
- const record = await runResilienceOnce(store, execute);
- assert.deepEqual(record.results, [
- { name: 'cpu-preview', passed: false, reason: 'PROBE_FAILED' },
- ]);
- assert.deepEqual(await runResilienceOnce(store, execute), record);
- assert.equal(calls, 1);
- const interrupted = storage();
- await interrupted.put('run', { state: 'running', results: [] });
- await runResilienceOnce(interrupted, execute);
- assert.equal(calls, 1);
-});
-
-test('readiness observes split fixed prefix, preserves bytes and never mistakes partial output for readiness', async () => {
- let ready = 0;
- let received;
- const actual = {
- async exec(command, options) {
- received = { command, options };
- return {
- stdin: null,
- stderr: null,
- stdout: new ReadableStream({
- start(c) {
- for (const chunk of ['KILN_', 'PROBE_READY\n', 'body'])
- c.enqueue(new TextEncoder().encode(chunk));
- c.close();
- },
- }),
- exitCode: Promise.resolve(0),
- };
- },
- };
- const observer = observeResilience(actual, 'fixed script', () => {
- ready++;
- });
- const process = await observer.container.exec(['original'], { user: '1000:1000' });
- assert.equal(await new Response(process.stdout).text(), 'KILN_PROBE_READY\nbody');
- assert.equal(ready, 1);
- assert.equal(observer.ready(), true);
- assert.deepEqual(received.command, [
- '/usr/local/bin/node',
- '--input-type=module',
- '-e',
- 'fixed script',
- ]);
- assert.equal(received.options.user, '1000:1000');
- assert.equal(observer.exitCode(), 0);
- const partial = observeResilience(
- {
- async exec() {
- return {
- stdout: new ReadableStream({
- start(c) {
- c.enqueue(new TextEncoder().encode('KILN_PROBE_'));
- c.close();
- },
- }),
- exitCode: Promise.resolve(0),
- };
- },
- },
- 'fixed',
- () => {
- assert.fail('partial prefix');
- },
- );
- await new Response((await partial.container.exec([])).stdout).text();
- assert.equal(partial.ready(), false);
-});
-
-test('destruction fault injection is probe-only and fails once without swallowing subsequent cleanup', async () => {
- let destroyed = 0;
- const observer = observeResilience(
- {
- async destroy() {
- destroyed++;
- },
- },
- 'fixed',
- () => {},
- true,
- );
- await assert.rejects(observer.container.destroy());
- assert.equal(destroyed, 0);
- await observer.container.destroy();
- assert.equal(destroyed, 1);
-});
-
-test('failure qualification requires the exact failure, real native readiness and confirmed destruction', async () => {
- const base = { name: 'native-cancel', reason: 'CANCELLED', ready: true, stopped: true };
- assert.equal((await checkResilienceResult(base)).passed, true);
- for (const change of [{ reason: 'WORKER_FAILED' }, { ready: false }, { stopped: false }]) {
- assert.equal((await checkResilienceResult({ ...base, ...change })).passed, false);
- }
- assert.equal(
- (
- await checkResilienceResult({
- name: 'engine-after',
- stopped: true,
- output: new TextEncoder().encode('{"ok":true}'),
- })
- ).passed,
- false,
- );
- assert.equal(
- (
- await checkResilienceResult({
- name: 'memory-limit',
- stopped: true,
- output: new TextEncoder().encode('{"ok":true,"oomKills":0}'),
- })
- ).passed,
- false,
- );
-});
-
-test('software proof rejects a truncated PNG even when reported colour counts look valid', async () => {
- const png = Buffer.alloc(24);
- png.set([137, 80, 78, 71]);
- png.writeUInt32BE(128, 16);
- png.writeUInt32BE(128, 20);
- const views = ['neutral', 'dark', 'light'].flatMap((backdrop) =>
- [0, 1].map((index) => ({
- backdrop,
- index,
- red: 100,
- green: 100,
- pngBase64: png.toString('base64'),
- })),
- );
- const output = new TextEncoder().encode(JSON.stringify({ ok: true, software: true, views }));
- assert.equal(
- (await checkResilienceResult({ name: 'software-views', stopped: true, output })).passed,
- false,
- );
-});
-
-test('the resilience candidate has no public entry or trigger and pins the stable software image', async () => {
- const config = JSON.parse(
- await readFile(new URL('../probe/resilience.wrangler.jsonc', import.meta.url), 'utf8'),
- );
- assert.equal(config.workers_dev, false);
- assert.equal(config.preview_urls, false);
- assert.deepEqual(config.routes, []);
- assert.equal(config.triggers, undefined);
- assert.equal(config.main, './resilience-worker.ts');
- assert.equal(config.containers.length, 1);
- assert.equal(config.containers[0].scheduling_policy, 'durable_object');
- assert.equal(config.containers[0].class_name, 'KilnResilienceJob');
- assert.equal(config.containers[0].images.kiln.image, resilienceImage);
- assert.equal(config.containers[0].observability.logs.enabled, false);
- assert.deepEqual(config.exports, {
- KilnResilienceControl: { type: 'worker' },
- KilnResilienceRun: { type: 'durable-object', storage: 'sqlite' },
- KilnResilienceJob: { type: 'durable-object', storage: 'sqlite' },
- });
-});
-
-test('unknown cases and wrong images are rejected before a native job can start', async () => {
- const f = runningFixture();
- const execution = new ResilienceExecution(f.context);
- await assert.rejects(execution.run('arbitrary-code'));
- f.context.container.images.kiln = 'wrong';
- assert.deepEqual(await execution.run('cpu-preview'), {
- name: 'cpu-preview',
- passed: false,
- reason: 'IMAGE_UNAVAILABLE',
- });
- assert.deepEqual(f.calls, []);
- assert.equal(await f.context.storage.get('probe'), undefined);
-});
-
-test('real Worker RPC admits only the fixed retained batch and denies HTTP execution', async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL('../probe/resilience-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- const runtime = new Miniflare(
- convertV4MiniflareOptions({
- workers: [
- {
- name: 'private-resilience',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- compatibilityFlags: ['enable_ctx_exports'],
- durableObjects: {
- RUN: { className: 'KilnResilienceRun', useSQLite: true },
- JOB: { className: 'KilnResilienceJob', useSQLite: true },
- },
- outboundService: async () => {
- throw new Error('No network');
- },
- },
- {
- name: 'operator',
- modules: true,
- compatibilityDate: '2026-10-06',
- serviceBindings: {
- PROBE: { name: 'private-resilience', entrypoint: 'KilnResilienceControl' },
- },
- script: `export default { async fetch(request,env){if(new URL(request.url).pathname==='/denied')return env.PROBE.fetch(request);return Response.json(await env.PROBE.runFixed({code:'arbitrary source is ignored'}));} }`,
- },
- ],
- }),
- );
- try {
- const worker = await runtime.getWorker('private-resilience');
- const operator = await runtime.getWorker('operator');
- assert.equal(
- (await worker.fetch('http://localhost/execute', { method: 'POST', body: '{}' })).status,
- 404,
- );
- assert.equal(
- (await operator.fetch('http://localhost/denied', { method: 'POST', body: '{}' })).status,
- 404,
- );
- const first = await (await operator.fetch('http://localhost/run')).json();
- assert.deepEqual(first, {
- state: 'finished',
- results: [{ name: 'cpu-preview', passed: false, reason: 'CONTAINER_UNAVAILABLE' }],
- });
- assert.deepEqual(await (await operator.fetch('http://localhost/run')).json(), first);
- } finally {
- await runtime.dispose();
- }
-});
diff --git a/hosting/test/startup-diagnostic.test.mjs b/hosting/test/startup-diagnostic.test.mjs
deleted file mode 100644
index 5c753d99..00000000
--- a/hosting/test/startup-diagnostic.test.mjs
+++ /dev/null
@@ -1,438 +0,0 @@
-import assert from 'node:assert/strict';
-import { fileURLToPath } from 'node:url';
-import { before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-let ManagedStartupDiagnostic;
-before(async () => {
- const output = new URL('../../.cache/startup-diagnostic-test/diagnostic.mjs', import.meta.url);
- await build({
- entryPoints: [fileURLToPath(new URL('../probe/startup-diagnostic.ts', import.meta.url))],
- outfile: fileURLToPath(output),
- bundle: true,
- format: 'esm',
- platform: 'node',
- });
- ({ ManagedStartupDiagnostic } = await import(output));
-});
-
-function fixture(options = {}) {
- const records = new Map();
- const calls = [];
- let tail = Promise.resolve();
- let alarmAt;
- let cleanupFails = options.cleanupFails ?? false;
- let finishMonitor;
- let failMonitor;
- const monitor = new Promise((resolve, reject) => {
- finishMonitor = resolve;
- failMonitor = reject;
- });
- const output = new TextEncoder().encode(
- options.output ?? JSON.stringify({ version: 'v24.20.0', uid: 0, gid: 0 }),
- );
- const stream = (bytes) =>
- new ReadableStream({
- start(controller) {
- controller.enqueue(bytes);
- controller.close();
- },
- });
- const container = {
- images: options.images ?? {},
- running: false,
- start(settings) {
- calls.push('start');
- this.settings = settings;
- this.running = true;
- if (options.startFails) throw new Error('private startup details');
- },
- monitor() {
- calls.push('monitor');
- if (options.monitorThrows) throw new Error('private synchronous monitor details');
- return monitor;
- },
- async setInactivityTimeout(ms) {
- calls.push('inactivity');
- this.inactivity = ms;
- },
- async exec(command, settings) {
- calls.push('exec');
- this.command = command;
- this.execSettings = settings;
- if (options.monitorFails) {
- failMonitor(new Error('private monitor details'));
- return new Promise(() => {});
- }
- if (options.execFails) throw new Error('private exec details');
- if (options.hang) return new Promise(() => {});
- return {
- stdout: stream(output),
- stderr: stream(new TextEncoder().encode(options.stderr ?? '')),
- exitCode: Promise.resolve(options.exitCode ?? 0),
- };
- },
- async inspect() {
- calls.push('inspect');
- if (!this.running) return null;
- return { image: options.image ?? this.settings.image };
- },
- async destroy() {
- calls.push('destroy');
- if (options.cleanupHangs) return new Promise(() => {});
- if (cleanupFails) throw new Error('private cleanup details');
- this.running = false;
- if (options.cleanupMonitorFails) failMonitor(new Error('private teardown details'));
- else finishMonitor();
- },
- };
- const storage = {
- async get(key) {
- return structuredClone(records.get(key));
- },
- async put(key, value) {
- records.set(key, structuredClone(value));
- },
- async setAlarm(value) {
- alarmAt = Number(value);
- calls.push('alarm');
- },
- async deleteAlarm() {
- alarmAt = undefined;
- },
- transaction(callback) {
- const operation = tail.then(() => callback(storage));
- tail = operation.catch(() => {});
- return operation;
- },
- };
- return {
- context: { container: options.absent ? undefined : container, storage },
- records,
- calls,
- container,
- get alarmAt() {
- return alarmAt;
- },
- repairCleanup() {
- cleanupFails = false;
- },
- };
-}
-
-test('managed control runs one fixed command offline and retains phase and destruction evidence', async () => {
- const f = fixture();
- const probe = new ManagedStartupDiagnostic(f.context);
- const result = await probe.run();
- assert.equal(result.passed, true);
- assert.equal(result.state, 'finished');
- assert.equal(result.stopped, true);
- assert.deepEqual(result.runtime, { version: 'v24.20.0', uid: 0, gid: 0 });
- assert.equal(f.container.settings.image, 'cloudflare/debian-trixie');
- assert.equal(f.container.settings.enableInternet, false);
- assert.equal(f.container.settings.instance, 'standard-2');
- assert.deepEqual(f.container.settings.entrypoint, ['sleep', 'infinity']);
- assert.deepEqual(f.container.command.slice(0, 2), ['/usr/local/bin/node', '--eval']);
- assert.equal(f.container.command.join(' ').includes('kiln'), false);
- assert.equal(f.calls.indexOf('alarm') < f.calls.indexOf('start'), true);
- assert.equal(f.container.running, false);
- assert.equal(f.alarmAt, undefined);
- for (const operation of ['start', 'exec', 'inspect', 'output', 'destroy', 'stopped']) {
- assert.ok(result.phases.some((p) => p.operation === operation && p.event === 'completed'));
- }
- assert.deepEqual(await probe.run(), result);
- assert.equal(f.calls.filter((x) => x === 'start').length, 1);
-});
-
-test('concurrent invocations cannot start another instance or change the fixed command', async () => {
- const f = fixture();
- await Promise.all([
- new ManagedStartupDiagnostic(f.context).run('untrusted command'),
- new ManagedStartupDiagnostic(f.context).run('new id'),
- ]);
- assert.equal(f.calls.filter((x) => x === 'start').length, 1);
- assert.equal(f.container.command.join(' ').includes('untrusted'), false);
-});
-
-test('missing binding and provider failure produce bounded metadata without private error text', async () => {
- for (const options of [
- { absent: true },
- { startFails: true },
- { execFails: true },
- { monitorFails: true },
- { monitorThrows: true },
- ]) {
- const f = fixture(options);
- const result = await new ManagedStartupDiagnostic(f.context).run();
- assert.equal(result.state, 'finished');
- assert.equal(result.passed, false);
- assert.equal(JSON.stringify(result).includes('private'), false);
- assert.equal(result.stopped, true);
- if (options.execFails) assert.equal(result.reason, 'EXEC_FAILED');
- if (options.monitorFails || options.monitorThrows) {
- assert.equal(result.reason, 'MONITOR_FAILED');
- assert.ok(
- result.phases.some(
- (p) => p.operation === 'monitor' && p.event === 'failed' && !p.duringCleanup,
- ),
- );
- }
- }
-});
-
-test('a monitor rejection caused by destruction is marked as cleanup, not startup failure', async () => {
- const f = fixture({ cleanupMonitorFails: true });
- const result = await new ManagedStartupDiagnostic(f.context).run();
- assert.equal(result.passed, true);
- assert.ok(
- result.phases.some((p) => p.operation === 'monitor' && p.event === 'failed' && p.duringCleanup),
- );
-});
-
-test('unexpected identity, process failure and output floods fail without retaining process output', async () => {
- for (const options of [
- { image: 'other-image' },
- { output: 'private process output' },
- { output: 'x'.repeat(1025) },
- { stderr: 'private stderr' },
- { exitCode: 2 },
- { output: JSON.stringify({ version: 'v22.23.3', uid: 0, gid: 0 }) },
- ]) {
- const f = fixture(options);
- const result = await new ManagedStartupDiagnostic(f.context).run();
- assert.equal(result.passed, false);
- assert.equal(result.stopped, true);
- assert.equal(JSON.stringify(result).includes('private'), false);
- assert.equal(f.container.running, false);
- }
-});
-
-test('failed cleanup retains a durable recovery alarm and never retries execution', async () => {
- const f = fixture({ cleanupFails: true });
- const result = await new ManagedStartupDiagnostic(f.context).run();
- assert.equal(result.passed, false);
- assert.equal(result.stopped, false);
- assert.equal(result.cleanupRequired, true);
- assert.ok(f.alarmAt > Date.now());
- f.repairCleanup();
- await new ManagedStartupDiagnostic(f.context).alarm();
- const recovered = await new ManagedStartupDiagnostic(f.context).run();
- assert.equal(recovered.passed, false);
- assert.equal(recovered.stopped, true);
- assert.equal(recovered.cleanupRequired, false);
- assert.equal(f.alarmAt, undefined);
- assert.equal(f.calls.filter((x) => x === 'start').length, 1);
-});
-
-test('deadline stops a hung command and a fresh controller can clean an interrupted claim', async (t) => {
- t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1_000_000 });
- const f = fixture({ hang: true });
- const pending = new ManagedStartupDiagnostic(f.context).run();
- while (!f.calls.includes('exec')) await new Promise((resolve) => setImmediate(resolve));
- t.mock.timers.tick(60_001);
- const result = await pending;
- assert.equal(result.reason, 'DEADLINE_EXCEEDED');
- assert.equal(result.stopped, true);
- assert.equal(f.container.running, false);
-
- const interrupted = fixture();
- interrupted.container.running = true;
- await interrupted.context.storage.put('startup', {
- state: 'running',
- passed: false,
- claimedAt: 1_000_000,
- deadlineAt: 1_060_000,
- phases: [],
- cleanupRequired: true,
- stopped: false,
- });
- await new ManagedStartupDiagnostic(interrupted.context).alarm();
- const retained = await new ManagedStartupDiagnostic(interrupted.context).run();
- assert.equal(retained.reason, 'DEADLINE_EXCEEDED');
- assert.equal(retained.stopped, true);
- assert.equal(interrupted.calls.includes('exec'), false);
-});
-
-test('cleanup itself is bounded and preserves recovery without granting a second invocation', async (t) => {
- t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 2_000_000 });
- const f = fixture({ cleanupHangs: true });
- const pending = new ManagedStartupDiagnostic(f.context).run();
- while (!f.calls.includes('destroy')) await new Promise((resolve) => setImmediate(resolve));
- t.mock.timers.tick(5_001);
- const result = await pending;
- assert.equal(result.passed, false);
- assert.equal(result.reason, 'CLEANUP_FAILED');
- assert.equal(result.cleanupRequired, true);
- assert.equal(result.stopped, false);
- assert.equal(f.alarmAt, Date.now() + 30_000);
- assert.deepEqual(await new ManagedStartupDiagnostic(f.context).run(), result);
- assert.equal(f.calls.filter((x) => x === 'start').length, 1);
-});
-
-test('configured control uses only a pinned Cloudflare image from its host binding', async () => {
- const image = `registry.cloudflare.com/${'a'.repeat(32)}/kiln-startup-control@sha256:${'b'.repeat(64)}`;
- const f = fixture({ images: { control: image } });
- const result = await new ManagedStartupDiagnostic(f.context, 'configured').run();
- assert.equal(result.passed, true);
- assert.equal(f.container.settings.image, image);
- assert.equal(f.container.settings.enableInternet, false);
- for (const invalid of [
- undefined,
- '',
- 'cloudflare/debian-trixie',
- 'node:24.20.0-trixie-slim',
- image.replace(/@sha256:.*/, ':latest'),
- ]) {
- const denied = fixture({ images: { control: invalid } });
- const failed = await new ManagedStartupDiagnostic(denied.context, 'configured').run();
- assert.equal(failed.reason, 'IMAGE_UNAVAILABLE');
- assert.equal(failed.passed, false);
- assert.equal(denied.calls.includes('start'), false);
- assert.equal(denied.calls.includes('exec'), false);
- }
-});
-
-test('configured control verifies the running image independently of the selected reference', async () => {
- const image = `registry.cloudflare.com/${'a'.repeat(32)}/kiln-startup-control@sha256:${'b'.repeat(64)}`;
- const f = fixture({ images: { control: image }, image: 'cloudflare/debian-trixie' });
- const result = await new ManagedStartupDiagnostic(f.context, 'configured').run();
- assert.equal(result.passed, false);
- assert.equal(result.reason, 'INSPECT_FAILED');
- assert.equal(result.stopped, true);
-});
-
-test('Kiln-image control selects its exact original image and numeric identity without importing Kiln', async () => {
- const image =
- 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a';
- const output = JSON.stringify({ version: 'v22.23.3', uid: 1000, gid: 1000 });
- const f = fixture({ images: { control: image }, output });
- const result = await new ManagedStartupDiagnostic(f.context, 'kiln').run();
- assert.equal(result.passed, true);
- assert.equal(f.container.settings.image, image);
- assert.equal(f.container.execSettings.user, '1000:1000');
- assert.deepEqual(f.container.command, [
- '/usr/local/bin/node',
- '--eval',
- 'process.stdout.write(JSON.stringify({version:process.version,uid:process.getuid(),gid:process.getgid()}))',
- ]);
- for (const runtime of [
- { version: 'v24.20.0', uid: 1000, gid: 1000 },
- { version: 'v22.23.3', uid: 0, gid: 0 },
- ]) {
- const mismatch = fixture({ images: { control: image }, output: JSON.stringify(runtime) });
- assert.equal(
- (await new ManagedStartupDiagnostic(mismatch.context, 'kiln').run()).reason,
- 'OUTPUT_FAILED',
- );
- }
- const substituted = fixture({
- images: { control: image.replace('69aff70b', 'ffffffff') },
- output,
- });
- assert.equal(
- (await new ManagedStartupDiagnostic(substituted.context, 'kiln').run()).reason,
- 'IMAGE_UNAVAILABLE',
- );
- assert.equal(substituted.calls.includes('start'), false);
-});
-
-test('Kiln platform-manifest control preserves runtime identity and rejects the original index', async () => {
- const image =
- 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8';
- const output = JSON.stringify({ version: 'v22.23.3', uid: 1000, gid: 1000 });
- const f = fixture({ images: { control: image }, output });
- const diagnostic = new ManagedStartupDiagnostic(f.context, 'kiln-manifest');
- const result = await diagnostic.run();
- assert.equal(result.passed, true);
- assert.equal(result.stopped, true);
- assert.equal(f.container.settings.image, image);
- assert.equal(f.container.execSettings.user, '1000:1000');
- assert.equal(f.container.settings.enableInternet, false);
- assert.deepEqual(await diagnostic.run(), result);
- assert.equal(f.calls.filter((call) => call === 'start').length, 1);
- for (const digest of [
- '69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a',
- 'a'.repeat(64),
- ]) {
- const mismatch = fixture({
- images: { control: image.replace(/sha256:.*/, `sha256:${digest}`) },
- output,
- });
- assert.equal(
- (await new ManagedStartupDiagnostic(mismatch.context, 'kiln-manifest').run()).reason,
- 'IMAGE_UNAVAILABLE',
- );
- assert.equal(mismatch.calls.includes('start'), false);
- }
- for (const runtime of [
- { version: 'v24.20.0', uid: 1000, gid: 1000 },
- { version: 'v22.23.3', uid: 0, gid: 0 },
- ]) {
- const mismatch = fixture({ images: { control: image }, output: JSON.stringify(runtime) });
- assert.equal(
- (await new ManagedStartupDiagnostic(mismatch.context, 'kiln-manifest').run()).reason,
- 'OUTPUT_FAILED',
- );
- }
-});
-
-for (const [entryFile, className, entrypoint] of [
- ['startup-worker.ts', 'KilnManagedStartupJob', 'KilnStartupControl'],
- ['custom-startup-worker.ts', 'KilnCustomStartupJob', 'KilnCustomStartupControl'],
- ['kiln-startup-worker.ts', 'KilnImageStartupJob', 'KilnImageStartupControl'],
- ['manifest-startup-worker.ts', 'KilnManifestStartupJob', 'KilnManifestStartupControl'],
-]) {
- test(`${entryFile} uses its private binding, denies HTTP and retains a missing-container result`, async () => {
- const bundle = await build({
- entryPoints: [fileURLToPath(new URL(`../probe/${entryFile}`, import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- const runtime = new Miniflare(
- convertV4MiniflareOptions({
- workers: [
- {
- name: 'diagnostic',
- modules: true,
- script: bundle.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- durableObjects: { STARTUP_JOB: { className, useSQLite: true } },
- },
- {
- name: 'operator',
- modules: true,
- compatibilityDate: '2026-10-06',
- serviceBindings: { DIAGNOSTIC: { name: 'diagnostic', entrypoint } },
- script: `export default {
- async fetch(request, env) {
- if (new URL(request.url).pathname === '/denied') return env.DIAGNOSTIC.fetch(request);
- return Response.json(await env.DIAGNOSTIC.runFixed());
- }
- }`,
- },
- ],
- }),
- );
- try {
- const diagnostic = await runtime.getWorker('diagnostic');
- assert.equal(
- (await diagnostic.fetch('http://localhost/run-fixed', { method: 'POST', body: '{}' }))
- .status,
- 404,
- );
- const operator = await runtime.getWorker('operator');
- assert.equal((await operator.fetch('http://localhost/denied')).status, 404);
- const first = await (await operator.fetch('http://localhost/run')).json();
- assert.equal(first.passed, false);
- assert.equal(first.reason, 'ISOLATION_UNAVAILABLE');
- assert.equal(first.stopped, true);
- assert.deepEqual(await (await operator.fetch('http://localhost/run')).json(), first);
- } finally {
- await runtime.dispose();
- }
- });
-}
diff --git a/hosting/test/storage-fault-worker.ts b/hosting/test/storage-fault-worker.ts
deleted file mode 100644
index 1bc8dfd5..00000000
--- a/hosting/test/storage-fault-worker.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { DurableObject } from 'cloudflare:workers';
-import { ArtifactStore } from '../src/artifact-store';
-import { serviceFailure } from '../src/http';
-
-// Never bundled for deployment. The real R2 binding is wrapped only to delay
-// acknowledgement or reject deletion, while SQLite inspection controls faults.
-export class StorageFaultFixture extends DurableObject<{ ARTIFACTS: R2Bucket }> {
- private readonly artifacts: ArtifactStore;
- private held = new Map<string, () => void>();
- private heldOnce = new Set<string>();
- constructor(ctx: DurableObjectState, env: { ARTIFACTS: R2Bucket }) {
- super(ctx, env);
- ctx.storage.sql.exec('CREATE TABLE IF NOT EXISTS faults (name TEXT PRIMARY KEY)');
- const fault = (name: string) =>
- ctx.storage.sql.exec('SELECT 1 FROM faults WHERE name = ?', name).toArray().length > 0;
- const hold = (name: string) => {
- this.heldOnce.add(name);
- return new Promise<void>((resolve) => this.held.set(name, resolve));
- };
- const heldOnce = this.heldOnce;
- const bucket = new Proxy(env.ARTIFACTS, {
- get(target, key) {
- if (key === 'put')
- return async (...args: Parameters<R2Bucket['put']>) => {
- if (fault('hold-put')) {
- // The provider has accepted the bytes, but its commit can arrive
- // after our request deadline. This test control never ships.
- args[1] = await new Response(args[1]).arrayBuffer();
- await hold('put');
- }
- const result = await target.put(...args);
- if (fault('slow-ack')) await new Promise((resolve) => setTimeout(resolve, 1500));
- return result;
- };
- if (key === 'list')
- return async (...args: Parameters<R2Bucket['list']>) => {
- const result = await target.list(...args);
- if (fault('hold-list') && !heldOnce.has('list')) await hold('list');
- return result;
- };
- if (key === 'delete')
- return async (...args: Parameters<R2Bucket['delete']>) => {
- if (fault('delete-failure')) throw new Error('Injected deletion failure');
- return target.delete(...args);
- };
- const value = Reflect.get(target, key);
- return typeof value === 'function' ? value.bind(target) : value;
- },
- });
- let fixtureClock = Date.now();
- this.artifacts = new ArtifactStore(
- ctx,
- bucket,
- { maxBytes: 1024 * 1024, maxObjects: 64, maxGroups: 8 },
- () =>
- fault('ticking-clock') ? ++fixtureClock : Date.now() + (fault('aged') ? 16 * 60 * 1000 : 0),
- 500,
- );
- }
- async alarm(): Promise<void> {
- await this.artifacts.sweep();
- }
- async fetch(request: Request): Promise<Response> {
- try {
- const path = new URL(request.url).pathname;
- if (path === '/held') return Response.json([...this.held.keys()]);
- if (path.startsWith('/release/')) {
- const name = path.slice('/release/'.length);
- this.held.get(name)?.();
- this.held.delete(name);
- return new Response('Released');
- }
- if (path === '/retire') return Response.json(await this.artifacts.retire());
- if (path === '/status')
- return Response.json({
- ...this.artifacts.retirementStatus(),
- alarm: await this.ctx.storage.getAlarm(),
- });
- if (path === '/run-alarm') {
- await this.alarm();
- return new Response('Alarm finished');
- }
- if (path === '/upload-short' || path === '/upload-large' || path === '/upload-negative') {
- const headers = new Headers(request.headers);
- headers.set(
- 'content-length',
- path === '/upload-short'
- ? '2'
- : path === '/upload-large'
- ? String(64 * 1024 * 1024 + 1)
- : '-1',
- );
- return Response.json(await this.artifacts.upload(new Request(request, { headers })), {
- status: 201,
- });
- }
- if (path === '/upload')
- return Response.json(await this.artifacts.upload(request), { status: 201 });
- if (path === '/sweep') return Response.json(await this.artifacts.sweep());
- if (path === '/usage') return Response.json(this.artifacts.usage());
- if (path.startsWith('/download/'))
- return await this.artifacts.download(path.slice('/download/'.length));
- return new Response('Not found', { status: 404 });
- } catch (error) {
- return serviceFailure(error);
- }
- }
-}
-export default { fetch: () => new Response('Not found', { status: 404 }) };
diff --git a/hosting/test/storage-fault.test.mjs b/hosting/test/storage-fault.test.mjs
deleted file mode 100644
index 30262fa2..00000000
--- a/hosting/test/storage-fault.test.mjs
+++ /dev/null
@@ -1,241 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash, randomBytes } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { setTimeout as delay } from 'node:timers/promises';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-let runtime;
-let namespace;
-before(async () => {
- const result = await build({
- entryPoints: [fileURLToPath(new URL('./storage-fault-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- name: 'faults',
- modules: true,
- script: result.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- r2Buckets: ['ARTIFACTS'],
- durableObjects: { TENANTS: { className: 'StorageFaultFixture', useSQLite: true } },
- outboundService: async () => {
- throw new Error('Unexpected network access');
- },
- }),
- unsafeInspectDurableObjects: true,
- });
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
-});
-after(async () => runtime?.dispose());
-const send = (owner, path, init) =>
- namespace.get(namespace.idFromName(owner)).fetch(`https://fixture.internal${path}`, init);
-async function database(owner) {
- await send(owner, '/usage');
- return runtime.unsafeGetDurableObjectStorage('faults', 'StorageFaultFixture', {
- id: namespace.idFromName(owner).toString(),
- });
-}
-const upload = (owner, path = '/upload') =>
- send(owner, path, {
- method: 'POST',
- body: 'durable',
- headers: {
- 'content-type': 'application/octet-stream',
- 'content-length': '7',
- 'x-artifact-name': 'asset.glb',
- 'x-artifact-sha256': createHash('sha256').update('durable').digest('hex'),
- },
- });
-const prefix = (owner) => `tenants/${namespace.idFromName(owner)}/artifacts/`;
-const status = async (owner) => (await send(owner, '/status')).json();
-async function until(predicate) {
- const deadline = Date.now() + 4000;
- while (!(await predicate())) {
- assert(Date.now() < deadline, 'Fixture did not reach the expected state');
- await delay(10);
- }
-}
-
-test('retirement waits for a late write and maintenance preserves its durable evidence', async () => {
- const owner = 'retire-late-put';
- const db = await database(owner);
- await db.exec("INSERT INTO faults VALUES ('hold-put')");
- const pending = upload(owner);
- try {
- await until(async () => (await (await send(owner, '/held')).json()).includes('put'));
- assert.equal((await pending).status, 502);
- assert.equal((await send(owner, '/sweep')).status, 200);
- assert.equal((await status(owner)).remainingObjects, 1, 'retain unresolved write metadata');
- const retired = await (await send(owner, '/retire')).json();
- assert.equal(retired.state, 'retiring');
- assert.equal(retired.pendingWrites, 1);
- assert.equal((await upload(owner)).status, 410);
- await send(owner, '/release/put');
- await until(async () => (await status(owner)).pendingWrites === 0);
- await send(owner, '/run-alarm');
- assert.deepEqual(await status(owner), {
- state: 'purged',
- pendingWrites: 0,
- remainingObjects: 0,
- alarm: null,
- });
- assert.equal(
- (await (await runtime.getR2Bucket('ARTIFACTS')).list({ prefix: prefix(owner) })).objects
- .length,
- 0,
- );
- } finally {
- await send(owner, '/release/put');
- await pending;
- }
-});
-
-test('failed retirement stays denied across eviction and retries deletion before clearing its alarm', async () => {
- const owner = 'retire-failed-delete';
- const db = await database(owner);
- const record = await (await upload(owner)).json();
- await db.exec("INSERT INTO faults VALUES ('delete-failure')");
- assert.equal((await send(owner, '/retire')).status, 503);
- assert.equal((await status(owner)).state, 'retiring');
- assert.equal((await status(owner)).remainingObjects, 1);
- assert.notEqual((await status(owner)).alarm, null);
- await runtime.unsafeEvictDurableObject('faults', 'StorageFaultFixture', {
- id: namespace.idFromName(owner).toString(),
- });
- assert.equal((await upload(owner)).status, 410);
- assert.equal((await send(owner, `/download/${record.id}`)).status, 404);
- await db.exec('DELETE FROM faults');
- assert.equal((await send(owner, '/run-alarm')).status, 200);
- assert.deepEqual(await status(owner), {
- state: 'purged',
- pendingWrites: 0,
- remainingObjects: 0,
- alarm: null,
- });
-});
-
-test('retirement recovers a lost put acknowledgement only from matching committed bytes', async () => {
- for (const committed of [false, true]) {
- const owner = `retire-lost-ack-${committed}`;
- const db = await database(owner);
- const record = await (await upload(owner)).json();
- await db.exec("UPDATE artifacts SET state='uploading',created_at=1");
- await db.exec('INSERT INTO artifact_writes VALUES (?)', record.id);
- if (!committed)
- await (await runtime.getR2Bucket('ARTIFACTS')).delete(prefix(owner) + record.id);
- await runtime.unsafeEvictDurableObject('faults', 'StorageFaultFixture', {
- id: namespace.idFromName(owner).toString(),
- });
- const result = await (await send(owner, '/retire')).json();
- assert.equal(result.state, committed ? 'purged' : 'retiring');
- assert.equal(result.pendingWrites, committed ? 0 : 1);
- assert.equal((await upload(owner)).status, 410);
- if (!committed) assert.notEqual((await status(owner)).alarm, null);
- }
-});
-
-test('an older maintenance pass cannot recreate metadata or alarms after retirement', async () => {
- const owner = 'retire-maintenance-race';
- const db = await database(owner);
- await db.exec("INSERT INTO faults VALUES ('hold-list')");
- const pending = send(owner, '/sweep');
- try {
- await until(async () => (await (await send(owner, '/held')).json()).includes('list'));
- assert.equal((await (await send(owner, '/retire')).json()).state, 'purged');
- await send(owner, '/release/list');
- assert.equal((await pending).status, 200);
- assert.equal((await db.exec('SELECT COUNT(*) AS n FROM maintenance'))[0].n, 0);
- assert.equal((await status(owner)).alarm, null);
- } finally {
- await send(owner, '/release/list');
- await pending;
- }
-});
-
-test('an unresolved write batch cannot indefinitely block retention of other expired files', async () => {
- const owner = 'retention-pending-batch';
- const db = await database(owner);
- const record = await (await upload(owner)).json();
- for (let i = 0; i < 32; i++) {
- const id = randomBytes(16).toString('hex');
- await db.exec(
- "INSERT INTO artifacts SELECT ?,?,sha256,bytes,filename,media_type,1,1,'uploading' FROM artifacts WHERE id=?",
- id,
- prefix(owner) + id,
- record.id,
- );
- await db.exec('INSERT INTO artifact_writes VALUES (?)', id);
- }
- await send(owner, '/sweep');
- await db.exec('UPDATE artifacts SET expires_at=1 WHERE id=?', record.id);
- assert.equal((await send(owner, '/sweep')).status, 200);
- assert.equal(
- await (await runtime.getR2Bucket('ARTIFACTS')).head(prefix(owner) + record.id),
- null,
- );
- assert.equal((await status(owner)).pendingWrites, 32);
- assert.equal((await status(owner)).remainingObjects, 32);
-});
-
-test('unsaved retention uses one creation instant even when the clock advances', async () => {
- const db = await database('retention-clock');
- await db.exec("INSERT INTO faults VALUES ('ticking-clock')");
- const result = await upload('retention-clock');
- assert.equal(result.status, 201);
- const record = await result.json();
- assert.equal(record.expiresAt - record.createdAt, 7 * 24 * 60 * 60 * 1000);
-});
-
-test('upload deadline includes R2 acknowledgement and retains failed-cleanup quota for retry', async () => {
- const db = await database('deadline');
- await db.exec("INSERT INTO faults VALUES ('slow-ack'), ('delete-failure')");
- const response = await upload('deadline');
- assert.equal(response.status, 502);
- const bucket = await runtime.getR2Bucket('ARTIFACTS');
- const objects = await bucket.list({ prefix: prefix('deadline') });
- assert.equal(objects.objects.length, 1);
- const id = objects.objects[0].key.slice(prefix('deadline').length);
- assert.equal((await send('deadline', `/download/${id}`)).status, 404);
- assert.equal((await (await send('deadline', '/usage')).json()).bytes, 7);
- assert.equal((await send('deadline', '/sweep')).status, 503);
- // Let the delayed R2 acknowledgement arrive. A timeout must not publish it.
- await delay(1600);
- assert.equal((await send('deadline', `/download/${id}`)).status, 404);
- assert.equal((await (await send('deadline', '/usage')).json()).bytes, 7);
- await db.exec('DELETE FROM faults');
- assert.equal((await send('deadline', '/sweep')).status, 200);
- assert.equal((await (await send('deadline', '/usage')).json()).bytes, 0);
- assert.equal((await bucket.list({ prefix: prefix('deadline') })).objects.length, 0);
-});
-
-test('recovery removes interrupted and aged orphan writes only within the tenant prefix', async () => {
- const db = await database('recover');
- const record = await (await upload('recover')).json();
- await db.exec("UPDATE artifacts SET state = 'uploading', created_at = 1");
- const bucket = await runtime.getR2Bucket('ARTIFACTS');
- const orphan = prefix('recover') + randomBytes(16).toString('hex');
- const foreign = prefix('other') + randomBytes(16).toString('hex');
- await bucket.put(orphan, 'orphan');
- await bucket.put(foreign, 'foreign');
- await db.exec("INSERT INTO faults VALUES ('aged')");
- assert.equal((await send('recover', '/sweep')).status, 200);
- assert.equal((await send('recover', `/download/${record.id}`)).status, 404);
- assert.equal((await (await send('recover', '/usage')).json()).bytes, 0);
- assert.equal((await bucket.list({ prefix: prefix('recover') })).objects.length, 0);
- assert.equal(await (await bucket.get(foreign)).text(), 'foreign');
-});
-
-test('declarations and actual stream length are checked independently of the HTTP client', async () => {
- assert.equal((await upload('length', '/upload-short')).status, 502);
- assert.equal((await upload('length', '/upload-large')).status, 400);
- assert.equal((await upload('length', '/upload-negative')).status, 400);
- await send('length', '/sweep');
- assert.equal((await (await send('length', '/usage')).json()).objects, 0);
-});
diff --git a/hosting/test/storage.test.mjs b/hosting/test/storage.test.mjs
deleted file mode 100644
index 95c7ff01..00000000
--- a/hosting/test/storage.test.mjs
+++ /dev/null
@@ -1,373 +0,0 @@
-import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-import { after, before, test } from 'node:test';
-import { build } from 'esbuild';
-import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
-
-let runtime;
-let namespace;
-const hash = (value) => createHash('sha256').update(value).digest('hex');
-before(async () => {
- const result = await build({
- entryPoints: [fileURLToPath(new URL('../src/tenant-worker.ts', import.meta.url))],
- bundle: true,
- write: false,
- format: 'esm',
- platform: 'browser',
- external: ['cloudflare:workers'],
- });
- runtime = new Miniflare({
- ...convertV4MiniflareOptions({
- name: 'tenant',
- modules: true,
- script: result.outputFiles[0].text,
- compatibilityDate: '2026-10-06',
- r2Buckets: ['ARTIFACTS'],
- durableObjects: { TENANTS: { className: 'KilnTenant', useSQLite: true } },
- bindings: {
- STORAGE_MAX_BYTES: '1048576',
- STORAGE_MAX_OBJECTS: '32',
- STORAGE_MAX_GROUPS: '8',
- },
- outboundService: async () => {
- throw new Error('Storage must not use outbound fetch');
- },
- }),
- unsafeInspectDurableObjects: true,
- });
- namespace = await runtime.getDurableObjectNamespace('TENANTS');
-});
-after(async () => runtime?.dispose());
-
-const tenant = (name) => namespace.get(namespace.idFromName(name));
-const send = (owner, path, init) => tenant(owner).fetch(`https://tenant.internal${path}`, init);
-async function upload(owner, bytes = Buffer.from('source bytes'), extra = {}) {
- const response = await send(owner, '/internal/artifacts', {
- method: 'POST',
- body: bytes,
- headers: {
- 'content-type': 'application/octet-stream',
- 'content-length': String(bytes.length),
- 'x-artifact-sha256': hash(bytes),
- 'x-artifact-name': 'asset.glb',
- ...extra,
- },
- });
- return { response, record: response.ok ? await response.json() : undefined };
-}
-const save = (owner, key, files, metadata = {}) =>
- send(owner, '/internal/groups', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ key, files, metadata }),
- });
-const get = (owner, id) => send(owner, `/mcp/artifacts/${id}`);
-const sweep = (owner) => send(owner, '/internal/maintenance', { method: 'POST' });
-const retire = (owner) => send(owner, '/internal/account-deletion', { method: 'POST' });
-const usage = async (owner) => (await send(owner, '/internal/usage')).json();
-
-test('account storage retirement erases saved and unsaved bytes while preserving another tenant', async () => {
- const owner = 'retire-account',
- other = 'retire-account-other';
- const saved = (await upload(owner)).record,
- unsaved = (await upload(owner, Buffer.from('unsaved'))).record;
- const foreign = (await upload(other)).record;
- assert.equal(
- (
- await save(
- owner,
- 'library/saved/revision',
- { 'asset.glb': saved.id },
- { name: 'Private title' },
- )
- ).status,
- 201,
- );
- const response = await retire(owner);
- assert.equal(response.status, 200);
- assert.equal((await response.json()).state, 'purged');
- for (const path of [
- '/internal/usage',
- '/internal/programs',
- `/mcp/artifacts/${saved.id}`,
- `/mcp/artifacts/${unsaved.id}`,
- ])
- assert.equal((await send(owner, path)).status, 410);
- assert.equal((await upload(owner)).response.status, 410);
- assert.equal(
- (await save(owner, 'library/recreate/revision', { 'asset.glb': saved.id })).status,
- 410,
- );
- const bucket = await runtime.getR2Bucket('ARTIFACTS');
- assert.equal(
- (await bucket.list({ prefix: `tenants/${namespace.idFromName(owner)}/artifacts/` })).objects
- .length,
- 0,
- );
- assert.equal((await get(other, foreign.id)).status, 200);
- const db = await database(owner);
- for (const table of ['saved_groups', 'group_files', 'artifacts', 'asset_download_tickets'])
- assert.equal((await db.exec(`SELECT COUNT(*) AS n FROM ${table}`))[0].n, 0);
- await runtime.unsafeEvictDurableObject('tenant', 'KilnTenant', {
- id: namespace.idFromName(owner).toString(),
- });
- assert.equal((await upload(owner)).response.status, 410);
- assert.equal((await (await retire(owner)).json()).state, 'purged');
-});
-
-test('retirement removes every orphan in bounded prefix-only batches', async () => {
- const owner = 'retire-orphans';
- await send(owner, '/internal/usage');
- const bucket = await runtime.getR2Bucket('ARTIFACTS');
- const prefix = `tenants/${namespace.idFromName(owner)}/artifacts/`;
- for (let i = 0; i < 105; i++) await bucket.put(`${prefix}orphan-${i}`, 'discard');
- const foreign = `tenants/${namespace.idFromName('retire-orphans-other')}/artifacts/other`;
- await bucket.put(foreign, 'keep');
- const first = await (await retire(owner)).json();
- assert.equal(first.state, 'retiring');
- assert.equal((await bucket.list({ prefix })).objects.length, 5);
- assert.equal((await (await retire(owner)).json()).state, 'purged');
- assert.equal(await (await bucket.get(foreign)).text(), 'keep');
-});
-
-test('storage retirement rejects identity selectors, bodies and unsupported methods before any mutation', async () => {
- const owner = 'retire-invalid';
- for (const init of [
- { method: 'GET' },
- { method: 'DELETE' },
- { method: 'POST', headers: { authorization: 'Bearer attacker' } },
- { method: 'POST', headers: { 'x-tenant-id': 'other' } },
- { method: 'POST', headers: { cookie: 'session=attacker' } },
- { method: 'POST', body: '{}' },
- ]) {
- assert.equal((await send(owner, '/internal/account-deletion', init)).status, 400);
- assert.equal((await send(owner, '/internal/usage')).status, 200);
- }
-});
-
-test('download ticket revocation commits in the same retirement transaction as the storage deny', async () => {
- const owner = 'retire-atomic-tickets';
- const record = (await upload(owner)).record;
- const group = await (await save(owner, 'saved/revision', { 'asset.glb': record.id })).json();
- const db = await database(owner);
- await db.exec(
- 'INSERT INTO asset_download_tickets VALUES (?,?,?,0)',
- 'synthetic-ticket',
- group.id,
- Date.now() + 600_000,
- );
- await db.exec(
- "CREATE TRIGGER retirement_fault BEFORE UPDATE ON artifacts BEGIN SELECT RAISE(ABORT,'injected'); END",
- );
- assert.equal((await retire(owner)).status, 503);
- assert.equal((await send(owner, '/internal/usage')).status, 200);
- assert.equal((await db.exec('SELECT COUNT(*) AS n FROM asset_download_tickets'))[0].n, 1);
- assert.equal((await get(owner, record.id)).status, 200);
- await db.exec('DROP TRIGGER retirement_fault');
- assert.equal((await (await retire(owner)).json()).state, 'purged');
- assert.equal((await db.exec('SELECT COUNT(*) AS n FROM asset_download_tickets'))[0].n, 0);
-});
-async function database(owner) {
- return runtime.unsafeGetDurableObjectStorage('tenant', 'KilnTenant', {
- id: namespace.idFromName(owner).toString(),
- });
-}
-
-test('private tenant worker has no public upload or download route', async () => {
- assert.equal(
- (
- await runtime.dispatchFetch('https://anything.example/internal/artifacts', {
- method: 'POST',
- body: 'data',
- })
- ).status,
- 404,
- );
- assert.equal(
- (
- await runtime.dispatchFetch('https://anything.example/internal/account-deletion', {
- method: 'POST',
- })
- ).status,
- 404,
- );
-});
-
-test('uploaded bytes are immutable, tenant-private and downloadable with exact metadata', async () => {
- const bytes = Buffer.from('function build() { return mesh; }');
- const { response, record } = await upload('bytes-alice', bytes, {
- 'x-artifact-name': 'source.kiln.js',
- });
- assert.equal(response.status, 201);
- assert.equal(record.sha256, hash(bytes));
- assert.equal(record.bytes, bytes.length);
- assert.equal(record.expiresAt - record.createdAt, 7 * 24 * 60 * 60 * 1000);
- const result = await get('bytes-alice', record.id);
- assert.equal(result.status, 200);
- assert.deepEqual(Buffer.from(await result.arrayBuffer()), bytes);
- assert.equal(result.headers.get('etag'), `"${hash(bytes)}"`);
- assert.match(result.headers.get('content-disposition'), /attachment; filename="source.kiln.js"/);
- assert.equal((await get('bytes-bob', record.id)).status, 404);
- assert.equal(
- (
- await tenant('bytes-alice').fetch(`https://tenant.internal/mcp/artifacts/${record.id}`, {
- method: 'PUT',
- body: 'overwrite',
- })
- ).status,
- 405,
- );
-});
-
-test('saving a revision pins all its bytes atomically and keeps the record immutable', async () => {
- const first = (await upload('save', Buffer.from('source'))).record;
- const second = (await upload('save', Buffer.from('GLB'))).record;
- const files = { 'source.kiln.js': first.id, 'asset.glb': second.id };
- const metadata = { engineVersion: '1.0.0-rc.1', parentRevision: null };
- const saved = await save('save', 'library/box/rev-1', files, metadata);
- assert.equal(saved.status, 201);
- const record = await saved.json();
- assert.deepEqual(record.files, files);
- assert.deepEqual(record.metadata, metadata);
- assert.equal((await save('save', 'library/box/rev-1', files, metadata)).status, 200);
- assert.equal((await save('save', 'library/box/rev-1', { 'asset.glb': second.id })).status, 409);
- const db = await database('save');
- await db.exec('UPDATE artifacts SET expires_at = 1');
- assert.equal((await sweep('save')).status, 200);
- assert.equal((await get('save', first.id)).status, 200);
- assert.equal((await get('save', second.id)).status, 200);
-});
-
-test('a failed cross-tenant save cannot partially pin a local artifact', async () => {
- const local = (await upload('pin-alice')).record;
- const foreign = (await upload('pin-bob')).record;
- assert.equal(
- (await save('pin-alice', 'asset/invalid/rev', { local: local.id, foreign: foreign.id })).status,
- 404,
- );
- const db = await database('pin-alice');
- await db.exec('UPDATE artifacts SET expires_at = 1');
- await sweep('pin-alice');
- assert.equal((await get('pin-alice', local.id)).status, 404);
- assert.equal((await get('pin-bob', foreign.id)).status, 200);
-});
-
-test('expired unsaved artifacts deny reads before cleanup and are removed from R2', async () => {
- const record = (await upload('expiry')).record;
- const db = await database('expiry');
- await db.exec('UPDATE artifacts SET expires_at = 1');
- assert.equal((await get('expiry', record.id)).status, 404);
- await sweep('expiry');
- assert.equal((await usage('expiry')).bytes, 0);
- const bucket = await runtime.getR2Bucket('ARTIFACTS');
- const objects = await bucket.list({ prefix: `tenants/${namespace.idFromName('expiry')}/` });
- assert.equal(objects.objects.length, 0);
-});
-
-test('concurrent uploads reserve quota before R2 work', async () => {
- const results = await Promise.all([
- upload('quota', Buffer.alloc(600_000, 1)),
- upload('quota', Buffer.alloc(600_000, 2)),
- ]);
- assert.deepEqual(results.map((result) => result.response.status).sort(), [201, 507]);
- assert.equal((await usage('quota')).bytes, 600_000);
-});
-
-test('checksum rejection does not publish a record or consume quota', async () => {
- const { response } = await upload('checksum', Buffer.from('different'), {
- 'x-artifact-sha256': '0'.repeat(64),
- });
- assert.equal(response.status, 502);
- await sweep('checksum');
- assert.equal((await usage('checksum')).bytes, 0);
-});
-
-test('deleting one revision preserves shared bytes; deleting its last owner removes them', async () => {
- const blob = (await upload('delete')).record;
- const a = await (await save('delete', 'asset/a/rev', { source: blob.id })).json();
- const b = await (await save('delete', 'asset/b/rev', { source: blob.id })).json();
- assert.equal(
- (await send('delete', `/internal/groups/${a.id}`, { method: 'DELETE' })).status,
- 200,
- );
- assert.equal((await get('delete', blob.id)).status, 200);
- assert.equal(
- (await send('delete-other', `/internal/groups/${b.id}`, { method: 'DELETE' })).status,
- 404,
- );
- assert.equal(
- (await send('delete', `/internal/groups/${b.id}`, { method: 'DELETE' })).status,
- 200,
- );
- assert.equal((await get('delete', blob.id)).status, 404);
- assert.equal((await usage('delete')).bytes, 0);
-});
-
-test('metadata and R2 bytes survive a Durable Object eviction', async () => {
- const blob = (await upload('restart', Buffer.from('retained'))).record;
- const id = namespace.idFromName('restart').toString();
- await runtime.unsafeEvictDurableObject('tenant', 'KilnTenant', { id });
- const response = await get('restart', blob.id);
- assert.equal(response.status, 200);
- assert.equal(await response.text(), 'retained');
-});
-
-test('download refuses corrupted or missing R2 bytes, including HEAD requests', async () => {
- const blob = (await upload('integrity', Buffer.from('original'))).record;
- const bucket = await runtime.getR2Bucket('ARTIFACTS');
- const key = `tenants/${namespace.idFromName('integrity')}/artifacts/${blob.id}`;
- await bucket.put(key, 'changed!');
- assert.equal((await get('integrity', blob.id)).status, 502);
- assert.equal(
- (await send('integrity', `/mcp/artifacts/${blob.id}`, { method: 'HEAD' })).status,
- 502,
- );
- await bucket.delete(key);
- assert.equal((await get('integrity', blob.id)).status, 502);
-});
-
-test('empty artifacts support HEAD and reject unsafe declarations before reserving quota', async () => {
- const blob = (await upload('empty', Buffer.alloc(0))).record;
- const head = await send('empty', `/mcp/artifacts/${blob.id}`, { method: 'HEAD' });
- assert.equal(head.status, 200);
- assert.equal(head.headers.get('content-length'), '0');
- assert.equal(await head.text(), '');
- for (const headers of [{ 'x-artifact-name': '../source.js' }, { 'content-type': 'text/html' }]) {
- assert.equal(
- (await upload('declarations', Buffer.from('bytes'), headers)).response.status,
- 400,
- );
- }
- assert.equal((await usage('declarations')).objects, 0);
-});
-
-test('object and saved-group counts prevent tiny-file quota bypass', async () => {
- const uploads = await Promise.all(
- Array.from({ length: 33 }, () => upload('object-count', Buffer.alloc(0))),
- );
- assert.equal(uploads.filter(({ response }) => response.status === 201).length, 32);
- assert.equal(uploads.filter(({ response }) => response.status === 507).length, 1);
- const id = uploads.find(({ record }) => record)?.record.id;
- for (let i = 0; i < 8; i++)
- assert.equal((await save('object-count', `revision/${i}`, { source: id })).status, 201);
- assert.equal((await save('object-count', 'revision/overflow', { source: id })).status, 507);
- assert.equal((await save('object-count', 'revision/0', { source: id })).status, 200);
- assert.equal((await usage('object-count')).groups, 8);
-});
-
-test('saved metadata consumes the same byte quota as artifacts without partial pinning', async () => {
- const blob = (await upload('metadata', Buffer.alloc(1048576 - 80))).record;
- const rejected = await save(
- 'metadata',
- 'large-metadata',
- { source: blob.id },
- { details: 'x'.repeat(100) },
- );
- assert.equal(rejected.status, 507);
- assert.equal((await usage('metadata')).groups, 0);
- const db = await database('metadata');
- await db.exec('UPDATE artifacts SET expires_at = 1');
- await sweep('metadata');
- assert.equal((await usage('metadata')).totalBytes, 0);
-});
diff --git a/hosting/test/worker.ts b/hosting/test/worker.ts
deleted file mode 100644
index 5bac2d0f..00000000
--- a/hosting/test/worker.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
-export { default } from '../src/worker';
-
-// This test-only backend records routing and transport data. It never evaluates
-// source or claims to implement the engine's MCP tools.
-export class TestTenant extends DurableObject {
- async fetch(request: Request): Promise<Response> {
- return Response.json({
- tenant: this.ctx.id.toString(),
- path: new URL(request.url).pathname,
- headers: Object.fromEntries(request.headers),
- body: request.method === 'POST' ? await request.text() : null,
- });
- }
-}
-
-// Auth tests observe routing only. Actual admission/compute has separate fixtures.
-export class TestCompute extends WorkerEntrypoint<{ TENANTS: DurableObjectNamespace }> {
- dispatch(tenant: string, request: Request): Promise<Response> {
- return this.env.TENANTS.getByName(tenant).fetch(request);
- }
-}
diff --git a/hosting/tsconfig.json b/hosting/tsconfig.json
deleted file mode 100644
index cb505152..00000000
--- a/hosting/tsconfig.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "ESNext",
- "moduleResolution": "Bundler",
- "lib": ["ES2022", "ESNext.Disposable"],
- "types": ["@cloudflare/workers-types"],
- "strict": true,
- "noEmit": true,
- "skipLibCheck": true,
- "noUncheckedIndexedAccess": true
- },
- "include": ["src/**/*.ts", "test/**/*.ts"],
- "exclude": ["src/native-*.ts"]
-}
diff --git a/hosting/tsconfig.native.json b/hosting/tsconfig.native.json
deleted file mode 100644
index 9fcf0d3a..00000000
--- a/hosting/tsconfig.native.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "lib": ["ES2022", "DOM", "DOM.Iterable"],
- "types": ["node"],
- "paths": {
- "@instruktlabs/kiln/assets": ["../lib/assets.d.ts"],
- "@instruktlabs/kiln/assets/node": ["../lib/assets-node.d.ts"],
- "@instruktlabs/kiln/material-library": ["../lib/material-library.d.ts"],
- "@instruktlabs/kiln/workspace": ["../lib/workspace.d.ts"],
- "@instruktlabs/kiln/material-library/node": ["../lib/material-library-node.d.ts"],
- "@instruktlabs/kiln/evaluator": ["../lib/evaluator/index.d.ts"],
- "@instruktlabs/kiln/tools": ["../lib/tools/registry.d.ts"],
- "@instruktlabs/kiln/composer": ["../lib/composer/index.d.ts"]
- }
- },
- "include": ["src/native-*.ts"],
- "exclude": []
-}
diff --git a/hosting/tsconfig.probe.json b/hosting/tsconfig.probe.json
deleted file mode 100644
index b4db479d..00000000
--- a/hosting/tsconfig.probe.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "include": ["probe/**/*.ts", "src/container-job.ts"],
- "exclude": []
-}
diff --git a/package.json b/package.json
index 1a1490f2..88c598d7 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@instruktlabs/kiln",
- "version": "1.0.0",
+ "version": "1.1.0-dev.1",
"description": "Create and refine procedural 3D assets with JavaScript, image feedback, and reusable source revisions.",
"license": "MIT",
"author": "Matthew Kissinger",
@@ -253,6 +253,9 @@
"plugins/kiln-engine/",
".mcp.json",
"scripts/create-workspace.mjs",
+ "scripts/workspace-config.mjs",
+ "scripts/workspace-project.mjs",
+ "scripts/workspace-transaction.mjs",
"scripts/package-plugin.mjs",
"render-service/src/",
"render-service/package.json",
@@ -327,10 +330,12 @@
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
+ "jsonc-parser": "3.3.1",
"manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
"sharp": "^0.35.5",
+ "smol-toml": "1.9.0",
"three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
diff --git a/plugin.json b/plugin.json
index 1b12986c..d2f0d09f 100644
--- a/plugin.json
+++ b/plugin.json
@@ -2,7 +2,7 @@
"name": "kiln",
"displayName": "Kiln",
"description": "Build and revise 3D assets with your coding agent. Write JavaScript, inspect selected views, edit saved source revisions, and export GLB files locally.",
- "version": "1.0.0",
+ "version": "1.1.0-dev.1",
"license": "MIT",
"homepage": "https://github.com/instruktlabs/kiln",
"keywords": [
diff --git a/plugins/kiln-engine.release.json b/plugins/kiln-engine.release.json
index 431dad8f..7f665a65 100644
--- a/plugins/kiln-engine.release.json
+++ b/plugins/kiln-engine.release.json
@@ -1,4 +1,4 @@
{
- "version": "1.0.1",
- "engineVersion": "1.0.0"
+ "version": "1.1.0-dev.1",
+ "engineVersion": "1.1.0-dev.1"
}
diff --git a/plugins/kiln-engine/.claude-plugin/plugin.json b/plugins/kiln-engine/.claude-plugin/plugin.json
index e364d499..c239e61c 100644
--- a/plugins/kiln-engine/.claude-plugin/plugin.json
+++ b/plugins/kiln-engine/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "kiln-engine",
- "version": "1.0.1",
+ "version": "1.1.0-dev.1",
"description": "Set up a local Kiln workspace to create, inspect and revise editable 3D assets with Claude Code or Codex.",
"author": {
"name": "Instrukt Labs",
diff --git a/plugins/kiln-engine/PRIVACY.md b/plugins/kiln-engine/PRIVACY.md
index 4fba8ceb..1fb29bf5 100644
--- a/plugins/kiln-engine/PRIVACY.md
+++ b/plugins/kiln-engine/PRIVACY.md
@@ -15,6 +15,14 @@ data directory outside the plugin cache. Paths can contain your device account
name; paths, package identity and file hashes appear in local configuration,
installation records and command results returned to your assistant.
+When adding Kiln to an existing project, setup reads the selected client's
+configuration and records ownership of Kiln's own entries. It preserves unrelated
+settings and existing project instructions. A recoverable setup transaction
+temporarily copies the affected files into private local recovery storage outside
+the project. Those copies can contain credentials already present in the client's
+configuration. They are not uploaded, printed or added to the workspace manifest.
+This storage uses filesystem permissions; Kiln does not encrypt these snapshots.
+
Your workspace and configured asset libraries hold authored JavaScript, material
files, asset names, metadata, previews and GLBs. Local tools read and write the
work you ask them to handle and return requested source, images and results to
@@ -60,6 +68,15 @@ remain until you delete them. Uninstalling the plugin removes neither your asset
nor its separately installed engine. Plugin updates also leave existing
workspaces on their installed engine until you request a managed upgrade.
+Setup removes recovery snapshots after a successful transaction or completed
+recovery. Interrupted setup can leave them until recovery succeeds or you resolve
+the interruption. The default location is
+`%LOCALAPPDATA%/InstruktLabs/Kiln/setup-transactions` on Windows, or
+`$XDG_DATA_HOME/instruktlabs/kiln/setup-transactions` elsewhere, falling back to
+`~/.local/share/instruktlabs/kiln/setup-transactions`. Use the setup helper's
+`--recover` operation before retrying an interrupted change. Do not upload recovery
+files to a public issue or delete them while setup or recovery is active.
+
There is no automatic seven-day expiry for local work; that is a separate hosted
service policy. Remove selected local work using Kiln's library controls or your
filesystem, and manage independent exports, backups, npm caches and assistant
diff --git a/plugins/kiln-engine/README.md b/plugins/kiln-engine/README.md
index 494f4131..a50eea65 100644
--- a/plugins/kiln-engine/README.md
+++ b/plugins/kiln-engine/README.md
@@ -1,9 +1,11 @@
# Kiln Engine local plugin
-Plugin version 1.0.1, maintained by Instrukt Labs under the MIT license.
-This plugin installs engine 1.0.0.
+**Development candidate.** This version is not published to npm. Qualification requires the reviewed local engine archive via `--archive`.
-Set up a persistent Kiln workspace for Claude Code or Codex, then create and revise
+Plugin version 1.1.0-dev.1, maintained by Instrukt Labs under the MIT license.
+This plugin installs engine 1.1.0-dev.1.
+
+Set up Kiln in an existing project or a new asset workspace, then create and revise
editable 3D assets with your coding agent. Use a supported Node.js installation
with npm. No Bun, engine checkout, Kiln account or separate model API key is needed.
The plugin requires a local shell and filesystem; Claude chat and Cowork are not
@@ -28,24 +30,34 @@ codex plugin add kiln-engine@instruktlabs
Restart or reload your coding agent's plugins as its installation message directs.
Then ask it to set up a Kiln workspace. The maintained setup skill runs this
plugin's `bin/kiln-setup-workspace.mjs` with Node, installs
-`@instruktlabs/[email protected]` and creates a separate asset workspace.
+`@instruktlabs/[email protected]` outside the project and configures your chosen
+workspace. The same initializer supports existing projects and new workspaces.
The plugin registers setup only. The workspace supplies authoring skills and one
-local MCP server, `kiln_workspace`. Open Claude Code in that workspace; launch
-Codex there with `node codex.mjs`. Follow `START.md`, accept the host's ordinary
-trust prompts and verify live tool discovery before authoring.
+local MCP server, `kiln_workspace`. Open Claude Code in that workspace or launch
+Codex there with `codex`. For headless Codex execution, use
+`node codex.mjs "TASK"` with an explicit prompt. Read `.kiln/START.md` after
+adoption or `START.md` in a legacy workspace, accept the host's ordinary trust
+prompts and verify live tool discovery before authoring.
-## Three setup examples
+## Setup examples
1. **Create:** “Set up a new Kiln workspace in an empty directory outside this
checkout, using my current coding agent. Verify its tools before I author an
asset.” The installer downloads the pinned engine when needed, creates the
selected workspace and keeps its engine in a separate runtime store. npm also
uses its normal cache and log directories.
-2. **Check:** “Check my existing Kiln workspace without changing it.” The helper's
+2. **Adopt:** “Add Kiln to this project without replacing my instructions or other
+ MCP settings. Show the planned changes first.” Use `--adopt --check` to
+ preview, then `--adopt` to apply. Read `.kiln/AGENTS.md` alongside the
+ project's instructions. Repeat with another supported `--harness` to add
+ that integration around the same saved assets. The engine's adapter list is
+ included in `runtime.json`; it does not imply this plugin can be installed
+ in every listed client. Published engine 1.0.0 does not support adoption.
+3. **Check:** “Check my existing Kiln workspace without changing it.” The helper's
`--check` mode reports whether managed files and the installed engine are
current. A missing runtime is reported without installing one.
-3. **Upgrade:** “Upgrade my managed Kiln workspace while preserving my sources,
+4. **Upgrade:** “Upgrade my managed Kiln workspace while preserving my sources,
saved assets and customizations.” Stop the workspace's harness session first.
The helper's `--upgrade` mode uses the pinned engine and refuses conflicts
rather than replacing customized managed files.
@@ -63,6 +75,13 @@ installer runs npm with lifecycle scripts disabled and invokes Kiln's workspace
generator. It does this before the workspace MCP server exists; it does not
silently install a global MCP server or grant itself shell permissions.
+Adoption and managed project updates temporarily keep recovery copies outside
+the project. Client configuration can already contain credentials, so these
+private copies may too. They are removed after successful setup or recovery;
+interrupted transactions retain them. See [local privacy](PRIVACY.md) for the
+storage location and protection limits. Use `--recover` before retrying an
+interrupted project update.
+
Marketplace installation and updates contact `https://github.com`. First engine
installation and dependency downloads use `https://registry.npmjs.org`. npm can
use your existing npm configuration and environment. No npm login or token is
diff --git a/plugins/kiln-engine/bin/kiln-setup-workspace.mjs b/plugins/kiln-engine/bin/kiln-setup-workspace.mjs
index c8386a00..a8b1b789 100755
--- a/plugins/kiln-engine/bin/kiln-setup-workspace.mjs
+++ b/plugins/kiln-engine/bin/kiln-setup-workspace.mjs
@@ -232,14 +232,15 @@ async function installRuntime(data, pin, archive, archiveHash, options) {
export async function setupPluginWorkspace(options = {}) {
const harness = options.harness || 'claude';
- if (!['claude', 'codex'].includes(harness)) throw new Error('Choose harness claude or codex.');
const mode = options.mode || 'create';
- if (!['create', 'check', 'upgrade', 'repair'].includes(mode))
+ if (!['create', 'check', 'upgrade', 'repair', 'recover'].includes(mode))
throw new Error('Unknown workspace setup mode.');
+ if (mode === 'recover' && (options.adopt || options.skills))
+ throw new Error('Use --recover alone before retrying setup.');
if (!options.directory) throw new Error('Provide a workspace directory.');
if (
options.skills &&
- (mode !== 'create' ||
+ ((mode !== 'create' && !(mode === 'check' && options.adopt)) ||
!Array.isArray(options.skills) ||
options.skills.some((name) => !['compose', 'batch'].includes(name)))
)
@@ -251,6 +252,18 @@ export async function setupPluginWorkspace(options = {}) {
if (pin.name !== packageName) throw new Error(`The plugin must pin package ${packageName}.`);
if (typeof pin.version !== 'string' || !exactVersion.test(pin.version))
throw new Error('The plugin runtime needs an exact stable, rc.N or dev.N version.');
+ // New bundles derive adapters from their pinned engine's initializer. Keep the
+ // original two-client contract for older bundles that have no capability list.
+ const harnesses = pin.harnesses === undefined ? ['claude', 'codex'] : pin.harnesses;
+ if (
+ !Array.isArray(harnesses) ||
+ !harnesses.length ||
+ harnesses.some((name) => typeof name !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(name)) ||
+ new Set(harnesses).size !== harnesses.length
+ )
+ throw new Error('Invalid workspace harness capabilities in the plugin runtime pin.');
+ if (!harnesses.includes(harness))
+ throw new Error(`Choose a supported workspace harness: ${harnesses.join(', ')}.`);
const directory = await canonical(options.directory);
const data = await canonical(options.dataDirectory || defaultDataDirectory());
for (const [a, b] of [
@@ -260,7 +273,7 @@ export async function setupPluginWorkspace(options = {}) {
])
if (inside(a, b) || inside(b, a))
throw new Error('Keep workspace, runtime data and plugin cache in separate directories.');
- if (mode === 'create' && (await exists(directory))) {
+ if (mode === 'create' && !options.adopt && (await exists(directory))) {
if (!(await lstat(directory)).isDirectory() || (await readdir(directory)).length)
throw new Error(
'The workspace destination must be an empty directory; no existing files were changed.',
@@ -273,13 +286,22 @@ export async function setupPluginWorkspace(options = {}) {
{ name: pin.name, version: pin.version },
archive,
archiveHash,
- { ...options, mode },
+ { ...options, mode: mode === 'recover' ? 'check' : mode },
);
- const { createWorkspace } = await import(
+ const { createWorkspace, workspaceSetupCapabilities } = await import(
pathToFileURL(join(runtime, 'scripts/create-workspace.mjs')).href
);
+ if (options.adopt && workspaceSetupCapabilities?.projectAdoption !== 1)
+ throw new Error(
+ 'The pinned engine does not support project adoption. Use a plugin release that pins a supporting engine; no project files were changed.',
+ );
+ if (mode === 'recover' && workspaceSetupCapabilities?.recovery !== 1)
+ throw new Error(
+ 'The pinned engine does not support project recovery. No project files were changed.',
+ );
const workspace = await createWorkspace(directory, harness, {
installation: runtime,
+ ...(options.adopt ? { adopt: true } : {}),
...(mode === 'create' ? {} : { [mode]: true }),
...(options.skills ? { skills: options.skills } : {}),
});
@@ -302,9 +324,13 @@ export function parseSetupArguments(args) {
};
while (values.length) {
const flag = values.shift();
- if (['--check', '--upgrade', '--repair'].includes(flag)) {
- if (result.mode) throw new Error('Choose only one of --check, --upgrade or --repair.');
+ if (['--check', '--upgrade', '--repair', '--recover'].includes(flag)) {
+ if (result.mode)
+ throw new Error('Choose only one of --check, --upgrade, --repair or --recover.');
result.mode = flag.slice(2);
+ } else if (flag === '--adopt') {
+ if (result.adopt) throw new Error('Repeated option --adopt.');
+ result.adopt = true;
} else if (Object.hasOwn(valueFlags, flag)) {
const value = values.shift();
if (!value || value.startsWith('--')) throw new Error(`Missing value for ${flag}.`);
@@ -312,6 +338,8 @@ export function parseSetupArguments(args) {
result[valueFlags[flag]] = flag === '--skills' ? value.split(',') : value;
} else throw new Error(`Unknown option ${flag}.`);
}
+ if (result.mode === 'recover' && (result.adopt || result.skills))
+ throw new Error('Use --recover alone before retrying setup.');
return result;
}
@@ -323,7 +351,7 @@ if (
const options = parseSetupArguments(process.argv.slice(2));
if (options.help)
console.log(
- 'Usage: node bin/kiln-setup-workspace.mjs <directory> [--harness claude|codex] [--skills compose,batch]\n node bin/kiln-setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>',
+ 'Usage: node bin/kiln-setup-workspace.mjs <directory> [--harness NAME] [--skills compose,batch]\n node bin/kiln-setup-workspace.mjs <project-or-new-workspace> --adopt [--check]\n node bin/kiln-setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair|--recover\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>\nWorkspace adapters are declared by the pinned engine in runtime.json.',
);
else {
const result = await setupPluginWorkspace(options);
diff --git a/plugins/kiln-engine/package-provenance.json b/plugins/kiln-engine/package-provenance.json
index ef2cc81f..b28d0ff4 100644
--- a/plugins/kiln-engine/package-provenance.json
+++ b/plugins/kiln-engine/package-provenance.json
@@ -1,21 +1,22 @@
{
"schemaVersion": 1,
"kind": "kiln-local-plugin",
- "pluginVersion": "1.0.1",
- "engineVersion": "1.0.0",
+ "pluginVersion": "1.1.0-dev.1",
+ "engineVersion": "1.1.0-dev.1",
"executables": [
"bin/kiln-setup-workspace.mjs"
],
"files": {
".claude-plugin/icon.png": "sha256:b4b651c402793b7e27cab780f04b14f80daec6d0cd5b7e4e90313930581a54e9",
- ".claude-plugin/plugin.json": "sha256:1c9a759df304878ca9b730b1c317fea48f07840e4cc38ae68b2a9d5a6670f8b4",
- "bin/kiln-setup-workspace.mjs": "sha256:31cd8c0b1028b8df487b7b333655d0dd5e456ae8d7dcadad687557dd3202cf3e",
+ ".claude-plugin/plugin.json": "sha256:db990218cbc1a73c3d4bc2ac927980fc8ae58c6cf35f959d972101d1a80247ba",
+ "bin/kiln-setup-workspace.mjs": "sha256:3d9a30236919a6ca91acb6b26f808cec442e6edc3dd88fe010645b010d76e838",
"LICENSE": "sha256:cdba278ebf1d6de618869936226bf03be4887179c128efc7aaa13d22034826a5",
- "plugin.json": "sha256:a877b48b4ddad084cc8ddffd819a7f091bd00991306f62753e5576a034490b2b",
- "PRIVACY.md": "sha256:4bd5eb34e9a936a2356aca8633c0f1bceeccb320b161dd47abbe608170fd2cd4",
- "README.md": "sha256:c71f9b9c2dd7cb56b87ca4dce454de128e3da8812b27d06275a7d4db35b5d689",
- "runtime.json": "sha256:18129a1d310c468aeba0966792940242f0359ab14c41a4c9ef240310d07d3bd2",
- "skills/kiln-setup-workspace/references/plugin-install.md": "sha256:a8e1758d851b8d52f3b9266c27be05d25134f10257501f8d8c7429e8687935e2",
- "skills/kiln-setup-workspace/SKILL.md": "sha256:7101b92d34c478e63d4cd96183cfebd383c7134883ab758a2c93d883f7066c5b"
+ "plugin.json": "sha256:3d55aab0e160cc067c78b3a4757a7973e03e6e1b716f1ecdec189b3133a30fef",
+ "PRIVACY.md": "sha256:5f58d981667e40441e21c2dec411f269a9a67a6141cec61976d27088fb12573b",
+ "README.md": "sha256:64a6b0f1ef5665ecad019930eda09903deaf8ad74b58c361b57c509f1084acd4",
+ "runtime.json": "sha256:2b93480e54e9b662893bfa9a7f90ee8dd80364fbde982fe4e8244960ffaac19e",
+ "skills/kiln-setup-workspace/references/plugin-install.md": "sha256:c338fb792e7fad0364c3e1a13c94c506afa1395489ec1b6e83b36d04728935fb",
+ "skills/kiln-setup-workspace/references/renderer-setup.md": "sha256:b743b1b2827fa814385990e1e5b849391cb427413e9c016d273aa19cebd46031",
+ "skills/kiln-setup-workspace/SKILL.md": "sha256:041e4fe55e80c72133dabb6d25be78cfc0aae45edc057eca3c7a5a1c8db0fef1"
}
}
diff --git a/plugins/kiln-engine/plugin.json b/plugins/kiln-engine/plugin.json
index 48fbd22f..2b7bcc4f 100644
--- a/plugins/kiln-engine/plugin.json
+++ b/plugins/kiln-engine/plugin.json
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "kiln-engine",
- "version": "1.0.1",
+ "version": "1.1.0-dev.1",
"description": "Set up a local Kiln workspace to create, inspect and revise editable 3D assets with Claude Code or Codex.",
"author": {
"name": "Instrukt Labs",
diff --git a/plugins/kiln-engine/runtime.json b/plugins/kiln-engine/runtime.json
index bf2c958a..e4cb80ba 100644
--- a/plugins/kiln-engine/runtime.json
+++ b/plugins/kiln-engine/runtime.json
@@ -1,4 +1,13 @@
{
"name": "@instruktlabs/kiln",
- "version": "1.0.0"
+ "version": "1.1.0-dev.1",
+ "harnesses": [
+ "claude",
+ "codex",
+ "opencode",
+ "hermes",
+ "agy",
+ "copilot",
+ "cursor-agent"
+ ]
}
diff --git a/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md b/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md
index b1e637f9..3f6efd58 100644
--- a/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md
+++ b/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md
@@ -1,6 +1,6 @@
---
name: kiln-setup-workspace
-description: Create and verify a Kiln asset workspace for a chosen coding-agent harness. Use before authoring when the current directory is the engine repository, an empty folder, or any project without a working kiln_workspace server.
+description: Configure and verify Kiln in an existing project or a new asset workspace for the selected coding agent. Use before authoring when the project has no working kiln_workspace server or needs another agent integration; engine development stays in the engine checkout.
license: MIT
metadata:
kiln-workflow: workspace
@@ -20,13 +20,16 @@ Do not author assets inside the engine checkout. The authoring skills assume a w
When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `bin/kiln-setup-workspace.mjs` (plugin 1.0.0 used `scripts/setup-workspace.mjs`). Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.
-Choose an absolute path to an empty directory outside the checkout.
+Choose the user's existing project or an absolute path for a new workspace outside the engine installation. Check the installed initializer's `--help`: this setup version supports `--adopt`; older engines support only empty destinations. Upgrade an older installation explicitly before adopting a populated project.
```bash
-node scripts/create-workspace.mjs /absolute/empty-workspace --harness claude
+node scripts/create-workspace.mjs /absolute/project --adopt --harness claude --check
+node scripts/create-workspace.mjs /absolute/project --adopt --harness claude
```
-From an installed package, the equivalent is `kiln-init /absolute/empty-workspace --harness claude`. Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional scene-composition and trial-dispatch workflows. Use the harness already selected by the user or current host; ask only when it is unknown. The choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+From an installed package, use `kiln-init` with the same arguments. Check reports planned changes and exits 1 when changes are needed; it writes nothing. Adoption preserves existing instruction files, unrelated settings, assets and skills. Read the returned `instructions` file (`.kiln/AGENTS.md`) and `.kiln/START.md`, alongside the project's existing instructions. Conflicts stop setup before writes; do not delete or replace owner configuration to make the command pass.
+
+Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional workflows. Use the agent selected by the user or current host; ask only when it is unknown. Repeat `--adopt --harness codex` (or another supported adapter) to add that integration around the same program store. It explicitly migrates a legacy managed workspace while preserving assets. A combination whose config formats conflict is reported before changes; do not force one client's configuration into another. The plain empty-directory setup command remains compatible with older workflows.
CLI/MCP workspaces use the shared skills under `skills/`. Kiln's optional built-in Strands agent adds its workflow internally, outside that directory. Do not copy its system prompt, native workflow skill or completion protocol into another harness's skills or instructions. This applies to manual setup and plugin installs too; the engine's `src/agent/` directory is not a skill source.
@@ -37,24 +40,18 @@ CLI/MCP workspaces use the shared skills under `skills/`. Kiln's optional built-
| `cursor-agent` | `cursor-agent` |
| `opencode` | `opencode` |
| `agy` | `node agy.mjs` |
-| `codex` | `node codex.mjs` |
+| `codex` | `codex` after project trust; `node codex.mjs "TASK"` for a headless run |
| `hermes` | `node hermes.mjs` |
-**Use the launcher where the table names one, and read the workspace's own START.md over this table.** Antigravity, Codex and Hermes keep all configuration in a user-level home and read nothing from a project directory, so their workspace configuration is applied per invocation by the generated launcher. Running their bare command inside the workspace reaches no Kiln tools at all. None of the three writes outside the workspace, and none touches the user's existing configuration or authentication.
+Read `.kiln/START.md` for an adopted project, or `START.md` in a legacy workspace. Codex reads trusted project configuration from `.codex/config.toml`; its optional headless launcher supplies the same settings per invocation without relocating authentication. Antigravity and Hermes use their generated launchers for the measured workspace flow. Setup does not grant project trust or edit global credentials. Skill registration is client-specific: Claude uses `.claude/skills`, Codex uses `.agents/skills`, and OpenCode uses its configured skills path, all copied from the same maintained Kiln skills.
Hermes needs one user-level registration for the MCP server, because it has no project-scoped equivalent and no per-invocation flag for one. Its START.md prints the exact `hermes mcp add` command; offer to run it, and verify with `hermes mcp list`. Never redirect `HERMES_HOME` at the workspace: that one variable resolves the configuration path and the credential path together, so pointing it at a workspace leaves the run with no provider.
-## Start the GPU render service
-
-Setup asks for render mode `auto`: textured or metallic scenes use a compatible GPU service, starting one lazily when available. Ordinary untextured scenes with zero metalness and no advanced material extensions use CPU views, even with a GPU available. CPU views support silhouette, proportion and contact review, but cannot confirm PBR appearance. Use CLI `--render gpu` when material review is required, including roughness on nonmetallic surfaces.
-
-The renderer code is included with Kiln; its native GPU dependency is optional at the Kiln package root. For material-dependent tasks, check `node kiln.mjs service status` before starting the authoring session. If dependencies are missing or incompatible, reinstall the official Kiln package with optional dependencies enabled. npm 11 may print an `install-scripts` warning for the optional `webgpu` package; its postinstall only clears the macOS download quarantine from the prebuilt Dawn binary the package ships, so Windows and Linux need nothing and the warning is not an install failure. Read `runtime` from `.kiln/workspace.json` to identify the installation. A source checkout uses `bun install --frozen-lockfile` at that root. Setup checks dependency resolution without loading native code; ready dependencies alone do not prove the device can render.
+## Check rendering readiness
-Once dependencies are available, local CLI/MCP auto mode starts a managed service lazily for a view that needs PBR shading. Compatible clients share it; it survives the initiating session and exits after five minutes without admitted uploads, queued jobs or active renders. From the installation root, `node --import ./render-service/src/register-hooks.mjs render-service/src/server.mjs` starts a manual service that remains running while idle. It binds loopback; widening `HOST` requires `RENDER_SERVICE_TOKEN`.
+Setup selects render mode `auto`. Textured or metallic scenes use a compatible render service; plain scenes use CPU geometry views. CPU views cannot confirm PBR appearance. Check `node kiln.mjs service status` before material-dependent work and require a real `viewFidelity` result before claiming material evidence.
-`node kiln.mjs service status` reports installation, verified health and lifetime. `node kiln.mjs service start` joins a compatible service or starts a managed one the way an on-demand view does, and prints its port, renderer, pid, lifetime and build; it starts nothing when a stale, foreign or unknown listener holds the socket. After dependency repair or a cached startup failure, call `kiln_renderer({action:"reprobe"})` inside the MCP session to refresh its existing route. It neither installs dependencies nor starts a renderer; the next view starts one if needed. CLI `service reprobe` checks only its own process. Restart the session after changing Kiln, environment variables or credentials. Unknown or incompatible listeners are reported and left alone. `service stop` explicitly stops a verified local service. If no usable GPU is available, report the material-review limitation and continue on CPU views when that fits the task.
-
-A `KILN_RENDER_PORT_URL` whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) takes the local route: it starts on demand and restarts after an idle exit. For rendering on another device, configure the MCP server process's `KILN_RENDER_PORT_URL` and, when needed, `KILN_RENDER_TOKEN` through the chosen harness. CLI accepts `--render-port URL` and reads `KILN_RENDER_TOKEN`. Start a compatible Kiln renderer on that device; its wider bind requires `RENDER_SERVICE_TOKEN` unless an authenticated proxy is explicitly configured. Manage the remote service on its own device. Verify the selected route with capabilities and require an actual `viewFidelity` receipt for material evidence.
+Read [local renderer setup](references/renderer-setup.md) when dependencies are missing, a service is unavailable, or the task uses a renderer on another device. It covers dependency repair, shared-service lifetime, reprobe and authenticated remote rendering. Do not replace an unknown listener or install dependencies merely to clear a diagnostic.
## Verify the loadout before authoring
@@ -97,7 +94,9 @@ node /current/kiln/scripts/create-workspace.mjs /absolute/empty-workspace --repa
Repair rewrites generated runtime paths only. It preserves copied skills, saved revisions and assets, refuses configuration that was edited by hand, and does not upgrade the skills.
-For an existing workspace, stop its harness/MCP session and run setup from the desired installation with `--check`, then `--upgrade`. Check returns JSON and exits 1 when an update is required. Upgrade refreshes unchanged configuration, instructions and all registered skill copies while preserving assets and source stores. Conflicting local edits stop the whole upgrade before writing. Older instruction files without ownership hashes also require explicit resolution: preserve them separately, compare against a fresh temporary workspace, then move them aside or supply the current version before retrying. Reapply compatible customizations after upgrading. Do not overwrite an edited file merely to clear a conflict.
+For an existing workspace, stop its harness/MCP session and run setup from the desired installation with `--check`, then `--upgrade`. Check returns JSON and exits 1 when an update is required. Upgrade refreshes unchanged owned configuration, instructions and registered skill copies while preserving assets and source stores. Conflicting local edits stop the whole upgrade before writing. Adopted projects preserve unrelated configuration changes and leave pre-existing instruction files alone. Legacy instruction files without ownership hashes can require explicit resolution; preserve them before resolving the named conflict. Do not overwrite an edited file merely to clear a diagnostic.
+
+If adopted-project setup stops partway through writing, it attempts rollback. When it reports recovery required, preserve the project and run `kiln-init /absolute/project --recover` after confirming setup has stopped. Recovery refuses conflicting edits and retains its private snapshots outside the project. Resolve named conflicts explicitly; do not delete a lock or journal to force another setup. Recovery is for interrupted setup, not a general asset backup.
New managed launchers reject runtime/skill mismatches before serving tools; older workspaces need this explicit check first. Restart the harness/MCP session after upgrading so cached tool schemas and instructions match. `--repair` alone does not refresh copied skills or a running session. For independent model evaluations, create a fresh workspace from the candidate.
@@ -105,4 +104,4 @@ Discovery replaces the removed `kiln_list_primitives` tool; its old `name`, `nam
## What isolation means
-A separate workspace limits task context. It is not an operating-system sandbox, and it is not a git repository. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md` in the engine checkout, which covers recording inherited context and reporting trials.
+A separate workspace limits task context; an adopted project retains its existing application context and Git repository. Neither is an operating-system sandbox. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, use a fresh workspace and read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md`, which covers inherited context and reporting trials.
diff --git a/plugins/kiln-engine/skills/kiln-setup-workspace/references/plugin-install.md b/plugins/kiln-engine/skills/kiln-setup-workspace/references/plugin-install.md
index c3f933f7..5050fcca 100644
--- a/plugins/kiln-engine/skills/kiln-setup-workspace/references/plugin-install.md
+++ b/plugins/kiln-engine/skills/kiln-setup-workspace/references/plugin-install.md
@@ -17,8 +17,11 @@ installation, confirm and use that file instead. Plugin and engine versions are
independent. `runtime.json` always names the exact engine to install.
For a fresh workspace, use an absolute empty destination outside both the plugin
-and its runtime data directory. Select `claude` or `codex` from the current host
-or the user's stated choice:
+and its runtime data directory. Select the current host or the user's stated
+adapter. New bundles list the engine's supported adapters in `runtime.json`;
+older bundles without that list accept `claude` or `codex` only. The plugin itself
+is installed in Claude Code or Codex, but its helper can configure another adapter
+supported by the pinned engine:
```sh
node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --harness codex
@@ -32,11 +35,23 @@ or `$XDG_DATA_HOME/instruktlabs/kiln` on other systems, falling back to
Do not place it or the asset workspace inside a removable plugin version directory.
Read the returned workspace's `START.md`. Open Claude Code in that workspace, or
-launch Codex there with `node codex.mjs`. Accept the host's ordinary project/MCP
+launch Codex there with `codex`. The `node codex.mjs "TASK"` launcher is for
+headless execution with an explicit prompt. Accept the host's ordinary project/MCP
trust prompts, then call `kiln_discover({capabilities:true})` on `kiln_workspace`.
Compare its installation identity to `.kiln/workspace.json`; a config file alone
does not prove the server loaded. The plugin itself starts no global MCP server.
+For an existing project, use a plugin whose helper advertises `--adopt` and whose
+pinned engine supports project adoption. The published engine 1.0.0 predates this
+feature. The helper checks the engine capability and refuses unsupported adoption
+instead of silently falling back to empty-folder setup. Preview with
+`--adopt --check --harness codex`, then apply with `--adopt --harness codex`.
+Use the same path with another `--harness` to add an integration around the same
+assets. Read the returned `instructions` path and `.kiln/START.md`; existing project
+instruction files remain intact. The helper still leaves normal client trust
+prompts to the host. No manual changes to a plugin's runtime pin are needed or
+appropriate.
+
If the current workspace already has a working `kiln_workspace`, keep it. Do not
create a second server. Use its installed authoring skills, which come from its
engine version. The plugin supplies only setup, so authoring instructions are not
diff --git a/plugins/kiln-engine/skills/kiln-setup-workspace/references/renderer-setup.md b/plugins/kiln-engine/skills/kiln-setup-workspace/references/renderer-setup.md
new file mode 100644
index 00000000..8cdd06cd
--- /dev/null
+++ b/plugins/kiln-engine/skills/kiln-setup-workspace/references/renderer-setup.md
@@ -0,0 +1,11 @@
+# Local renderer setup
+
+Setup asks for render mode `auto`: textured or metallic scenes use a compatible GPU service, starting one lazily when available. Ordinary untextured scenes with zero metalness and no advanced material extensions use CPU views, even with a GPU available. CPU views support silhouette, proportion and contact review, but cannot confirm PBR appearance. Use CLI `--render gpu` when material review is required, including roughness on nonmetallic surfaces.
+
+The renderer code is included with Kiln; its native GPU dependency is optional at the Kiln package root. For material-dependent tasks, check `node kiln.mjs service status` before starting the authoring session. If dependencies are missing or incompatible, reinstall the official Kiln package with optional dependencies enabled. npm 11 may print an `install-scripts` warning for the optional `webgpu` package; its postinstall only clears the macOS download quarantine from the prebuilt Dawn binary the package ships, so Windows and Linux need nothing and the warning is not an install failure. Read `runtime` from `.kiln/workspace.json` to identify the installation. A source checkout uses `bun install --frozen-lockfile` at that root. Setup checks dependency resolution without loading native code; ready dependencies alone do not prove the device can render.
+
+Once dependencies are available, local CLI/MCP auto mode starts a managed service lazily for a view that needs PBR shading. Compatible clients share it; it survives the initiating session and exits after five minutes without admitted uploads, queued jobs or active renders. From the installation root, `node --import ./render-service/src/register-hooks.mjs render-service/src/server.mjs` starts a manual service that remains running while idle. It binds loopback; widening `HOST` requires `RENDER_SERVICE_TOKEN`.
+
+`node kiln.mjs service status` reports installation, verified health and lifetime. `node kiln.mjs service start` joins a compatible service or starts a managed one the way an on-demand view does, and prints its port, renderer, pid, lifetime and build; it starts nothing when a stale, foreign or unknown listener holds the socket. After dependency repair or a cached startup failure, call `kiln_renderer({action:"reprobe"})` inside the MCP session to refresh its existing route. It neither installs dependencies nor starts a renderer; the next view starts one if needed. CLI `service reprobe` checks only its own process. Restart the session after changing Kiln, environment variables or credentials. Unknown or incompatible listeners are reported and left alone. `service stop` explicitly stops a verified local service. If no usable GPU is available, report the material-review limitation and continue on CPU views when that fits the task.
+
+A `KILN_RENDER_PORT_URL` whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) takes the local route: it starts on demand and restarts after an idle exit. For rendering on another device, configure the MCP server process's `KILN_RENDER_PORT_URL` and, when needed, `KILN_RENDER_TOKEN` through the chosen harness. CLI accepts `--render-port URL` and reads `KILN_RENDER_TOKEN`. Start a compatible Kiln renderer on that device; its wider bind requires `RENDER_SERVICE_TOKEN` unless an authenticated proxy is explicitly configured. Manage the remote service on its own device. Verify the selected route with capabilities and require an actual `viewFidelity` receipt for material evidence.
diff --git a/hosting/plugin/README.md b/plugins/kiln-hosted/README.md
similarity index 70%
rename from hosting/plugin/README.md
rename to plugins/kiln-hosted/README.md
index b00e1fa0..05f17d1c 100644
--- a/hosting/plugin/README.md
+++ b/plugins/kiln-hosted/README.md
@@ -38,3 +38,20 @@ receipt.
[Support](https://kiln.instruktlabs.com/support) ·
[Privacy](https://kiln.instruktlabs.com/privacy) ·
[Terms](https://kiln.instruktlabs.com/terms)
+
+## Source and packaging boundary
+
+These public integration files remain with the Kiln engine. The official hosted
+application builds independently in the private `instruktlabs/kiln-hosted`
+repository. No private application source or credentials are needed to build this
+draft with `node scripts/package-hosted-plugin.mjs FRESH_OUTPUT_DIRECTORY`.
+
+`tool-surface.json` records the 26 public operation names generated from the
+qualified private candidate using the published engine 1.0.0. It contains no
+service configuration or tool implementation. The private candidate's protocol
+parity checks establish these names; the packaging tests validate review cases
+against them. Refresh this generated record when the qualified service contract
+changes. The plugin version and hosted engine version are recorded separately.
+
+This relocation changes neither the pending product-name decision nor submission
+status. The owner review and live-service qualification still precede submission.
diff --git a/hosting/plugin/mcp.json b/plugins/kiln-hosted/mcp.json
similarity index 100%
rename from hosting/plugin/mcp.json
rename to plugins/kiln-hosted/mcp.json
diff --git a/hosting/plugin/plugin.json b/plugins/kiln-hosted/plugin.json
similarity index 98%
rename from hosting/plugin/plugin.json
rename to plugins/kiln-hosted/plugin.json
index fc00d25f..c543049d 100644
--- a/hosting/plugin/plugin.json
+++ b/plugins/kiln-hosted/plugin.json
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "kiln-engine",
- "version": "1.0.0",
+ "version": "1.1.0-dev.1",
"description": "Create, review and revise editable 3D assets, with private saved revisions and GLB downloads.",
"author": {
"name": "Instrukt Labs",
diff --git a/hosting/plugin/review-cases.json b/plugins/kiln-hosted/review-cases.json
similarity index 100%
rename from hosting/plugin/review-cases.json
rename to plugins/kiln-hosted/review-cases.json
diff --git a/hosting/plugin/skills/kiln-hosted/SKILL.md b/plugins/kiln-hosted/skills/kiln-hosted/SKILL.md
similarity index 100%
rename from hosting/plugin/skills/kiln-hosted/SKILL.md
rename to plugins/kiln-hosted/skills/kiln-hosted/SKILL.md
diff --git a/plugins/kiln-hosted/tool-surface.json b/plugins/kiln-hosted/tool-surface.json
new file mode 100644
index 00000000..8322deda
--- /dev/null
+++ b/plugins/kiln-hosted/tool-surface.json
@@ -0,0 +1,38 @@
+{
+ "kind": "kiln.hosted-public-interface.v1",
+ "hostedToolSurface": "kiln.hosted-tools.v1",
+ "engine": {
+ "name": "@instruktlabs/kiln",
+ "version": "1.0.0",
+ "sourceCommit": "fda71ac775750f25390b6ee30082ebc56463edc6",
+ "sha256": "6ed3d6b9964429f14c3c6a0a6a13d56be509dd0f40b07061a37d491f901c1508"
+ },
+ "tools": [
+ "kiln_assets_catalog",
+ "kiln_assets_collections",
+ "kiln_assets_get",
+ "kiln_assets_list",
+ "kiln_assets_restore",
+ "kiln_capabilities",
+ "kiln_discover",
+ "kiln_edit",
+ "kiln_export",
+ "kiln_import",
+ "kiln_inspect",
+ "kiln_material_create_preset",
+ "kiln_material_create_procedural",
+ "kiln_material_get",
+ "kiln_material_import",
+ "kiln_material_list",
+ "kiln_material_presets",
+ "kiln_present",
+ "kiln_render",
+ "kiln_renderer_reprobe",
+ "kiln_renderer_status",
+ "kiln_save",
+ "kiln_screenshot_animation",
+ "kiln_source",
+ "kiln_validate",
+ "kiln_view_interior"
+ ]
+}
diff --git a/scripts/create-workspace.mjs b/scripts/create-workspace.mjs
index 97c373af..c6995e22 100644
--- a/scripts/create-workspace.mjs
+++ b/scripts/create-workspace.mjs
@@ -22,11 +22,24 @@ import { assertNodeRuntime } from '../src/runtime-support.mjs';
const installation = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const quote = JSON.stringify;
const hash = (value) => createHash('sha256').update(value).digest('hex');
-const harnesses = ['claude', 'codex', 'opencode', 'hermes', 'agy', 'copilot', 'cursor-agent'];
+const harnesses = Object.freeze([
+ 'claude',
+ 'codex',
+ 'opencode',
+ 'hermes',
+ 'agy',
+ 'copilot',
+ 'cursor-agent',
+]);
+export const workspaceSetupCapabilities = Object.freeze({
+ projectAdoption: 1,
+ recovery: 1,
+ harnesses,
+});
/**
* Where the chosen harness looks for project skills, relative to the workspace, as
- * measured on the installed CLIs (docs/harnesses.md). Claude Code names `.claude/skills`
- * and `.agents/skills`, so a workspace that carried both registered every skill twice;
+ * measured on the installed CLIs (docs/harnesses.md). Fresh-profile probes on
+ * 2026-10-07 load Claude skills from `.claude/skills`, not `.agents/skills`;
* codex, hermes, agy, copilot and cursor-agent name `.agents/skills`; opencode reads only
* the `skills.paths` its generated config names, which is `skills/` itself. One registry
* per harness: every copy is bytes an upgrade must track and a reader may edit.
@@ -304,7 +317,7 @@ try {
}
function startGuide(root, runtime, harness, nodeExecutable, server) {
- const launchers = { agy: 'node agy.mjs', codex: 'node codex.mjs', hermes: 'node hermes.mjs' };
+ const launchers = { agy: 'node agy.mjs', hermes: 'node hermes.mjs' };
const command = launchers[harness] ?? harness;
const launch =
harness === 'hermes'
@@ -573,13 +586,30 @@ export async function renderServiceNotice(runtime) {
/** Preflight first; create a complete project in a staging directory before installing it. */
export async function createWorkspace(directory, harness = 'claude', options = {}) {
let root = resolve(directory);
+ if (options.recover) {
+ if (options.repair || options.upgrade || options.check || options.adopt || options.skills)
+ throw new Error('Use --recover alone before retrying setup.');
+ const { recoverProjectEdits } = await import('./workspace-transaction.mjs');
+ return recoverProjectEdits(root, { stateDirectory: options.stateDirectory });
+ }
const runtime = await realpath(resolve(options.installation ?? installation));
if ([options.repair, options.upgrade, options.check].filter(Boolean).length > 1)
throw new Error('Choose only one of --repair, --upgrade or --check.');
- if ((options.repair || options.upgrade || options.check) && options.skills)
+ if ((options.repair || options.upgrade || (options.check && !options.adopt)) && options.skills)
throw new Error('Maintenance does not change the installed skill selection.');
- const previous =
- options.repair || options.upgrade || options.check ? await readManifest(root) : undefined;
+ let previous;
+ if (options.adopt) {
+ const bytes = await workspaceFile(root, '.kiln/workspace.json');
+ if (bytes !== undefined) {
+ try {
+ previous = JSON.parse(bytes.toString('utf8'));
+ if (!previous || typeof previous !== 'object' || Array.isArray(previous)) throw new Error();
+ } catch {
+ throw new Error('Invalid Kiln workspace manifest; no files were changed.');
+ }
+ }
+ } else if (options.repair || options.upgrade || options.check)
+ previous = await readManifest(root);
// A read-only check validates the configured interpreter, not whichever supported
// Node the caller's shell selected. Setup/repair/upgrade deliberately repin it.
// A missing recorded executable remains drift; do not silently accept that case.
@@ -588,17 +618,20 @@ export async function createWorkspace(directory, harness = 'claude', options = {
options.check && typeof previous?.node === 'string' && existsSync(previous.node)
? previous.node
: realpathSync(process.execPath);
- if (previous) harness = previous.harness;
+ if (previous && !options.adopt) harness = previous.harness;
if (!harnesses.includes(harness)) throw new Error(`Choose ${harnesses.join(', ')}.`);
const extras = options.skills ?? [];
if (extras.some((name) => !Object.hasOwn(optional, name)))
throw new Error('Optional skills: compose,batch.');
- const skills = previous?.skills ?? [...core, ...new Set(extras.map((name) => optional[name]))];
+ const previousSkills = previous?.skills ?? core;
if (
- !Array.isArray(skills) ||
- skills.some((name) => ![...core, ...Object.values(optional)].includes(name))
+ !Array.isArray(previousSkills) ||
+ !core.every((name) => previousSkills.includes(name)) ||
+ new Set(previousSkills).size !== previousSkills.length ||
+ previousSkills.some((name) => ![...core, ...Object.values(optional)].includes(name))
)
throw new Error('Invalid workspace skill manifest.');
+ const skills = [...new Set([...previousSkills, ...extras.map((name) => optional[name])])];
const pkg = await preflightRuntime(runtime, skills, !options.check);
let exists = false;
try {
@@ -631,7 +664,7 @@ export async function createWorkspace(directory, harness = 'claude', options = {
}
if (inside(runtime, root) || inside(runtime, ancestor))
throw new Error('Choose a directory outside the Kiln installation.');
- if (!previous && exists && (await readdir(root)).length)
+ if (!options.adopt && !previous && exists && (await readdir(root)).length)
throw new Error('The destination must be empty; no existing files were changed.');
const { files, store, server } = managedFiles(root, runtime, harness, nodeExecutable);
const manifest = {
@@ -660,6 +693,29 @@ export async function createWorkspace(directory, harness = 'claude', options = {
: undefined,
generated: Object.fromEntries(Object.entries(files).map(([name, body]) => [name, hash(body)])),
};
+ if (options.adopt || previous?.schemaVersion === 2) {
+ const { setupProject } = await import('./workspace-project.mjs');
+ return setupProject({
+ root,
+ runtime,
+ harness,
+ previous,
+ metadata: manifest,
+ exists,
+ options,
+ guide,
+ allowedHarnesses: harnesses,
+ projectFiles: (selected) => managedFiles(root, runtime, selected, nodeExecutable).files,
+ startGuide: (selected) => startGuide(root, runtime, selected, nodeExecutable, server),
+ skillFiles: async () => {
+ const result = {};
+ for (const skill of skills)
+ for (const name of Object.keys(await fileHashes(join(runtime, 'skills', skill))).sort())
+ result[`${skill}/${name}`] = await readFile(join(runtime, 'skills', skill, name));
+ return result;
+ },
+ });
+ }
if (previous && (options.upgrade || options.check))
return upgradeWorkspace(root, runtime, previous, manifest, files, options.check);
if (previous) {
@@ -773,7 +829,7 @@ if (isDirectSetupEntry()) {
const args = process.argv.slice(2);
if (args.includes('--help') || args.includes('-h')) {
console.log(
- `Usage: kiln-init <empty-directory> [--harness ${harnesses.join('|')}] [--skills compose,batch]\n kiln-init <managed-workspace> --repair|--check|--upgrade`,
+ `Usage: kiln-init <empty-directory> [--harness ${harnesses.join('|')}] [--skills compose,batch]\n kiln-init <project-or-new-workspace> --adopt [--harness NAME] [--check]\n kiln-init <managed-workspace> --repair|--check|--upgrade\n kiln-init <project> --recover`,
);
} else {
const directory = args.shift();
@@ -786,6 +842,8 @@ if (isDirectSetupEntry()) {
if (flag === '--repair') options.repair = true;
else if (flag === '--upgrade') options.upgrade = true;
else if (flag === '--check') options.check = true;
+ else if (flag === '--adopt') options.adopt = true;
+ else if (flag === '--recover') options.recover = true;
else if (flag === '--harness' || flag === '--skills') {
const value = args.shift();
if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value.`);
diff --git a/scripts/hosting/README.md b/scripts/hosting/README.md
index 9a3ecf4e..d875885a 100644
--- a/scripts/hosting/README.md
+++ b/scripts/hosting/README.md
@@ -26,14 +26,34 @@ preflight, use an explicitly named fresh container, `--network none`, a memory
limit, a CPU limit, and a PID limit. Copy `/tmp/qualification` out after exit and
inspect its receipt before removing that specific probe container. Do not add
privileged mode, host namespaces, extra capabilities or a looser seccomp profile
-to force a pass. The current Docker daemon is unavailable on the development PC.
+to force a pass. Check the current daemon state before a local run; earlier
+unavailable-daemon records do not describe its present state.
The separate `Native hosting preflight` GitHub workflow builds this six-file
context on Linux, records the exact archive/image/dependency identities, and runs
with no network or host mounts, one CPU, 6 GiB memory, 256 PIDs, no capabilities
-and no new privileges. It retains unsuccessful receipts and keeps the workflow
-failed when qualification fails. Its independently executed trusted renderer
-fixture can diagnose native dependencies after an isolation failure; it never
-qualifies untrusted evaluation. CI evidence does not establish Cloudflare support.
+and no new privileges. Its explicit `--expect-unsupported-isolation` mode requires
+kernel namespace permission denial, readiness rejection and a failed source
+request with no artifact. This emits `kiln.unsupported-evaluator-rejection.v1`,
+which records `isolatedExecutionAvailable: false`; it never counts as successful
+isolation. Unexpected readiness success, source execution or a different failure
+fails this negative-host test. The separate software-renderer fixture must also
+pass. Original failed receipts remain retained; CI evidence does not establish
+Cloudflare support.
+
+An additional `Installed nested evaluator` job tests the archive on an
+unprivileged Ubuntu 22.04 VM, with a source-pinned non-setuid Bubblewrap build and
+no changes to host security policy. Its explicit `--isolation-only` mode emits a
+different receipt, `kiln.nested-evaluator-qualification.v1`: all ten readiness
+invariants and nine host/evaluation/CPU/limit checks must pass. It uses dedicated
+`/usr/local/bin/kiln-probe-bwrap` and `kiln-probe-node` binaries, records their
+hashes and installs the archive at `/app` outside the source checkout. This mode
+does not test software rendering or qualify Cloudflare. Both the positive VM job
+and the restricted Docker refusal/renderer job must pass. The former passed all
+nine checks at `5b1094c`, with archive and artifact hashes independently verified;
+see the [preflight evidence](../../docs/reviews/2026-10-07-native-preflight-alignment.md).
+The negative-host mode is selected explicitly, never as a fallback after failed
+positive qualification. The default command still requires complete positive
+evaluation and software rendering on a compatible host.
The initial Bookworm image built but Mesa 22.3 failed Dawn's required Vulkan
features. The pinned Trixie replacement passes the six-image software fixture.
@@ -58,12 +78,12 @@ startup or earlier work; retain the before/after snapshots without relabeling th
as per-job RSS or billed CPU. Load, tenancy, persistence, retention and cost remain
separate service tests.
-Cloudflare's current documentation recommends the Durable Object Container API
-for new applications and describes a separate microVM per container. Neither fact
-guarantees that this image can create Kiln's nested namespaces. Run this unchanged
-probe on the provider before selecting its production execution boundary. If it
-fails, record the specific failure and evaluate a reviewed per-job/per-user
-provider sandbox design; do not silently substitute ordinary subprocess execution.
+Cloudflare's documented microVM boundary does not guarantee nested namespace
+support. Kiln's hosted candidate explicitly selects its separately qualified
+fresh-VM adapter; these generic SDK probes do not qualify that provider boundary.
+Never silently substitute ordinary subprocess execution when nested isolation
+fails. Keep provider image/controller, tenancy and whole-instance cleanup evidence
+separate from these two CI host profiles.
References checked 6 October 2026:
[container lifecycle](https://developers.cloudflare.com/containers/concepts/architecture/),
diff --git a/scripts/hosting/diagnose-native-launch.mjs b/scripts/hosting/diagnose-native-launch.mjs
new file mode 100644
index 00000000..3efd2e1d
--- /dev/null
+++ b/scripts/hosting/diagnose-native-launch.mjs
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+// CI-only diagnostics for the fixed installed transport worker and box fixture. No user source,
+// provider access, inherited child environment or security-policy changes.
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { existsSync, writeFileSync } from 'node:fs';
+import { pathToFileURL } from 'node:url';
+
+assert.equal(process.platform, 'linux');
+assert(process.getuid() > 0);
+assert.equal(process.argv.length, 3);
+const output = process.argv[2];
+const installation = '/app/node_modules/@instruktlabs/kiln';
+const host = {
+ bwrapPath: '/usr/local/bin/kiln-probe-bwrap',
+ nodePath: '/usr/local/bin/kiln-probe-node',
+};
+const record = { version: 'kiln.fixed-transport-diagnostic.v1', qualified: false };
+try {
+ const evaluator = await import(pathToFileURL(`${installation}/lib/evaluator/isolation.js`).href);
+ const worker = `${installation}/lib/evaluator/transport-worker.mjs`;
+ record.filesPresent = Object.fromEntries(
+ [worker, host.bwrapPath, host.nodePath, '/usr/bin/setpriv', '/usr/bin/prlimit'].map((path) => [
+ path,
+ existsSync(path),
+ ]),
+ );
+ const launch = evaluator.isolatedEvaluatorLaunch(worker, host);
+ const child = spawnSync(launch.command, launch.args, {
+ env: launch.env,
+ detached: true,
+ stdio: ['ignore', 'pipe', 'pipe', 'pipe'],
+ encoding: 'utf8',
+ timeout: 8000,
+ killSignal: 'SIGKILL',
+ maxBuffer: 16 * 1024,
+ });
+ record.launch = { command: launch.command, args: launch.args };
+ record.exit = {
+ status: child.status,
+ signal: child.signal,
+ error: child.error?.code ?? null,
+ };
+ record.stdout = String(child.output[1] ?? '').slice(0, 4096);
+ record.stderr = String(child.output[2] ?? '').slice(0, 4096);
+ record.fd3 = String(child.output[3] ?? '').slice(0, 4096);
+ // This fixed inspection runs with the exact same launch boundary after a
+ // successful transport. It reads only kernel identity flags and env key names.
+ if (child.status === 0) {
+ const fixedInspection = `
+ import { readFileSync } from 'node:fs';
+ const status = readFileSync('/proc/self/status', 'utf8').split('\\n')
+ .filter(line => /^(Uid|Gid|NoNewPrivs|CapInh|CapPrm|CapEff|CapBnd|CapAmb|Seccomp):/.test(line));
+ console.log(JSON.stringify({status, uidMap: readFileSync('/proc/self/uid_map', 'utf8'),
+ envKeys: Object.keys(process.env).sort(), pwd: process.env.PWD ?? null}));
+ `;
+ const inspected = spawnSync(
+ launch.command,
+ [...launch.args.slice(0, -1), '--input-type=module', '--eval', fixedInspection],
+ {
+ env: launch.env,
+ detached: true,
+ stdio: ['ignore', 'pipe', 'pipe', 'pipe'],
+ encoding: 'utf8',
+ timeout: 8000,
+ killSignal: 'SIGKILL',
+ maxBuffer: 16 * 1024,
+ },
+ );
+ record.invariants = {
+ status: inspected.status,
+ signal: inspected.signal,
+ error: inspected.error?.code ?? null,
+ stdout: String(inspected.stdout ?? '').slice(0, 4096),
+ stderr: String(inspected.stderr ?? '').slice(0, 4096),
+ };
+ // The public worker deliberately strips exception details. For this fixed
+ // repository fixture only, inspect the installed renderer under the same
+ // boundary. There is no source input, host environment or product storage.
+ // Never add this diagnostic path to the evaluator protocol or public host.
+ const fixedRender = `
+ try {
+ const { renderGLBInProcess } = await import('file:///app/node_modules/@instruktlabs/kiln/lib/render.js');
+ const result = await renderGLBInProcess('function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}');
+ console.log(JSON.stringify({status: 'passed', bytes: result.glb.length}));
+ } catch (error) {
+ console.log(JSON.stringify({status: 'failed', name: error?.name,
+ code: error?.code, message: String(error?.message ?? '').slice(0, 1024),
+ stack: String(error?.stack ?? '').slice(0, 2048)}));
+ process.exitCode = 1;
+ }
+ `;
+ const rendered = spawnSync(
+ launch.command,
+ [...launch.args.slice(0, -1), '--input-type=module', '--eval', fixedRender],
+ {
+ env: launch.env,
+ detached: true,
+ stdio: ['ignore', 'pipe', 'pipe', 'pipe'],
+ encoding: 'utf8',
+ timeout: 30000,
+ killSignal: 'SIGKILL',
+ maxBuffer: 16 * 1024,
+ },
+ );
+ record.fixedRender = {
+ status: rendered.status,
+ signal: rendered.signal,
+ error: rendered.error?.code ?? null,
+ stdout: String(rendered.stdout ?? '').slice(0, 4096),
+ stderr: String(rendered.stderr ?? '').slice(0, 4096),
+ };
+ }
+} catch {
+ record.failure = 'Fixed launch could not be prepared';
+}
+writeFileSync(output, `${JSON.stringify(record, null, 2)}\n`, { flag: 'wx' });
diff --git a/scripts/hosting/native-qualification.mjs b/scripts/hosting/native-qualification.mjs
index 186c2e50..6a44603f 100644
--- a/scripts/hosting/native-qualification.mjs
+++ b/scripts/hosting/native-qualification.mjs
@@ -41,6 +41,62 @@ const LIMITS = {
};
const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
+export async function qualifyNestedEvaluator(ports) {
+ return qualifyRuntime(ports, false);
+}
+
+/** Explicit negative-host test. Never an alternate successful isolation route. */
+export async function qualifyUnsupportedEvaluator(ports) {
+ const receipt = {
+ version: 'kiln.unsupported-evaluator-rejection.v1',
+ status: 'running',
+ checks: [],
+ artifacts: [],
+ };
+ let phase = 'host';
+ async function check(name, run) {
+ phase = name;
+ const start = performance.now();
+ await run();
+ receipt.checks.push({ name, elapsedMs: performance.now() - start });
+ }
+ async function requireRejection(invoke, classify, expected) {
+ try {
+ await invoke();
+ } catch (error) {
+ assert.equal(classify(error), expected);
+ return;
+ }
+ assert.fail('Unsupported boundary unexpectedly accepted the request');
+ }
+ try {
+ await check('host', () => {
+ assert(ports.platform === 'linux' && Number.isInteger(ports.uid) && ports.uid > 0);
+ });
+ await check('kernel-namespace-denied', async () => {
+ assert.equal(await ports.namespaceDenied(), true);
+ });
+ await check('readiness-refused', () =>
+ requireRejection(ports.ready, ports.readinessCode, 'wrapper-launch'),
+ );
+ receipt.readinessFailure = 'wrapper-launch';
+ await check('source-request-refused', () =>
+ requireRejection(
+ () => ports.render(BOX, { ...LIMITS }),
+ (error) => error?.code,
+ 'WORKER_FAILED',
+ ),
+ );
+ receipt.evaluationFailure = 'WORKER_FAILED';
+ receipt.isolatedExecutionAvailable = false;
+ receipt.status = 'passed';
+ } catch {
+ receipt.status = 'failed';
+ receipt.failure = { phase, code: 'CHECK_FAILED' };
+ }
+ return receipt;
+}
+
export async function captureCgroupSnapshot(readText) {
const snapshot = {};
for (const name of ['memory.current', 'memory.peak', 'memory.max', 'cpu.stat']) {
@@ -57,8 +113,14 @@ export async function captureCgroupSnapshot(readText) {
/** Fixed qualification fixtures only. No caller-supplied source and no fallback evaluator. */
export async function qualifyNativeRuntime(ports) {
+ return qualifyRuntime(ports, true);
+}
+
+async function qualifyRuntime(ports, includeSoftware) {
const receipt = {
- version: 'kiln.host-native-qualification.v1',
+ version: includeSoftware
+ ? 'kiln.host-native-qualification.v1'
+ : 'kiln.nested-evaluator-qualification.v1',
status: 'running',
checks: [],
artifacts: [],
@@ -139,13 +201,15 @@ export async function qualifyNativeRuntime(ports) {
rejects('OUTPUT_LIMIT_EXCEEDED', () => ports.render(BOX, { ...LIMITS, maxGlbBytes: 32 })),
);
await check('post-limit-recovery', async () => assert.equal(sha(await render()), sha(glb)));
- receipt.software = await check('software-vulkan', async () => {
- const result = await ports.software();
- assert.equal(result.status, 'passed');
- assert.equal(result.software, true);
- assert(typeof result.rendererId === 'string' && result.rendererId.length < 256);
- return { status: result.status, software: true, rendererId: result.rendererId };
- });
+ if (includeSoftware) {
+ receipt.software = await check('software-vulkan', async () => {
+ const result = await ports.software();
+ assert.equal(result.status, 'passed');
+ assert.equal(result.software, true);
+ assert(typeof result.rendererId === 'string' && result.rendererId.length < 256);
+ return { status: result.status, software: true, rendererId: result.rendererId };
+ });
+ }
receipt.status = 'passed';
} catch (error) {
const code = ports.readinessCode(error) ?? error?.code;
diff --git a/scripts/hosting/native-qualification.test.mjs b/scripts/hosting/native-qualification.test.mjs
index 28845ff2..305dd73f 100644
--- a/scripts/hosting/native-qualification.test.mjs
+++ b/scripts/hosting/native-qualification.test.mjs
@@ -1,5 +1,10 @@
import { expect, test } from 'bun:test';
-import { captureCgroupSnapshot, qualifyNativeRuntime } from './native-qualification.mjs';
+import {
+ captureCgroupSnapshot,
+ qualifyNativeRuntime,
+ qualifyNestedEvaluator,
+ qualifyUnsupportedEvaluator,
+} from './native-qualification.mjs';
test('cgroup evidence retains dotted kernel counters from the Linux preflight', async () => {
const cpu =
@@ -134,6 +139,44 @@ test('successful qualification retains bounded artifacts and separate safety che
);
});
+test('VM evaluator qualification preserves every isolation and execution check without a renderer claim', async () => {
+ const { ports } = fixture();
+ ports.software = async () => {
+ throw new Error('Software rendering belongs to its own image test');
+ };
+ const result = await qualifyNestedEvaluator(ports);
+ expect(result.version).toBe('kiln.nested-evaluator-qualification.v1');
+ expect(result.status).toBe('passed');
+ expect(result.checks.map((item) => item.name)).toEqual([
+ 'host',
+ 'isolation',
+ 'first-evaluation',
+ 'repeat-evaluation',
+ 'cpu-preview',
+ 'deadline',
+ 'cancellation',
+ 'output-limit',
+ 'post-limit-recovery',
+ ]);
+ expect(result.isolation.checks).toEqual(checks);
+ expect(result.artifacts.map((item) => item.name)).toEqual(['fixture.glb', 'cpu-preview.png']);
+ expect(result).not.toHaveProperty('software');
+});
+
+test('VM evaluator qualification cannot relabel unavailable isolation as success', async () => {
+ const { ports, calls } = fixture();
+ ports.ready = async () => {
+ throw { readinessCode: 'wrapper-launch' };
+ };
+ expect(await qualifyNestedEvaluator(ports)).toMatchObject({
+ version: 'kiln.nested-evaluator-qualification.v1',
+ status: 'failed',
+ failure: { phase: 'isolation', code: 'wrapper-launch' },
+ artifacts: [],
+ });
+ expect(calls).toHaveLength(0);
+});
+
test('a deadline check that resolves instead of rejecting is a failure', async () => {
const { ports } = fixture();
ports.render = async () => ({ glb });
@@ -143,6 +186,87 @@ test('a deadline check that resolves instead of rejecting is a failure', async (
});
});
+function unsupportedFixture() {
+ const { ports } = fixture();
+ ports.namespaceDenied = async () => true;
+ ports.ready = async () => {
+ throw { readinessCode: 'wrapper-launch' };
+ };
+ ports.render = async () => {
+ throw { code: 'WORKER_FAILED', message: 'private diagnostic must not escape' };
+ };
+ ports.cpu =
+ ports.software =
+ ports.artifact =
+ async () => {
+ throw new Error('A refused source request cannot produce an artifact');
+ };
+ return ports;
+}
+
+test('an unsupported host qualifies refusal only, with kernel denial and both API rejections', async () => {
+ const receipt = await qualifyUnsupportedEvaluator(unsupportedFixture());
+ expect(receipt).toMatchObject({
+ version: 'kiln.unsupported-evaluator-rejection.v1',
+ status: 'passed',
+ isolatedExecutionAvailable: false,
+ readinessFailure: 'wrapper-launch',
+ evaluationFailure: 'WORKER_FAILED',
+ artifacts: [],
+ });
+ expect(receipt.checks.map((check) => check.name)).toEqual([
+ 'host',
+ 'kernel-namespace-denied',
+ 'readiness-refused',
+ 'source-request-refused',
+ ]);
+ expect(JSON.stringify(receipt)).not.toContain('private diagnostic');
+ expect(receipt).not.toHaveProperty('isolation');
+ expect(receipt).not.toHaveProperty('software');
+});
+
+test('readiness success, unproven kernel denial and source execution cannot pass a refusal check', async () => {
+ for (const overrides of [
+ { namespaceDenied: async () => false },
+ { ready: fixture().ports.ready },
+ { render: fixture().ports.render },
+ {
+ ready: async () => {
+ throw { readinessCode: 'deadline' };
+ },
+ },
+ {
+ render: async () => {
+ throw { code: 'EXECUTION_REJECTED' };
+ },
+ },
+ {
+ render: async () => {
+ throw { code: 'DEADLINE_EXCEEDED' };
+ },
+ },
+ ]) {
+ const receipt = await qualifyUnsupportedEvaluator({ ...unsupportedFixture(), ...overrides });
+ expect(receipt.status).toBe('failed');
+ expect(receipt.artifacts).toEqual([]);
+ }
+});
+
+test('unsupported-host qualification rejects root before either readiness or evaluation', async () => {
+ let invoked = false;
+ const ports = unsupportedFixture();
+ ports.uid = 0;
+ ports.namespaceDenied = async () => {
+ invoked = true;
+ return true;
+ };
+ expect(await qualifyUnsupportedEvaluator(ports)).toMatchObject({
+ status: 'failed',
+ failure: { phase: 'host', code: 'CHECK_FAILED' },
+ });
+ expect(invoked).toBe(false);
+});
+
test('wrong negative outcome is not accepted as a successful limit', async () => {
const { ports } = fixture();
const original = ports.render;
diff --git a/scripts/hosting/run-native-qualification.mjs b/scripts/hosting/run-native-qualification.mjs
index 5b107370..d4acd06b 100644
--- a/scripts/hosting/run-native-qualification.mjs
+++ b/scripts/hosting/run-native-qualification.mjs
@@ -7,13 +7,30 @@ import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { join, resolve, sep } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
-import { captureCgroupSnapshot, qualifyNativeRuntime } from './native-qualification.mjs';
+import {
+ captureCgroupSnapshot,
+ qualifyNativeRuntime,
+ qualifyNestedEvaluator,
+ qualifyUnsupportedEvaluator,
+} from './native-qualification.mjs';
-const [installationArg, outputArg, archiveArg] = process.argv.slice(2);
+const [installationArg, outputArg, archiveArg, mode] = process.argv.slice(2);
assert(
- installationArg && outputArg && archiveArg && process.argv.length === 5,
- 'Usage: run-native-qualification.mjs INSTALLED_PACKAGE NEW_OUTPUT_DIRECTORY EXACT_ARCHIVE',
+ installationArg &&
+ outputArg &&
+ archiveArg &&
+ (process.argv.length === 5 ||
+ (process.argv.length === 6 &&
+ ['--isolation-only', '--expect-unsupported-isolation'].includes(mode))),
+ 'Usage: run-native-qualification.mjs INSTALLED_PACKAGE NEW_OUTPUT_DIRECTORY EXACT_ARCHIVE [--isolation-only | --expect-unsupported-isolation]',
);
+const isolationOnly = mode === '--isolation-only';
+const expectUnsupported = mode === '--expect-unsupported-isolation';
+const qualificationVersion = expectUnsupported
+ ? 'kiln.unsupported-evaluator-rejection.v1'
+ : isolationOnly
+ ? 'kiln.nested-evaluator-qualification.v1'
+ : 'kiln.host-native-qualification.v1';
const installation = await realpath(resolve(installationArg));
const output = resolve(outputArg);
const parent = await realpath(resolve(output, '..'));
@@ -52,15 +69,44 @@ try {
);
const module = (path) => import(pathToFileURL(join(installation, path)).href);
const evaluator = await module('lib/evaluator/index.js');
- const host = { bwrapPath: '/usr/bin/bwrap' };
+ const host = isolationOnly
+ ? { bwrapPath: '/usr/local/bin/kiln-probe-bwrap', nodePath: process.execPath }
+ : { bwrapPath: '/usr/bin/bwrap' };
const require = createRequire(pathToFileURL(join(installation, 'package.json')));
const { PNG } = require('pngjs');
record.cgroupBefore = await cgroupSnapshot();
- const result = await qualifyNativeRuntime({
+ const qualify = expectUnsupported
+ ? qualifyUnsupportedEvaluator
+ : isolationOnly
+ ? qualifyNestedEvaluator
+ : qualifyNativeRuntime;
+ const result = await qualify({
platform: process.platform,
uid: record.uid,
ready: () => evaluator.assertIsolatedEvaluatorReady(host),
readinessCode: evaluator.isolationReadinessFailureCode,
+ namespaceDenied: async () => {
+ const probe = spawnSync('/usr/bin/unshare', ['--user', '--map-root-user', '/usr/bin/true'], {
+ env: { LC_ALL: 'C' },
+ encoding: 'utf8',
+ timeout: 5000,
+ maxBuffer: 4096,
+ });
+ const denied =
+ probe.status === 1 &&
+ probe.signal === null &&
+ !probe.error &&
+ /^unshare: unshare failed: (Operation not permitted|Permission denied)\s*$/.test(
+ probe.stderr,
+ );
+ record.namespaceProbe = {
+ status: probe.status,
+ signal: probe.signal,
+ error: probe.error?.code ?? null,
+ permissionDenied: denied,
+ };
+ return denied;
+ },
render: (source, controls) =>
evaluator.renderGLBViaIsolatedEvaluator(source, {}, { ...controls, host }),
cpu: async (glb) => {
@@ -109,7 +155,7 @@ try {
Object.assign(record, result);
} catch {
Object.assign(record, {
- version: 'kiln.host-native-qualification.v1',
+ version: qualificationVersion,
status: 'failed',
checks: [],
artifacts: [],
diff --git a/hosting/scripts/package-public-plugin.mjs b/scripts/package-hosted-plugin.mjs
similarity index 80%
rename from hosting/scripts/package-public-plugin.mjs
rename to scripts/package-hosted-plugin.mjs
index af766f84..339b606a 100644
--- a/hosting/scripts/package-public-plugin.mjs
+++ b/scripts/package-hosted-plugin.mjs
@@ -4,9 +4,8 @@ import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { zipSync } from 'three/addons/libs/fflate.module.js';
-import { createPublicTools, HOSTED_TOOL_SURFACE } from '../src/public-tools.ts';
-const repo = await realpath(fileURLToPath(new URL('../../', import.meta.url)));
+const repo = await realpath(fileURLToPath(new URL('../', import.meta.url)));
const json = (value) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
const origin = 'https://kiln.instruktlabs.com';
@@ -111,18 +110,32 @@ export async function packagePublicPlugin(destination) {
}
const sourceJson = async (name) => JSON.parse(await source(name));
const pkg = await sourceJson('package.json');
- const manifest = await sourceJson('hosting/plugin/plugin.json');
- const mcp = await sourceJson('hosting/plugin/mcp.json');
- const cases = await sourceJson('hosting/plugin/review-cases.json');
+ const manifest = await sourceJson('plugins/kiln-hosted/plugin.json');
+ const mcp = await sourceJson('plugins/kiln-hosted/mcp.json');
+ const cases = await sourceJson('plugins/kiln-hosted/review-cases.json');
assert.equal(pkg.name, '@instruktlabs/kiln');
assert.equal(manifest.version, pkg.version, 'Review plugin version against the pinned engine');
- // This metadata snapshot is larger than plugin inputs and is never copied into
- // the ZIP. The build's existing regeneration check qualifies it separately.
- const native = JSON.parse(
- await source('hosting/src/generated/edge-manifest.json', 2 * 1024 * 1024),
- );
- await source('hosting/src/public-tools.ts');
- const toolNames = new Set(createPublicTools(native.tools).tools.map((tool) => tool.name));
+ // Generated public operation names from the qualified service candidate. This
+ // packaging process never imports the private application or its configuration.
+ const surface = await sourceJson('plugins/kiln-hosted/tool-surface.json');
+ noPrivateConfiguration(surface);
+ assert.deepEqual(Object.keys(surface).sort(), ['engine', 'hostedToolSurface', 'kind', 'tools']);
+ assert.equal(surface.kind, 'kiln.hosted-public-interface.v1');
+ assert.equal(surface.hostedToolSurface, 'kiln.hosted-tools.v1');
+ assert.deepEqual(Object.keys(surface.engine).sort(), [
+ 'name',
+ 'sha256',
+ 'sourceCommit',
+ 'version',
+ ]);
+ assert.equal(surface.engine.name, '@instruktlabs/kiln');
+ assert.match(surface.engine.version, /^\d+\.\d+\.\d+(?:-[\w.]+)?$/);
+ assert.match(surface.engine.sourceCommit, /^[a-f0-9]{40}$/);
+ assert.match(surface.engine.sha256, /^[a-f0-9]{64}$/);
+ assert(Array.isArray(surface.tools) && surface.tools.length > 0);
+ for (const name of surface.tools) assert.match(name, /^kiln_[a-z0-9_]+$/);
+ const toolNames = new Set(surface.tools);
+ assert.equal(toolNames.size, surface.tools.length);
validatePublicMetadata(manifest, mcp, cases, toolNames);
manifest.extensions['com.openai'].review = {
test_cases: cases,
@@ -134,9 +147,12 @@ export async function packagePublicPlugin(destination) {
const files = new Map([
['plugin.json', json(manifest)],
['mcp.json', json(mcp)],
- ['README.md', await source('hosting/plugin/README.md')],
+ ['README.md', await source('plugins/kiln-hosted/README.md')],
['LICENSE', await source('LICENSE')],
- ['skills/kiln-hosted/SKILL.md', await source('hosting/plugin/skills/kiln-hosted/SKILL.md')],
+ [
+ 'skills/kiln-hosted/SKILL.md',
+ await source('plugins/kiln-hosted/skills/kiln-hosted/SKILL.md'),
+ ],
]);
for (const name of [
'program-contract.md',
@@ -162,8 +178,9 @@ export async function packagePublicPlugin(destination) {
'package-provenance.json',
json({
kind: 'kiln.public-plugin.v1',
- engineVersion: pkg.version,
- hostedToolSurface: HOSTED_TOOL_SURFACE,
+ pluginVersion: pkg.version,
+ engineVersion: surface.engine.version,
+ hostedToolSurface: surface.hostedToolSurface,
sources,
files: Object.fromEntries([...files].map(([name, bytes]) => [name, hash(bytes)])),
}),
@@ -175,8 +192,9 @@ export async function packagePublicPlugin(destination) {
const receipt = {
kind: 'kiln.public-plugin.draft.v1',
submissionReady: false,
- engineVersion: pkg.version,
- hostedToolSurface: HOSTED_TOOL_SURFACE,
+ pluginVersion: pkg.version,
+ engineVersion: surface.engine.version,
+ hostedToolSurface: surface.hostedToolSurface,
remaining: [
'live-endpoint-and-terms',
'live-client-review-cases',
@@ -204,7 +222,7 @@ export async function packagePublicPlugin(destination) {
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const [destination, ...extra] = process.argv.slice(2);
if (!destination || extra.length)
- throw new Error('Usage: node hosting/scripts/package-public-plugin.mjs FRESH_OUTPUT_DIRECTORY');
+ throw new Error('Usage: node scripts/package-hosted-plugin.mjs FRESH_OUTPUT_DIRECTORY');
const receipt = await packagePublicPlugin(destination);
console.log(
JSON.stringify(
diff --git a/hosting/test/public-plugin.test.mjs b/scripts/package-hosted-plugin.test.mjs
similarity index 89%
rename from hosting/test/public-plugin.test.mjs
rename to scripts/package-hosted-plugin.test.mjs
index 899ff888..b77818dc 100644
--- a/hosting/test/public-plugin.test.mjs
+++ b/scripts/package-hosted-plugin.test.mjs
@@ -6,10 +6,9 @@ import { join, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { after, test } from 'node:test';
import { unzipSync } from 'three/addons/libs/fflate.module.js';
-import { packagePublicPlugin, validatePublicMetadata } from '../scripts/package-public-plugin.mjs';
-import { createPublicTools } from '../src/public-tools.ts';
+import { packagePublicPlugin, validatePublicMetadata } from './package-hosted-plugin.mjs';
-const repo = fileURLToPath(new URL('../../', import.meta.url));
+const repo = fileURLToPath(new URL('../', import.meta.url));
const temporary = await realpath(await mkdtemp(join(tmpdir(), 'kiln-public-plugin-')));
after(async () => {
const parent = await realpath(tmpdir());
@@ -30,7 +29,7 @@ test('public draft ZIP has one hosted MCP, complete referenced assets and no loc
const files = unzipSync(zip);
const manifest = JSON.parse(Buffer.from(files['plugin.json']));
assert.equal(manifest.name, 'kiln-engine');
- assert.equal(manifest.version, '1.0.0');
+ assert.equal(manifest.version, (await json(join(repo, 'package.json'))).version);
const metadata = manifest.extensions['com.openai'];
assert.ok(metadata.interface.shortDescription.length <= 30);
assert.equal(metadata.interface.termsOfServiceURL, 'https://kiln.instruktlabs.com/terms');
@@ -99,11 +98,11 @@ test('packaging refuses existing output before modifying its files', async () =>
});
test('public metadata refuses private connectors, credential headers, hidden components and unadvertised review operations', async () => {
- const manifest = await json(join(repo, 'hosting/plugin/plugin.json'));
- const mcp = await json(join(repo, 'hosting/plugin/mcp.json'));
- const cases = await json(join(repo, 'hosting/plugin/review-cases.json'));
- const native = await json(join(repo, 'hosting/src/generated/edge-manifest.json'));
- const names = new Set(createPublicTools(native.tools).tools.map((tool) => tool.name));
+ const manifest = await json(join(repo, 'plugins/kiln-hosted/plugin.json'));
+ const mcp = await json(join(repo, 'plugins/kiln-hosted/mcp.json'));
+ const cases = await json(join(repo, 'plugins/kiln-hosted/review-cases.json'));
+ const surface = await json(join(repo, 'plugins/kiln-hosted/tool-surface.json'));
+ const names = new Set(surface.tools);
validatePublicMetadata(manifest, mcp, cases, names);
for (const mutation of [
(m) => {
diff --git a/scripts/package-local-plugin.mjs b/scripts/package-local-plugin.mjs
index 1487e96b..22c7773a 100644
--- a/scripts/package-local-plugin.mjs
+++ b/scripts/package-local-plugin.mjs
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
import { chmod, lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { workspaceSetupCapabilities } from './create-workspace.mjs';
const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const json = (value) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
@@ -89,7 +90,14 @@ async function expectedFiles() {
json({ ...identity, icon: './.claude-plugin/icon.png', ...listingLinks }),
],
['.claude-plugin/icon.png', await readFile(join(repo, 'assets/branding/kiln-512.png'))],
- ['runtime.json', json({ name: pkg.name, version: pkg.version })],
+ [
+ 'runtime.json',
+ json({
+ name: pkg.name,
+ version: pkg.version,
+ harnesses: workspaceSetupCapabilities.harnesses,
+ }),
+ ],
['LICENSE', await readFile(join(repo, 'LICENSE'))],
['PRIVACY.md', await readFile(join(repo, 'docs/local-plugin-privacy.md'))],
[executable, await readFile(join(repo, 'scripts/setup-plugin-workspace.mjs'))],
@@ -112,7 +120,7 @@ async function expectedFiles() {
${development}Plugin version ${release.version}, maintained by Instrukt Labs under the MIT license.
This plugin installs engine ${pkg.version}.
-Set up a persistent Kiln workspace for Claude Code or Codex, then create and revise
+Set up Kiln in an existing project or a new asset workspace, then create and revise
editable 3D assets with your coding agent. Use a supported Node.js installation
with npm. No Bun, engine checkout, Kiln account or separate model API key is needed.
The plugin requires a local shell and filesystem; Claude chat and Cowork are not
@@ -137,24 +145,34 @@ codex plugin add kiln-engine@instruktlabs
Restart or reload your coding agent's plugins as its installation message directs.
Then ask it to set up a Kiln workspace. The maintained setup skill runs this
plugin's \`bin/kiln-setup-workspace.mjs\` with Node, installs
-\`${pkg.name}@${pkg.version}\` and creates a separate asset workspace.
+\`${pkg.name}@${pkg.version}\` outside the project and configures your chosen
+workspace. The same initializer supports existing projects and new workspaces.
The plugin registers setup only. The workspace supplies authoring skills and one
-local MCP server, \`kiln_workspace\`. Open Claude Code in that workspace; launch
-Codex there with \`node codex.mjs\`. Follow \`START.md\`, accept the host's ordinary
-trust prompts and verify live tool discovery before authoring.
+local MCP server, \`kiln_workspace\`. Open Claude Code in that workspace or launch
+Codex there with \`codex\`. For headless Codex execution, use
+\`node codex.mjs "TASK"\` with an explicit prompt. Read \`.kiln/START.md\` after
+adoption or \`START.md\` in a legacy workspace, accept the host's ordinary trust
+prompts and verify live tool discovery before authoring.
-## Three setup examples
+## Setup examples
1. **Create:** “Set up a new Kiln workspace in an empty directory outside this
checkout, using my current coding agent. Verify its tools before I author an
asset.” The installer downloads the pinned engine when needed, creates the
selected workspace and keeps its engine in a separate runtime store. npm also
uses its normal cache and log directories.
-2. **Check:** “Check my existing Kiln workspace without changing it.” The helper's
+2. **Adopt:** “Add Kiln to this project without replacing my instructions or other
+ MCP settings. Show the planned changes first.” Use \`--adopt --check\` to
+ preview, then \`--adopt\` to apply. Read \`.kiln/AGENTS.md\` alongside the
+ project's instructions. Repeat with another supported \`--harness\` to add
+ that integration around the same saved assets. The engine's adapter list is
+ included in \`runtime.json\`; it does not imply this plugin can be installed
+ in every listed client. Published engine 1.0.0 does not support adoption.
+3. **Check:** “Check my existing Kiln workspace without changing it.” The helper's
\`--check\` mode reports whether managed files and the installed engine are
current. A missing runtime is reported without installing one.
-3. **Upgrade:** “Upgrade my managed Kiln workspace while preserving my sources,
+4. **Upgrade:** “Upgrade my managed Kiln workspace while preserving my sources,
saved assets and customizations.” Stop the workspace's harness session first.
The helper's \`--upgrade\` mode uses the pinned engine and refuses conflicts
rather than replacing customized managed files.
@@ -172,6 +190,13 @@ installer runs npm with lifecycle scripts disabled and invokes Kiln's workspace
generator. It does this before the workspace MCP server exists; it does not
silently install a global MCP server or grant itself shell permissions.
+Adoption and managed project updates temporarily keep recovery copies outside
+the project. Client configuration can already contain credentials, so these
+private copies may too. They are removed after successful setup or recovery;
+interrupted transactions retain them. See [local privacy](PRIVACY.md) for the
+storage location and protection limits. Use \`--recover\` before retrying an
+interrupted project update.
+
Marketplace installation and updates contact \`https://github.com\`. First engine
installation and dependency downloads use \`https://registry.npmjs.org\`. npm can
use your existing npm configuration and environment. No npm login or token is
diff --git a/scripts/package-local-plugin.test.mjs b/scripts/package-local-plugin.test.mjs
index bf5e9455..55ec73aa 100644
--- a/scripts/package-local-plugin.test.mjs
+++ b/scripts/package-local-plugin.test.mjs
@@ -16,6 +16,7 @@ import { tmpdir } from 'node:os';
import { join, resolve, sep } from 'node:path';
import { PNG } from 'pngjs';
import { packageLocalPlugin } from './package-local-plugin.mjs';
+import { workspaceSetupCapabilities } from './create-workspace.mjs';
const roots = [];
afterEach(async () => {
@@ -58,6 +59,7 @@ test('local plugin versions independently while retaining its exact engine pin',
expect(await readJson(join(directory, 'runtime.json'))).toEqual({
name: pkg.name,
version: pkg.version,
+ harnesses: workspaceSetupCapabilities.harnesses,
});
expect(portable.extensions['com.openai'].interface.displayName).toBe('Kiln Engine');
expect(portable.mcpServers).toBeUndefined();
diff --git a/scripts/setup-plugin-workspace.mjs b/scripts/setup-plugin-workspace.mjs
index c8386a00..a8b1b789 100644
--- a/scripts/setup-plugin-workspace.mjs
+++ b/scripts/setup-plugin-workspace.mjs
@@ -232,14 +232,15 @@ async function installRuntime(data, pin, archive, archiveHash, options) {
export async function setupPluginWorkspace(options = {}) {
const harness = options.harness || 'claude';
- if (!['claude', 'codex'].includes(harness)) throw new Error('Choose harness claude or codex.');
const mode = options.mode || 'create';
- if (!['create', 'check', 'upgrade', 'repair'].includes(mode))
+ if (!['create', 'check', 'upgrade', 'repair', 'recover'].includes(mode))
throw new Error('Unknown workspace setup mode.');
+ if (mode === 'recover' && (options.adopt || options.skills))
+ throw new Error('Use --recover alone before retrying setup.');
if (!options.directory) throw new Error('Provide a workspace directory.');
if (
options.skills &&
- (mode !== 'create' ||
+ ((mode !== 'create' && !(mode === 'check' && options.adopt)) ||
!Array.isArray(options.skills) ||
options.skills.some((name) => !['compose', 'batch'].includes(name)))
)
@@ -251,6 +252,18 @@ export async function setupPluginWorkspace(options = {}) {
if (pin.name !== packageName) throw new Error(`The plugin must pin package ${packageName}.`);
if (typeof pin.version !== 'string' || !exactVersion.test(pin.version))
throw new Error('The plugin runtime needs an exact stable, rc.N or dev.N version.');
+ // New bundles derive adapters from their pinned engine's initializer. Keep the
+ // original two-client contract for older bundles that have no capability list.
+ const harnesses = pin.harnesses === undefined ? ['claude', 'codex'] : pin.harnesses;
+ if (
+ !Array.isArray(harnesses) ||
+ !harnesses.length ||
+ harnesses.some((name) => typeof name !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(name)) ||
+ new Set(harnesses).size !== harnesses.length
+ )
+ throw new Error('Invalid workspace harness capabilities in the plugin runtime pin.');
+ if (!harnesses.includes(harness))
+ throw new Error(`Choose a supported workspace harness: ${harnesses.join(', ')}.`);
const directory = await canonical(options.directory);
const data = await canonical(options.dataDirectory || defaultDataDirectory());
for (const [a, b] of [
@@ -260,7 +273,7 @@ export async function setupPluginWorkspace(options = {}) {
])
if (inside(a, b) || inside(b, a))
throw new Error('Keep workspace, runtime data and plugin cache in separate directories.');
- if (mode === 'create' && (await exists(directory))) {
+ if (mode === 'create' && !options.adopt && (await exists(directory))) {
if (!(await lstat(directory)).isDirectory() || (await readdir(directory)).length)
throw new Error(
'The workspace destination must be an empty directory; no existing files were changed.',
@@ -273,13 +286,22 @@ export async function setupPluginWorkspace(options = {}) {
{ name: pin.name, version: pin.version },
archive,
archiveHash,
- { ...options, mode },
+ { ...options, mode: mode === 'recover' ? 'check' : mode },
);
- const { createWorkspace } = await import(
+ const { createWorkspace, workspaceSetupCapabilities } = await import(
pathToFileURL(join(runtime, 'scripts/create-workspace.mjs')).href
);
+ if (options.adopt && workspaceSetupCapabilities?.projectAdoption !== 1)
+ throw new Error(
+ 'The pinned engine does not support project adoption. Use a plugin release that pins a supporting engine; no project files were changed.',
+ );
+ if (mode === 'recover' && workspaceSetupCapabilities?.recovery !== 1)
+ throw new Error(
+ 'The pinned engine does not support project recovery. No project files were changed.',
+ );
const workspace = await createWorkspace(directory, harness, {
installation: runtime,
+ ...(options.adopt ? { adopt: true } : {}),
...(mode === 'create' ? {} : { [mode]: true }),
...(options.skills ? { skills: options.skills } : {}),
});
@@ -302,9 +324,13 @@ export function parseSetupArguments(args) {
};
while (values.length) {
const flag = values.shift();
- if (['--check', '--upgrade', '--repair'].includes(flag)) {
- if (result.mode) throw new Error('Choose only one of --check, --upgrade or --repair.');
+ if (['--check', '--upgrade', '--repair', '--recover'].includes(flag)) {
+ if (result.mode)
+ throw new Error('Choose only one of --check, --upgrade, --repair or --recover.');
result.mode = flag.slice(2);
+ } else if (flag === '--adopt') {
+ if (result.adopt) throw new Error('Repeated option --adopt.');
+ result.adopt = true;
} else if (Object.hasOwn(valueFlags, flag)) {
const value = values.shift();
if (!value || value.startsWith('--')) throw new Error(`Missing value for ${flag}.`);
@@ -312,6 +338,8 @@ export function parseSetupArguments(args) {
result[valueFlags[flag]] = flag === '--skills' ? value.split(',') : value;
} else throw new Error(`Unknown option ${flag}.`);
}
+ if (result.mode === 'recover' && (result.adopt || result.skills))
+ throw new Error('Use --recover alone before retrying setup.');
return result;
}
@@ -323,7 +351,7 @@ if (
const options = parseSetupArguments(process.argv.slice(2));
if (options.help)
console.log(
- 'Usage: node bin/kiln-setup-workspace.mjs <directory> [--harness claude|codex] [--skills compose,batch]\n node bin/kiln-setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>',
+ 'Usage: node bin/kiln-setup-workspace.mjs <directory> [--harness NAME] [--skills compose,batch]\n node bin/kiln-setup-workspace.mjs <project-or-new-workspace> --adopt [--check]\n node bin/kiln-setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair|--recover\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>\nWorkspace adapters are declared by the pinned engine in runtime.json.',
);
else {
const result = await setupPluginWorkspace(options);
diff --git a/scripts/setup-plugin-workspace.test.mjs b/scripts/setup-plugin-workspace.test.mjs
index efef88f1..8e15f84a 100644
--- a/scripts/setup-plugin-workspace.test.mjs
+++ b/scripts/setup-plugin-workspace.test.mjs
@@ -80,6 +80,33 @@ test('plugin setup installs an exact package once outside the cache and delegate
expect(f.calls).toHaveLength(1);
});
+test.each(['opencode', 'hermes', 'agy', 'copilot', 'cursor-agent'])(
+ 'the plugin helper can register the engine-supported %s adapter',
+ async (harness) => {
+ const f = await fixture();
+ await writeFile(
+ join(f.options.pluginRoot, 'runtime.json'),
+ JSON.stringify({ ...f.pin, harnesses: ['claude', 'codex', harness] }),
+ );
+ const result = await setupPluginWorkspace({ ...f.options, harness });
+ expect(result.workspace.harness).toBe(harness);
+ expect(f.calls).toHaveLength(1);
+ },
+);
+
+test('invalid advertised adapters fail before installation or workspace changes', async () => {
+ const f = await fixture();
+ for (const harnesses of [[], ['claude', 'claude'], ['../other'], 'claude']) {
+ await writeFile(
+ join(f.options.pluginRoot, 'runtime.json'),
+ JSON.stringify({ ...f.pin, harnesses }),
+ );
+ await expect(setupPluginWorkspace(f.options)).rejects.toThrow('harness');
+ }
+ expect(f.calls).toHaveLength(0);
+ await expect(readdir(f.options.directory)).rejects.toMatchObject({ code: 'ENOENT' });
+});
+
test.each(['latest', '^1.0.0', '../other', 'file:/private', 'https://example.com/p.tgz'])(
'rejects a non-exact runtime pin %s before invoking npm',
async (version) => {
@@ -130,6 +157,46 @@ test('does not install or touch an existing nonempty directory when creation was
expect(f.calls).toHaveLength(0);
});
+test('explicit project adoption delegates to a capable pinned engine without touching owner files', async () => {
+ const f = await fixture();
+ await mkdir(f.options.directory);
+ await writeFile(join(f.options.directory, 'AGENTS.md'), 'Owner instructions');
+ const install = f.options.run;
+ const result = await setupPluginWorkspace({
+ ...f.options,
+ adopt: true,
+ run: async (...args) => {
+ await install(...args);
+ const module = join(args[1], 'node_modules/@instruktlabs/kiln/scripts/create-workspace.mjs');
+ await writeFile(
+ module,
+ (await readFile(module, 'utf8')) +
+ '\nexport const workspaceSetupCapabilities = {projectAdoption:1,recovery:1};\n',
+ );
+ },
+ });
+ expect(result.workspace.options.adopt).toBe(true);
+ expect(await readFile(join(f.options.directory, 'AGENTS.md'), 'utf8')).toBe('Owner instructions');
+});
+
+test('adoption never falls back to an older engine that can only create empty workspaces', async () => {
+ const f = await fixture();
+ await mkdir(f.options.directory);
+ await writeFile(join(f.options.directory, 'keep.txt'), 'owner');
+ await expect(setupPluginWorkspace({ ...f.options, adopt: true })).rejects.toThrow(
+ 'does not support project adoption',
+ );
+ expect(await readFile(join(f.options.directory, 'keep.txt'), 'utf8')).toBe('owner');
+ expect(await readdir(f.options.directory)).toEqual(['keep.txt']);
+});
+
+test('CLI can preview project adoption and cannot combine recovery with setup changes', () => {
+ expect(
+ parseSetupArguments(['/project', '--adopt', '--check', '--harness', 'codex']),
+ ).toMatchObject({ adopt: true, mode: 'check', harness: 'codex' });
+ expect(() => parseSetupArguments(['/project', '--adopt', '--recover'])).toThrow('recover');
+});
+
test('check is read-only when the pinned engine has not been installed', async () => {
const f = await fixture();
await expect(setupPluginWorkspace({ ...f.options, mode: 'check' })).rejects.toThrow(
diff --git a/scripts/smoke-package-adoption.mjs b/scripts/smoke-package-adoption.mjs
new file mode 100644
index 00000000..f7794282
--- /dev/null
+++ b/scripts/smoke-package-adoption.mjs
@@ -0,0 +1,122 @@
+/** Installed-package proof of project preservation and cross-client storage reuse. */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+export async function smokePackageAdoption({ runtime, root, command, connect, textResult }) {
+ const setup = join(runtime, 'scripts/create-workspace.mjs');
+ const { workspaceSetupCapabilities } = await import(pathToFileURL(setup).href);
+ const pkg = JSON.parse(await readFile(join(runtime, 'package.json'), 'utf8'));
+ const supportsAdoption = workspaceSetupCapabilities?.projectAdoption === 1;
+ assert.equal(
+ supportsAdoption,
+ pkg.files.includes('scripts/workspace-project.mjs'),
+ 'Installed adoption capability and package contents must agree',
+ );
+ // The public-registry matrix also qualifies immutable older releases. Report
+ // their missing feature explicitly; only a supporting candidate runs this gate.
+ if (!supportsAdoption) return { status: 'not-supported-by-this-release' };
+ const require = createRequire(join(runtime, 'package.json'));
+ const { parse } = await import(pathToFileURL(require.resolve('smol-toml')).href);
+ const project = join(root, 'existing project café');
+ const profile = join(root, 'adoption-profile');
+ const env = {
+ LOCALAPPDATA: profile,
+ XDG_DATA_HOME: profile,
+ KILN_COLLECTIONS: '',
+ KILN_PROJECT: '',
+ KILN_WORK_ITEM: 'package-adoption-proof',
+ };
+ await mkdir(project);
+ const ownerFiles = {
+ 'AGENTS.md': '# Existing project instructions\n',
+ 'CLAUDE.md': '# Existing Claude instructions\n',
+ 'README.md': '# Existing application\n',
+ };
+ for (const [name, bytes] of Object.entries(ownerFiles))
+ await writeFile(join(project, name), bytes);
+ await writeFile(
+ join(project, '.mcp.json'),
+ '{ "mcpServers": { "owner": { "command": "unused-fixture" } }, "ownerNumber": 9007199254740993 }\n',
+ );
+ const run = (...args) => command([setup, project, ...args], root, env);
+ assert.equal(JSON.parse(await run('--adopt', '--harness', 'claude')).status, 'current');
+ const claude = JSON.parse(await readFile(join(project, '.mcp.json'), 'utf8')).mcpServers
+ .kiln_workspace;
+ const sessionFor = (config) =>
+ connect(
+ config.args,
+ project,
+ config.env.KILN_PROGRAM_STORE,
+ { ...env, ...config.env },
+ config.command,
+ );
+ const tool = async (session, name, args) =>
+ textResult(await session.call('tools/call', { name, arguments: args }));
+ const source =
+ "const meta = { name: 'ContractCube', category: 'prop' };\n" +
+ "function build() { const root = createRoot('ContractCube');\n" +
+ "createPart('Body', boxGeo(1,1,1), gameMaterial(0x808080), {position:[0,0.5,0],parent:root});\n" +
+ 'return root; }\n';
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
+ let programRef, asset, sourceUri, glbUri, glbHash;
+ const first = await sessionFor(claude);
+ try {
+ assert.equal((await first.call('tools/list', {})).tools.length, 17);
+ programRef = (await tool(first, 'kiln_validate', { code: source })).programRef;
+ assert.equal(typeof programRef, 'string');
+ await tool(first, 'kiln_render', { programRef, capture: { preset: '1x1' } });
+ asset = (await tool(first, 'kiln_save', { programRef, name: 'ContractCube' })).asset;
+ assert.equal(asset.editable, true);
+ sourceUri = `kiln://assets/project/${asset.assetId}/${asset.revisionId}/source.kiln.js`;
+ glbUri = `kiln://assets/project/${asset.assetId}/${asset.revisionId}/asset.glb`;
+ assert.equal((await first.call('resources/read', { uri: sourceUri })).contents[0].text, source);
+ const glb = await first.call('resources/read', { uri: glbUri });
+ glbHash = hash(Buffer.from(glb.contents[0].blob, 'base64'));
+ } finally {
+ await first.close();
+ }
+ await run('--adopt', '--harness', 'codex');
+ const codex = parse(await readFile(join(project, '.codex/config.toml'), 'utf8')).mcp_servers
+ .kiln_workspace;
+ assert.equal(codex.env.KILN_PROGRAM_STORE, claude.env.KILN_PROGRAM_STORE);
+ const second = await sessionFor(codex);
+ try {
+ assert.equal((await second.call('tools/list', {})).tools.length, 17);
+ assert.match(
+ (await tool(second, 'kiln_source', { programRef, query: 'ContractCube' })).code,
+ /ContractCube/,
+ );
+ const restored = await tool(second, 'kiln_assets', {
+ action: 'restore',
+ collection: 'project',
+ assetId: asset.assetId,
+ revisionId: asset.revisionId,
+ });
+ assert.equal(restored.asset.revisionId, asset.revisionId);
+ assert.equal(
+ (await second.call('resources/read', { uri: sourceUri })).contents[0].text,
+ source,
+ );
+ const glb = await second.call('resources/read', { uri: glbUri });
+ assert.equal(hash(Buffer.from(glb.contents[0].blob, 'base64')), glbHash);
+ } finally {
+ await second.close();
+ }
+ const checked = JSON.parse(await run('--check'));
+ assert.equal(checked.status, 'current');
+ assert.deepEqual(checked.harnesses, ['claude', 'codex']);
+ for (const [name, bytes] of Object.entries(ownerFiles))
+ assert.equal(await readFile(join(project, name), 'utf8'), bytes);
+ assert((await readFile(join(project, '.mcp.json'), 'utf8')).includes('9007199254740993'));
+ return {
+ status: 'passed',
+ programRef,
+ assetId: asset.assetId,
+ revisionId: asset.revisionId,
+ glbSha256: glbHash,
+ };
+}
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index 101cedbd..f723a839 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -9,6 +9,7 @@ import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { smokePackageExporter } from './smoke-package-exporter.mjs';
import { smokeSdkTypes } from './smoke-sdk-types.mjs';
+import { smokePackageAdoption } from './smoke-package-adoption.mjs';
const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
// macOS exposes /var through /private/var. Match Node's canonical module URLs
@@ -77,11 +78,11 @@ async function npmCli() {
throw new Error('Run this check with npm run test:package so npm can locate its CLI.');
}
-async function connect(server, cwd, store) {
- const child = spawn(process.execPath, Array.isArray(server) ? server : [server], {
+async function connect(server, cwd, store, env = {}, executable = process.execPath) {
+ const child = spawn(executable, Array.isArray(server) ? server : [server], {
cwd,
windowsHide: true,
- env: { ...process.env, KILN_RENDER: 'cpu', KILN_PROGRAM_STORE: store },
+ env: { ...process.env, ...env, KILN_RENDER: 'cpu', KILN_PROGRAM_STORE: store },
stdio: ['pipe', 'pipe', 'pipe'],
});
let next = 0,
@@ -231,7 +232,16 @@ try {
);
assert.equal(portablePlugin.name, 'kiln-engine');
assert.equal((await pluginJson('.claude-plugin/plugin.json')).version, portablePlugin.version);
- assert.deepEqual(await pluginJson('runtime.json'), { name: pkg.name, version: pkg.version });
+ const { workspaceSetupCapabilities } = await import(
+ pathToFileURL(join(runtime, 'scripts/create-workspace.mjs')).href
+ );
+ assert.deepEqual(await pluginJson('runtime.json'), {
+ name: pkg.name,
+ version: pkg.version,
+ ...(workspaceSetupCapabilities?.harnesses
+ ? { harnesses: workspaceSetupCapabilities.harnesses }
+ : {}),
+ });
assert.deepEqual(await readdir(join(plugin, 'skills')), ['kiln-setup-workspace']);
const pluginReceipt = await pluginJson('package-provenance.json');
assert.equal(pluginReceipt.kind, 'kiln-local-plugin');
@@ -640,6 +650,15 @@ console.log(JSON.stringify({ renderBytes: result.glb.length }));
'server-restart-persistence',
'exact-source-export',
);
+ receipt.projectAdoption = await smokePackageAdoption({
+ runtime,
+ root,
+ command,
+ connect,
+ textResult,
+ });
+ if (receipt.projectAdoption.status === 'passed')
+ receipt.checks.push('installed-project-adoption-and-cross-client-storage');
receipt.status = 'passed';
} catch (error) {
receipt.status = 'failed';
diff --git a/scripts/verify-package-receipt.mjs b/scripts/verify-package-receipt.mjs
index dfe8830a..1162b3d4 100644
--- a/scripts/verify-package-receipt.mjs
+++ b/scripts/verify-package-receipt.mjs
@@ -62,6 +62,11 @@ export function receiptProblems(receipt, { platform, arch, manifest, toolchain,
for (const check of REQUIRED_CHECKS) {
if (!receipt.checks?.includes(check)) problems.push(`missing check: ${check}`);
}
+ if (manifest.files?.includes('scripts/workspace-project.mjs')) {
+ const check = 'installed-project-adoption-and-cross-client-storage';
+ if (!receipt.checks?.includes(check)) problems.push(`missing check: ${check}`);
+ mustBe(receipt.projectAdoption?.status, 'passed', 'projectAdoption.status');
+ }
return problems;
}
diff --git a/scripts/verify-package-receipt.test.mjs b/scripts/verify-package-receipt.test.mjs
index e92e4dae..8aa1b1d0 100644
--- a/scripts/verify-package-receipt.test.mjs
+++ b/scripts/verify-package-receipt.test.mjs
@@ -83,6 +83,30 @@ describe('package receipt verification', () => {
expect(receiptProblems({ ...good(), checks: undefined }, target)).toHaveLength(12);
});
+ test('a package shipping project adoption requires its installed storage-reuse proof', () => {
+ const candidate = {
+ ...target,
+ manifest: { ...manifest, files: ['scripts/workspace-project.mjs'] },
+ };
+ expect(receiptProblems(good(), candidate)).toContain(
+ 'missing check: installed-project-adoption-and-cross-client-storage',
+ );
+ const receipt = good();
+ receipt.checks.push('installed-project-adoption-and-cross-client-storage');
+ expect(
+ receiptProblems(
+ { ...receipt, projectAdoption: { status: 'not-supported-by-this-release' } },
+ candidate,
+ ),
+ ).toContain(
+ 'projectAdoption.status: expected passed, receipt says not-supported-by-this-release',
+ );
+ expect(
+ receiptProblems({ ...receipt, projectAdoption: { status: 'passed' } }, candidate),
+ ).toEqual([]);
+ expect(receiptProblems(good(), target)).toEqual([]);
+ });
+
test.each([
'installed-consumer-documents',
'plain-node-sdk-exports',
diff --git a/scripts/workspace-adoption.test.mjs b/scripts/workspace-adoption.test.mjs
new file mode 100644
index 00000000..5196d1f3
--- /dev/null
+++ b/scripts/workspace-adoption.test.mjs
@@ -0,0 +1,334 @@
+import { expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { spawnSync } from 'node:child_process';
+import {
+ cp,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ realpath,
+ rename,
+ rm,
+ rmdir,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve, sep } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const repo = resolve(import.meta.dir, '..');
+const entry = pathToFileURL(join(repo, 'scripts/create-workspace.mjs')).href;
+const sha = (value) => createHash('sha256').update(value).digest('hex');
+const put = async (root, name, value) => {
+ await mkdir(dirname(join(root, name)), { recursive: true });
+ await writeFile(join(root, name), value);
+};
+async function cleanup(temp) {
+ const actual = await realpath(temp),
+ parent = await realpath(tmpdir());
+ if (
+ !actual.startsWith(parent + sep) ||
+ !actual.slice(parent.length + 1).startsWith('kiln-adopt-')
+ )
+ throw new Error('Unsafe fixture cleanup.');
+ await rm(actual, { recursive: true, force: true });
+}
+async function fixture(fn) {
+ const temp = await realpath(await mkdtemp(join(tmpdir(), 'kiln-adopt-')));
+ const runtime = join(temp, 'runtime'),
+ root = join(temp, 'project'),
+ stateDirectory = join(temp, 'private-state');
+ await mkdir(root);
+ const entries = {};
+ for (const [key, name] of [
+ ['cli', 'cli.mjs'],
+ ['mcp', 'mcp-server.mjs'],
+ ['engine', 'mcp-engine.mjs'],
+ ['worker', 'evaluator-worker.mjs'],
+ ]) {
+ const source = 'export function main() {}\n';
+ await put(runtime, `dist/${name}`, source);
+ entries[key] = { identity: `sha256:${sha('fixture')}`, bundleHash: `sha256:${sha(source)}` };
+ }
+ await put(runtime, 'package.json', '{"name":"@instruktlabs/kiln","version":"1.0.0"}');
+ await put(runtime, 'dist/build.json', JSON.stringify({ schemaVersion: 1, entries }));
+ for (const skill of ['author', 'refine', 'qa', 'compose-scene', 'batch-dispatch']) {
+ const name = skill.includes('-') ? `kiln-${skill}` : `kiln-${skill}-asset`;
+ await put(runtime, `skills/${name}/SKILL.md`, `# ${name}\n`);
+ }
+ const run = (harness = 'claude', options = {}, destination = root) =>
+ spawnSync(
+ 'node',
+ [
+ '--input-type=module',
+ '-e',
+ `import {createWorkspace} from ${JSON.stringify(entry)}; try { console.log(JSON.stringify(await createWorkspace(process.argv[1],process.argv[3],JSON.parse(process.argv[2])))); } catch(error) { console.error(error.message); process.exitCode=1; }`,
+ destination,
+ JSON.stringify({ installation: runtime, stateDirectory, adopt: true, ...options }),
+ harness,
+ ],
+ { encoding: 'utf8', timeout: 15000, windowsHide: true },
+ );
+ try {
+ await fn({ root, runtime, temp, stateDirectory, run });
+ } finally {
+ await cleanup(temp);
+ }
+}
+const json = async (root, name) => JSON.parse(await readFile(join(root, name), 'utf8'));
+const passed = (result) => {
+ expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' });
+ return JSON.parse(result.stdout);
+};
+
+test('adopts an existing project without replacing instructions, another MCP server or assets', () =>
+ fixture(async ({ root, run }) => {
+ await put(root, 'AGENTS.md', '# Owner project rules\n');
+ await put(root, 'CLAUDE.md', '# Owner Claude rules\n');
+ await put(
+ root,
+ '.mcp.json',
+ '{ "mcpServers": { "other": { "command": "other", "env": { "API_KEY": "synthetic-owner-key" } } }, "owner": 9007199254740993 }\n',
+ );
+ await put(root, 'assets/source.kiln.js', '// owned asset');
+ const report = passed(run());
+ expect(report.status).toBe('current');
+ expect(report.harnesses).toEqual(['claude']);
+ expect(await readFile(join(root, 'AGENTS.md'), 'utf8')).toBe('# Owner project rules\n');
+ expect(await readFile(join(root, 'CLAUDE.md'), 'utf8')).toBe('# Owner Claude rules\n');
+ expect(await readFile(join(root, 'assets/source.kiln.js'), 'utf8')).toBe('// owned asset');
+ const config = await json(root, '.mcp.json');
+ expect(config.mcpServers.other.env.API_KEY).toBe('synthetic-owner-key');
+ expect(config.mcpServers.kiln_workspace.env.KILN_PROGRAM_STORE).toBe(
+ join(root, '.kiln', 'programs'),
+ );
+ expect(await readFile(join(root, '.mcp.json'), 'utf8')).toContain('9007199254740993');
+ const manifest = await readFile(join(root, '.kiln/workspace.json'), 'utf8');
+ expect(manifest).not.toContain('synthetic-owner-key');
+ expect(JSON.stringify(report)).not.toContain('synthetic-owner-key');
+ expect((await json(root, '.kiln/workspace.json')).schemaVersion).toBe(2);
+ expect(
+ await readFile(join(root, '.claude/skills/kiln-author-asset/SKILL.md'), 'utf8'),
+ ).toContain('kiln-author-asset');
+ }));
+
+test('adds Codex around the same store and keeps unrelated TOML settings byte-for-byte', () =>
+ fixture(async ({ root, run }) => {
+ passed(run());
+ await put(root, '.kiln/programs/owner-source.txt', 'source retained');
+ const prefix =
+ '# owner settings\nmodel = "owner-choice"\n[mcp_servers.other]\ncommand = "other"\n';
+ await put(root, '.codex/config.toml', prefix);
+ const report = passed(run('codex'));
+ expect(report.harnesses).toEqual(['claude', 'codex']);
+ expect(await readFile(join(root, '.codex/config.toml'), 'utf8')).toStartWith(prefix);
+ expect(await readFile(join(root, '.kiln/programs/owner-source.txt'), 'utf8')).toBe(
+ 'source retained',
+ );
+ expect(await readFile(join(root, '.claude/skills/kiln-author-asset/SKILL.md'), 'utf8')).toBe(
+ await readFile(join(root, '.agents/skills/kiln-author-asset/SKILL.md'), 'utf8'),
+ );
+ expect(passed(run('codex')).changed).toEqual([]);
+ expect(passed(run('claude', { adopt: false, check: true })).status).toBe('current');
+ }));
+
+test('check previews adoption without creating a manifest, configuration or recovery storage', () =>
+ fixture(async ({ root, stateDirectory, run }) => {
+ await put(root, 'AGENTS.md', 'owner');
+ const report = passed(run('codex', { check: true }));
+ expect(report.status).toBe('update-required');
+ expect(report.files.some((file) => file.path === '.codex/config.toml')).toBe(true);
+ expect(await readdir(root)).toEqual(['AGENTS.md']);
+ await expect(readdir(stateDirectory)).rejects.toMatchObject({ code: 'ENOENT' });
+ }));
+
+test('conflicting MCP ownership fails before any project file is installed', () =>
+ fixture(async ({ root, run }) => {
+ const original =
+ '{"mcpServers":{"kiln_workspace":{"command":"owner-server","env":{"TOKEN":"synthetic-private-token"}}}}';
+ await put(root, '.mcp.json', original);
+ const result = run();
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('conflict');
+ expect(result.stderr).not.toContain('synthetic-private-token');
+ expect(await readdir(root)).toEqual(['.mcp.json']);
+ expect(await readFile(join(root, '.mcp.json'), 'utf8')).toBe(original);
+ }));
+
+test('maintenance tolerates unrelated config edits and preserves customized unchanged skills', () =>
+ fixture(async ({ root, run }) => {
+ passed(run());
+ const config = await json(root, '.mcp.json');
+ config.mcpServers.owner = { command: 'owner' };
+ await put(root, '.mcp.json', JSON.stringify(config));
+ await put(root, 'skills/kiln-author-asset/SKILL.md', '# Owner skill customization\n');
+ const report = passed(run('claude', { adopt: false, check: true }));
+ expect(report.status).toBe('current');
+ expect(report.files).toContainEqual({
+ path: 'skills/kiln-author-asset/SKILL.md',
+ status: 'customized',
+ });
+ passed(run('claude', { adopt: false, upgrade: true }));
+ expect((await json(root, '.mcp.json')).mcpServers.owner.command).toBe('owner');
+ expect(await readFile(join(root, 'skills/kiln-author-asset/SKILL.md'), 'utf8')).toContain(
+ 'Owner skill',
+ );
+ }));
+
+test('an explicit legacy migration retains saved assets and allows a second integration', () =>
+ fixture(async ({ root, run }) => {
+ passed(run('claude', { adopt: false }));
+ const first = await json(root, '.kiln/workspace.json');
+ expect(first.schemaVersion).toBe(1);
+ await put(root, '.kiln/programs/preserved.txt', 'original');
+ passed(run('codex'));
+ expect((await json(root, '.kiln/workspace.json')).harnesses).toEqual(['claude', 'codex']);
+ expect(await readFile(join(root, '.kiln/programs/preserved.txt'), 'utf8')).toBe('original');
+ expect(passed(run('codex', { adopt: false, check: true })).status).toBe('current');
+ }));
+
+test('adopting a copied legacy OpenCode workspace replaces only its owned old skill path', () =>
+ fixture(async ({ root, temp, run }) => {
+ passed(run('opencode', { adopt: false }));
+ const originalConfig = await readFile(join(root, 'opencode.json'));
+ const originalManifest = await readFile(join(root, '.kiln/workspace.json'));
+ await put(root, '.kiln/programs/retained.txt', 'saved source');
+ const moved = join(temp, 'copied-project');
+ await cp(root, moved, { recursive: true });
+ passed(run('opencode', {}, moved));
+ const config = await json(moved, 'opencode.json');
+ expect(config.skills.paths).toEqual([join(moved, 'skills')]);
+ expect(config.mcp.kiln_workspace.environment.KILN_PROGRAM_STORE).toBe(
+ join(moved, '.kiln/programs'),
+ );
+ expect(await readFile(join(moved, '.kiln/programs/retained.txt'), 'utf8')).toBe('saved source');
+ expect(await readFile(join(root, 'opencode.json'))).toEqual(originalConfig);
+ expect(await readFile(join(root, '.kiln/workspace.json'))).toEqual(originalManifest);
+ expect(passed(run('opencode', {}, moved)).changed).toEqual([]);
+ }));
+
+test('the same adoption path creates a new workspace with optional skills', () =>
+ fixture(async ({ root, run }) => {
+ const report = passed(run('codex', { skills: ['compose'] }));
+ expect(report.status).toBe('current');
+ expect(await readFile(join(root, 'AGENTS.md'), 'utf8')).toContain('Kiln asset workspace');
+ expect(await readFile(join(root, 'skills/kiln-compose-scene/SKILL.md'), 'utf8')).toContain(
+ 'compose-scene',
+ );
+ expect((await json(root, '.kiln/workspace.json')).skills).toContain('kiln-compose-scene');
+ }));
+
+test('repair updates every registered runtime path after relocation without rewriting source', () =>
+ fixture(async ({ root, temp, runtime, run, stateDirectory }) => {
+ passed(run());
+ passed(run('codex'));
+ await put(root, '.kiln/programs/retained.txt', 'original');
+ const moved = join(temp, 'moved-runtime');
+ await rename(runtime, moved);
+ passed(run('claude', { adopt: false, repair: true, installation: moved, stateDirectory }));
+ expect((await json(root, '.mcp.json')).mcpServers.kiln_workspace.args[0]).toBe(
+ join(moved, 'dist', 'mcp-server.mjs'),
+ );
+ expect(await readFile(join(root, '.codex/config.toml'), 'utf8')).toContain(
+ JSON.stringify(join(moved, 'dist', 'mcp-server.mjs')),
+ );
+ expect(await readFile(join(root, '.kiln/programs/retained.txt'), 'utf8')).toBe('original');
+ }));
+
+test('repair preserves copied skills until an explicit upgrade adopts the new source', () =>
+ fixture(async ({ root, runtime, run }) => {
+ passed(run());
+ await put(runtime, 'skills/kiln-author-asset/SKILL.md', '# New release guidance\n');
+ passed(run('claude', { adopt: false, repair: true }));
+ expect(await readFile(join(root, 'skills/kiln-author-asset/SKILL.md'), 'utf8')).toBe(
+ '# kiln-author-asset\n',
+ );
+ expect(passed(run('claude', { adopt: false, check: true })).status).toBe('update-required');
+ passed(run('claude', { adopt: false, upgrade: true }));
+ expect(await readFile(join(root, 'skills/kiln-author-asset/SKILL.md'), 'utf8')).toBe(
+ '# New release guidance\n',
+ );
+ }));
+
+test('OpenCode keeps other skill paths and servers while adopting only its Kiln entries', () =>
+ fixture(async ({ root, run }) => {
+ await put(
+ root,
+ 'opencode.json',
+ '{ // owner comment\n "skills":{"paths":["./owner-skills"]}, "mcp":{"other":{"type":"local","command":["other"]}} }',
+ );
+ passed(run('opencode'));
+ const raw = await readFile(join(root, 'opencode.json'), 'utf8');
+ expect(raw).toContain('// owner comment');
+ expect(raw).toContain('./owner-skills');
+ expect(raw).toContain('"other"');
+ expect(passed(run('opencode', { adopt: false, check: true })).status).toBe('current');
+ }));
+
+test('untrusted manifest paths cannot delete or read a project asset during upgrade', () =>
+ fixture(async ({ root, run }) => {
+ passed(run());
+ await put(root, 'assets/keep.txt', 'owner asset');
+ const manifest = await json(root, '.kiln/workspace.json');
+ manifest.ownedFiles['assets/keep.txt'] = sha('owner asset');
+ await put(root, '.kiln/workspace.json', JSON.stringify(manifest));
+ const result = run('claude', { adopt: false, upgrade: true });
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('Invalid managed-file manifest');
+ expect(await readFile(join(root, 'assets/keep.txt'), 'utf8')).toBe('owner asset');
+ }));
+
+test('invalid UTF-8 config fails without replacing its original bytes', () =>
+ fixture(async ({ root, run }) => {
+ const original = Buffer.from([123, 34, 120, 34, 58, 34, 255, 34, 125]);
+ await put(root, '.mcp.json', original);
+ expect(run().status).toBe(1);
+ expect(await readFile(join(root, '.mcp.json'))).toEqual(original);
+ expect(await readdir(root)).toEqual(['.mcp.json']);
+ }));
+
+test('adoption validates and creates a previously missing directory, while check stays read-only', () =>
+ fixture(async ({ root, run }) => {
+ await rmdir(root);
+ expect(passed(run('claude', { check: true })).status).toBe('update-required');
+ await expect(readdir(root)).rejects.toMatchObject({ code: 'ENOENT' });
+ passed(run());
+ expect((await json(root, '.kiln/workspace.json')).schemaVersion).toBe(2);
+ }));
+
+test('adoption previews optional skill selection and rejects corrupt manifests before writing', () =>
+ fixture(async ({ root, run }) => {
+ const report = passed(run('codex', { check: true, skills: ['compose'] }));
+ expect(report.files.some((file) => file.path === 'skills/kiln-compose-scene/SKILL.md')).toBe(
+ true,
+ );
+ expect(await readdir(root)).toEqual([]);
+ await put(root, '.kiln/workspace.json', 'null');
+ expect(run().status).toBe(1);
+ expect(await readdir(root)).toEqual(['.kiln']);
+ }));
+
+test('malformed manifest lists stop with a clear error and leave owned files intact', () =>
+ fixture(async ({ root, run }) => {
+ passed(run());
+ const manifest = await json(root, '.kiln/workspace.json');
+ const config = await readFile(join(root, '.mcp.json'));
+ const skill = await readFile(join(root, 'skills/kiln-author-asset/SKILL.md'));
+ for (const [patch, message] of [
+ [{ skills: {} }, 'Invalid workspace skill manifest'],
+ [{ skills: [] }, 'Invalid workspace skill manifest'],
+ [{ skills: [...manifest.skills, manifest.skills[0]] }, 'Invalid workspace skill manifest'],
+ [{ harnesses: {} }, 'Invalid workspace harness manifest'],
+ [{ harnesses: ['codex'] }, 'Invalid workspace harness manifest'],
+ ]) {
+ const bytes = JSON.stringify({ ...manifest, ...patch });
+ await put(root, '.kiln/workspace.json', bytes);
+ const result = run('claude', { adopt: false, upgrade: true });
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain(message);
+ expect(await readFile(join(root, '.kiln/workspace.json'), 'utf8')).toBe(bytes);
+ expect(await readFile(join(root, '.mcp.json'))).toEqual(config);
+ expect(await readFile(join(root, 'skills/kiln-author-asset/SKILL.md'))).toEqual(skill);
+ }
+ }));
diff --git a/scripts/workspace-config.mjs b/scripts/workspace-config.mjs
new file mode 100644
index 00000000..b0a1c982
--- /dev/null
+++ b/scripts/workspace-config.mjs
@@ -0,0 +1,239 @@
+/** Shared configuration edits for local project integrations. Never writes files. */
+import { isDeepStrictEqual } from 'node:util';
+import { applyEdits, getNodeValue, modify, parseTree } from 'jsonc-parser';
+import { parse as parseToml } from 'smol-toml';
+
+const maxLength = 2 * 1024 * 1024;
+const forbidden = new Set(['__proto__', 'prototype', 'constructor']);
+const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
+const conflict = (path) =>
+ new Error(`Configuration conflict at ${path.join('.')}; no files were changed.`);
+
+function checkPath(path) {
+ if (
+ !Array.isArray(path) ||
+ !path.length ||
+ path.length > 16 ||
+ path.some(
+ (part) => typeof part !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(part) || forbidden.has(part),
+ )
+ )
+ throw new Error('Invalid configuration path.');
+}
+
+function checkText(text, kind) {
+ if (typeof text !== 'string' || text.length > maxLength)
+ throw new Error(`Invalid ${kind} configuration.`);
+}
+
+function jsonTree(text, comments) {
+ checkText(text, 'JSON');
+ try {
+ const errors = [];
+ const root = parseTree(text, errors, {
+ disallowComments: !comments,
+ allowTrailingComma: comments,
+ });
+ if (errors.length || root?.type !== 'object') throw new Error();
+ let count = 0;
+ const visit = (node, depth = 0) => {
+ if (++count > 100000 || depth > 64) throw new Error();
+ if (node.type === 'object') {
+ const keys = new Set();
+ for (const property of node.children ?? []) {
+ const key = property.children[0].value;
+ if (keys.has(key)) throw new Error();
+ keys.add(key);
+ }
+ }
+ for (const child of node.children ?? []) visit(child, depth + 1);
+ };
+ visit(root);
+ return root;
+ } catch {
+ // Parser messages can include source lines containing user credentials.
+ throw new Error('Invalid JSON configuration.');
+ }
+}
+
+function jsonEntry(root, path) {
+ let node = root;
+ for (const part of path) {
+ if (node === undefined) return undefined;
+ if (node.type !== 'object') throw conflict(path);
+ node = node.children?.find((property) => property.children[0].value === part)?.children[1];
+ }
+ return node;
+}
+
+function jsonValue(value) {
+ try {
+ const serialized = JSON.stringify(value);
+ if (serialized === undefined || !isDeepStrictEqual(JSON.parse(serialized), value))
+ throw new Error();
+ jsonTree(`{"value":${serialized}}`, false);
+ return value;
+ } catch {
+ throw new Error('Invalid configuration value.');
+ }
+}
+
+function equalJson(a, b) {
+ if (Object.is(a, b)) return true;
+ if (
+ !a ||
+ !b ||
+ typeof a !== 'object' ||
+ typeof b !== 'object' ||
+ Array.isArray(a) !== Array.isArray(b)
+ )
+ return false;
+ const keys = Object.keys(a);
+ return (
+ keys.length === Object.keys(b).length &&
+ keys.every((key) => Object.hasOwn(b, key) && equalJson(a[key], b[key]))
+ );
+}
+
+function checkOwnedNumbers(node, path) {
+ if (
+ node.type === 'number' &&
+ (!Number.isFinite(node.value) ||
+ (Number.isInteger(node.value) && !Number.isSafeInteger(node.value)))
+ )
+ throw conflict(path);
+ for (const child of node.children ?? []) checkOwnedNumbers(child, path);
+}
+
+/** Apply non-overlapping owned entries; unrelated JSON bytes are not reserialized. */
+export function mergeJsonConfig(text, changes, { comments = false } = {}) {
+ checkText(text, 'JSON');
+ if (!Array.isArray(changes) || changes.length > 64)
+ throw new Error('Invalid configuration edits.');
+ for (const change of changes) {
+ checkPath(change?.path);
+ jsonValue(change.value);
+ if (Object.hasOwn(change, 'previous')) jsonValue(change.previous);
+ }
+ for (let i = 0; i < changes.length; i++)
+ for (let j = i + 1; j < changes.length; j++) {
+ const a = changes[i].path,
+ b = changes[j].path;
+ if (a.slice(0, Math.min(a.length, b.length)).every((part, k) => part === b[k]))
+ throw new Error('Overlapping configuration edits.');
+ }
+ let result = text.trim() ? text : `${text}{}\n`;
+ let root = jsonTree(result, comments);
+ for (const change of changes) {
+ const node = jsonEntry(root, change.path);
+ if (node !== undefined) {
+ checkOwnedNumbers(node, change.path);
+ const current = getNodeValue(node);
+ if (equalJson(current, change.value)) continue;
+ if (!Object.hasOwn(change, 'previous') || !equalJson(current, change.previous))
+ throw conflict(change.path);
+ }
+ // No whole-document formatter: preserve comments, large numbers and unrelated bytes.
+ result = applyEdits(result, modify(result, change.path, change.value, {}));
+ root = jsonTree(result, comments);
+ }
+ return result;
+}
+
+function toml(text) {
+ checkText(text, 'TOML');
+ try {
+ return parseToml(text, { integersAsBigInt: true });
+ } catch {
+ throw new Error('Invalid TOML configuration.');
+ }
+}
+
+function entry(root, path) {
+ let value = root;
+ for (const part of path) {
+ if (!object(value)) throw conflict(path);
+ if (!Object.hasOwn(value, part)) return undefined;
+ value = value[part];
+ }
+ return value;
+}
+
+function withoutEntry(root, path) {
+ const result = { ...root };
+ const [key, ...rest] = path;
+ if (Object.hasOwn(result, key)) {
+ if (!rest.length) delete result[key];
+ else {
+ result[key] = withoutEntry(result[key], rest);
+ if (!Object.keys(result[key]).length) delete result[key];
+ }
+ }
+ return result;
+}
+
+function fragmentValue(fragment, path) {
+ const parsed = toml(fragment);
+ const value = entry(parsed, path);
+ if (
+ !object(value) ||
+ !Object.keys(value).length ||
+ Object.keys(withoutEntry(parsed, path)).length
+ )
+ throw new Error('Invalid managed TOML fragment.');
+ return value;
+}
+
+function markerLines(text, marker) {
+ const offsets = [];
+ let offset = 0;
+ for (const line of text.split('\n')) {
+ if (line.replace(/\r$/, '') === marker) offsets.push(offset);
+ offset += line.length + 1;
+ }
+ return offsets;
+}
+
+/** TOML is preserved verbatim outside a validated, exclusively owned table block. */
+export function mergeTomlConfig(text, { path, fragment, previous } = {}) {
+ checkPath(path);
+ const original = toml(text);
+ const desired = fragmentValue(fragment, path);
+ if (previous !== undefined) fragmentValue(previous, path);
+ const start = `# BEGIN KILN ${JSON.stringify(path)}`;
+ const end = `# END KILN ${JSON.stringify(path)}`;
+ const starts = markerLines(text, start),
+ ends = markerLines(text, end);
+ const newline = text.includes('\r\n') ? '\r\n' : '\n';
+ const block = (value) =>
+ `${start}${newline}${value.replace(/\r\n/g, '\n').trim().replace(/\n/g, newline)}${newline}${end}${newline}`;
+ let prefix = text,
+ suffix = '',
+ base = original;
+ if (starts.length || ends.length) {
+ if (starts.length !== 1 || ends.length !== 1 || starts[0] >= ends[0]) throw conflict(path);
+ const afterLine = text.indexOf('\n', ends[0]);
+ const after = afterLine < 0 ? text.length : afterLine + 1;
+ if (text.slice(starts[0], after) !== block(previous ?? fragment)) throw conflict(path);
+ prefix = text.slice(0, starts[0]);
+ suffix = text.slice(after);
+ base = toml(prefix + suffix);
+ if (
+ entry(base, path) !== undefined ||
+ !isDeepStrictEqual(entry(original, path), fragmentValue(previous ?? fragment, path)) ||
+ !isDeepStrictEqual(withoutEntry(original, path), withoutEntry(base, path))
+ )
+ throw conflict(path);
+ } else {
+ if (entry(original, path) !== undefined) throw conflict(path);
+ if (prefix && !prefix.endsWith('\n')) prefix += newline;
+ }
+ const result = prefix + block(fragment) + suffix;
+ const parsed = toml(result);
+ if (
+ !isDeepStrictEqual(entry(parsed, path), desired) ||
+ !isDeepStrictEqual(withoutEntry(parsed, path), withoutEntry(base, path))
+ )
+ throw conflict(path);
+ return result;
+}
diff --git a/scripts/workspace-config.test.mjs b/scripts/workspace-config.test.mjs
new file mode 100644
index 00000000..65ce936c
--- /dev/null
+++ b/scripts/workspace-config.test.mjs
@@ -0,0 +1,234 @@
+import { describe, expect, test } from 'bun:test';
+import { mergeJsonConfig, mergeTomlConfig } from './workspace-config.mjs';
+
+const server = { command: '/node', args: ['/kiln/mcp.mjs'], env: { KILN_WORKSPACE: '/game' } };
+const change = { path: ['mcpServers', 'kiln_workspace'], value: server };
+
+describe('project JSON configuration ownership', () => {
+ test('adds only Kiln while preserving unrelated servers, settings, comments and numeric spelling', () => {
+ const source =
+ '{\r\n // Project configuration\r\n "model": "owner-choice",\r\n "budget": 9007199254740993,\r\n "mcpServers": {\r\n "other": { "command": "other-cli", "env": { "TOKEN": "private-fixture" } }\r\n }\r\n}\r\n';
+ const result = mergeJsonConfig(source, [change], { comments: true });
+ expect(result).toContain('// Project configuration\r\n');
+ expect(result).toContain('"budget": 9007199254740993');
+ expect(result).toContain(
+ '"other": { "command": "other-cli", "env": { "TOKEN": "private-fixture" } }',
+ );
+ expect(result).toContain('"model": "owner-choice"');
+ expect(result).toContain('"kiln_workspace"');
+ expect(result.replaceAll('\r\n', '')).not.toContain('\n');
+ expect(mergeJsonConfig(result, [change], { comments: true })).toBe(result);
+ });
+
+ test('replaces only a previously owned entry, tolerating independent project edits', () => {
+ const source = JSON.stringify({
+ model: 'new-choice',
+ mcpServers: { other: { url: 'https://example.test/mcp' }, kiln_workspace: server },
+ });
+ const updated = { ...server, args: ['/new/kiln/mcp.mjs'] };
+ const result = JSON.parse(
+ mergeJsonConfig(source, [{ ...change, value: updated, previous: server }]),
+ );
+ expect(result.model).toBe('new-choice');
+ expect(result.mcpServers.other).toEqual({ url: 'https://example.test/mcp' });
+ expect(result.mcpServers.kiln_workspace).toEqual(updated);
+ });
+
+ test('refuses a conflicting server or non-object parent without leaking values', () => {
+ for (const source of [
+ '{"mcpServers":{"kiln_workspace":{"token":"private-fixture"}}}',
+ '{"mcpServers":["private-fixture"]}',
+ '{"mcpServers":null}',
+ ]) {
+ let message;
+ try {
+ mergeJsonConfig(source, [change]);
+ } catch (error) {
+ message = error.message;
+ }
+ expect(message).toMatch(/conflict.*mcpServers/i);
+ expect(message).not.toContain('private-fixture');
+ }
+ });
+
+ test('refuses modified owned entries and never overwrites unknown fields in them', () => {
+ const source = JSON.stringify({
+ mcpServers: { kiln_workspace: { ...server, enabled: false } },
+ });
+ expect(() =>
+ mergeJsonConfig(source, [
+ { ...change, previous: server, value: { ...server, command: '/new-node' } },
+ ]),
+ ).toThrow(/conflict/i);
+ });
+
+ test('rejects malformed, duplicate, ambiguous and unsafe paths with sanitized errors', () => {
+ for (const source of [
+ '{"private-fixture":',
+ '{"mcpServers":{},"mcpServers":{}}',
+ '{"mcpServers":{"kiln_workspace":{},"kiln_\\u0077orkspace":{}}}',
+ '[]',
+ '{"a":1,}',
+ '// private-fixture\n{}',
+ ]) {
+ let message;
+ try {
+ mergeJsonConfig(source, [change]);
+ } catch (error) {
+ message = error.message;
+ }
+ expect(message).toMatch(/invalid.*configuration/i);
+ expect(message).not.toContain('private-fixture');
+ }
+ for (const path of [
+ [],
+ ['__proto__', 'polluted'],
+ ['constructor', 'prototype'],
+ ['mcpServers', 0],
+ ])
+ expect(() => mergeJsonConfig('{}', [{ path, value: true }])).toThrow(/invalid.*path/i);
+ expect({}.polluted).toBeUndefined();
+ });
+
+ test('rejects overlapping edits and leaves input unchanged when a later edit conflicts', () => {
+ const source = '{"owned":{"value":1}}';
+ expect(() => mergeJsonConfig(source, [change, { path: ['owned'], value: 2 }])).toThrow(
+ /conflict/i,
+ );
+ expect(source).toBe('{"owned":{"value":1}}');
+ expect(() => mergeJsonConfig('{}', [change, { path: ['mcpServers'], value: {} }])).toThrow(
+ /overlap/i,
+ );
+ });
+
+ test('rejects lossy owned numbers, unsupported desired values and oversized input', () => {
+ for (const source of ['{"owned":9007199254740993}', '{"owned":1e999}'])
+ expect(() => mergeJsonConfig(source, [{ path: ['owned'], value: 9007199254740992 }])).toThrow(
+ /conflict/i,
+ );
+ for (const value of [
+ undefined,
+ Number.NaN,
+ Infinity,
+ () => {},
+ new Date(0),
+ { nested: undefined },
+ ])
+ expect(() => mergeJsonConfig('{}', [{ path: ['owned'], value }])).toThrow(
+ /invalid configuration value/i,
+ );
+ expect(() => mergeJsonConfig(' '.repeat(2 * 1024 * 1024 + 1), [change])).toThrow(
+ /^Invalid JSON configuration\.$/,
+ );
+ });
+
+ test('preserves unrelated prototype-like keys without mutating object prototypes', () => {
+ const source = '{"__proto__":{"owner":"keep"},"constructor":{"prototype":"keep"}}';
+ const result = mergeJsonConfig(source, [change]);
+ expect(Object.getOwnPropertyDescriptor(JSON.parse(result), '__proto__')?.value).toEqual({
+ owner: 'keep',
+ });
+ expect(JSON.parse(result).constructor).toEqual({ prototype: 'keep' });
+ expect({}.owner).toBeUndefined();
+ });
+
+ test('supports empty files, trailing commas when allowed, and multiple independent entries', () => {
+ expect(JSON.parse(mergeJsonConfig('', [change])).mcpServers.kiln_workspace).toEqual(server);
+ const source = '{\n "model": "owner-choice",\n}\n';
+ const result = mergeJsonConfig(
+ source,
+ [change, { path: ['skills', 'paths'], value: ['/game/skills'] }],
+ { comments: true },
+ );
+ expect(result).toContain('"model": "owner-choice"');
+ expect(mergeJsonConfig(result, [change], { comments: true })).toBe(result);
+ });
+});
+
+const tomlPath = ['mcp_servers', 'kiln_workspace'];
+const fragment =
+ '[mcp_servers.kiln_workspace]\ncommand = "/node"\nargs = ["/kiln/mcp.mjs"]\n[mcp_servers.kiln_workspace.env]\nKILN_WORKSPACE = "/game"\n';
+
+describe('project TOML configuration ownership', () => {
+ test('preserves existing configuration byte-for-byte while adding a validated Kiln table', () => {
+ const source =
+ '# Owner comment\r\nmodel = "owner-choice"\r\nlimit = 9223372036854775807\r\n[mcp_servers."other"]\r\nurl = "https://example.test/mcp"\r\n';
+ const result = mergeTomlConfig(source, { path: tomlPath, fragment });
+ expect(result.startsWith(source)).toBe(true);
+ expect(result).toContain('[mcp_servers.kiln_workspace]');
+ expect(result.replaceAll('\r\n', '')).not.toContain('\n');
+ expect(mergeTomlConfig(result, { path: tomlPath, fragment, previous: fragment })).toBe(result);
+ });
+
+ test('updates the owned block while preserving before/after user content', () => {
+ const initial = mergeTomlConfig('model = "owner-choice"\n', { path: tomlPath, fragment });
+ const suffix = '\n[owner]\nnote = "keep this"\n';
+ const result = mergeTomlConfig(initial + suffix, {
+ path: tomlPath,
+ fragment: fragment.replace('/node', '/new-node'),
+ previous: fragment,
+ });
+ expect(result.startsWith('model = "owner-choice"\n')).toBe(true);
+ expect(result.endsWith(suffix)).toBe(true);
+ expect(result).toContain('command = "/new-node"');
+ expect(result).not.toContain('command = "/node"');
+ });
+
+ test('rejects manual target tables and edited managed blocks without printing credentials', () => {
+ const initial = mergeTomlConfig('', { path: tomlPath, fragment });
+ for (const source of [fragment, initial.replace('/node', '/private-fixture')]) {
+ let message;
+ try {
+ mergeTomlConfig(source, { path: tomlPath, fragment, previous: fragment });
+ } catch (error) {
+ message = error.message;
+ }
+ expect(message).toMatch(/conflict/i);
+ expect(message).not.toContain('private-fixture');
+ }
+ });
+
+ test('rejects invalid TOML and fragments that would modify non-Kiln settings', () => {
+ expect(() => mergeTomlConfig('token = "private-fixture', { path: tomlPath, fragment })).toThrow(
+ /^Invalid TOML configuration\.$/,
+ );
+ expect(() =>
+ mergeTomlConfig('', { path: tomlPath, fragment: `model = "overwrite"\n${fragment}` }),
+ ).toThrow(/fragment/i);
+ expect(() => mergeTomlConfig('', { path: ['__proto__'], fragment })).toThrow(/invalid.*path/i);
+ });
+
+ test('marker-like text in a multiline value is never interpreted as a writable block', () => {
+ const initial = mergeTomlConfig('', { path: tomlPath, fragment });
+ const source = `notes = '''\n${initial}\n'''\n`;
+ expect(() => mergeTomlConfig(source, { path: tomlPath, fragment, previous: fragment })).toThrow(
+ /conflict/i,
+ );
+ });
+
+ test('rejects ambiguous trailing assignments whose table changes when a block is updated', () => {
+ const initial = mergeTomlConfig('', { path: tomlPath, fragment });
+ expect(() =>
+ mergeTomlConfig(`${initial}OWNER_SETTING = "keep"\n`, {
+ path: tomlPath,
+ fragment: fragment.replace('/node', '/new-node'),
+ previous: fragment,
+ }),
+ ).toThrow(/conflict/i);
+ });
+
+ test('rejects duplicate or incomplete markers and unsafe parent shapes', () => {
+ const initial = mergeTomlConfig('', { path: tomlPath, fragment });
+ const begin = initial.split('\n')[0];
+ for (const source of [`${begin}\n${initial}`, initial.replace('# END KILN', '# OWNER END')])
+ expect(() =>
+ mergeTomlConfig(source, { path: tomlPath, fragment, previous: fragment }),
+ ).toThrow(/conflict/i);
+ expect(() =>
+ mergeTomlConfig('mcp_servers = "private-fixture"', { path: tomlPath, fragment }),
+ ).toThrow(/conflict/i);
+ expect(() =>
+ mergeTomlConfig(' '.repeat(2 * 1024 * 1024 + 1), { path: tomlPath, fragment }),
+ ).toThrow(/^Invalid TOML configuration\.$/);
+ });
+});
diff --git a/scripts/workspace-project.mjs b/scripts/workspace-project.mjs
new file mode 100644
index 00000000..4494bdad
--- /dev/null
+++ b/scripts/workspace-project.mjs
@@ -0,0 +1,384 @@
+/** Shared project adoption and maintenance, independent of any one agent client. */
+import { createHash } from 'node:crypto';
+import { mkdir } from 'node:fs/promises';
+import { join } from 'node:path';
+import { getNodeValue, parseTree } from 'jsonc-parser';
+import { mergeJsonConfig, mergeTomlConfig } from './workspace-config.mjs';
+import { applyProjectEdits, readProjectFile } from './workspace-transaction.mjs';
+
+const hash = (value) =>
+ value === undefined ? undefined : createHash('sha256').update(value).digest('hex');
+const digestPattern = /^[a-f0-9]{64}$/;
+const text = (value, name) => {
+ try {
+ return value === undefined ? '' : new TextDecoder('utf-8', { fatal: true }).decode(value);
+ } catch {
+ throw new Error(`Invalid UTF-8 project configuration: ${name}`);
+ }
+};
+const descriptorKey = (value) => JSON.stringify([value.file, value.path]);
+const object = (value) => value && typeof value === 'object' && !Array.isArray(value);
+
+function configProjection(file, body) {
+ if (file === '.codex/config.toml')
+ return [{ file, kind: 'toml', path: ['mcp_servers', 'kiln_workspace'], fragment: body }];
+ if (file === 'opencode.json') {
+ const value = JSON.parse(body);
+ return [
+ {
+ file,
+ kind: 'json',
+ path: ['mcp', 'kiln_workspace'],
+ value: value.mcp.kiln_workspace,
+ comments: true,
+ },
+ {
+ file,
+ kind: 'json-list',
+ path: ['skills', 'paths'],
+ value: value.skills.paths[0],
+ comments: true,
+ },
+ ];
+ }
+ if (['.mcp.json', '.cursor/mcp.json', '.agents/mcp_config.json'].includes(file))
+ return [
+ {
+ file,
+ kind: 'json',
+ path: ['mcpServers', 'kiln_workspace'],
+ value: JSON.parse(body).mcpServers.kiln_workspace,
+ },
+ ];
+ return [];
+}
+
+function validatePrevious(previous, allowedNames, skills, knownConfigs, allowedHarnesses) {
+ if (!previous) return;
+ if (![1, 2].includes(previous.schemaVersion))
+ throw new Error('Unsupported workspace manifest version.');
+ if (!allowedHarnesses.includes(previous.harness))
+ throw new Error('Invalid workspace harness manifest.');
+ const ownedName = (name) => {
+ if (
+ typeof name !== 'string' ||
+ name.includes('\\') ||
+ name.includes(':') ||
+ name.split('/').some((p) => !p || p === '.' || p === '..')
+ )
+ return false;
+ if (allowedNames.has(name)) return true;
+ for (const prefix of ['skills/', '.claude/skills/', '.agents/skills/']) {
+ if (name.startsWith(prefix) && skills.includes(name.slice(prefix.length).split('/')[0]))
+ return true;
+ }
+ return false;
+ };
+ for (const map of [previous.ownedFiles, previous.managedHashes, previous.generated]) {
+ if (
+ map !== undefined &&
+ (!object(map) ||
+ Object.entries(map).some(
+ ([name, value]) =>
+ !ownedName(name) || typeof value !== 'string' || !digestPattern.test(value),
+ ))
+ )
+ throw new Error('Invalid managed-file manifest.');
+ }
+ if (previous.schemaVersion === 2) {
+ if (!Array.isArray(previous.configEntries) || previous.configEntries.length > 32)
+ throw new Error('Invalid configuration ownership manifest.');
+ const seen = new Set();
+ for (const entry of previous.configEntries) {
+ const key = descriptorKey(entry);
+ if (!knownConfigs.has(key) || entry.kind !== knownConfigs.get(key).kind || seen.has(key))
+ throw new Error('Invalid configuration ownership manifest.');
+ seen.add(key);
+ }
+ }
+}
+
+function listValue(content, path) {
+ const errors = [];
+ const tree = parseTree(content, errors, { allowTrailingComma: true });
+ if (errors.length || tree?.type !== 'object') throw new Error('Invalid JSON configuration.');
+ let value = getNodeValue(tree);
+ for (const part of path) {
+ if (!object(value)) throw new Error('Configuration conflict at skills.paths.');
+ value = value[part];
+ if (value === undefined) return [];
+ }
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string'))
+ throw new Error('Configuration conflict at skills.paths.');
+ return value;
+}
+
+/** All side effects go through one validated transaction after the complete plan is built. */
+export async function setupProject({
+ root,
+ runtime,
+ harness,
+ previous,
+ metadata,
+ exists,
+ options,
+ projectFiles,
+ skillFiles,
+ guide,
+ startGuide,
+ allowedHarnesses,
+}) {
+ if (
+ previous?.schemaVersion === 2 &&
+ (!Array.isArray(previous.harnesses) ||
+ !previous.harnesses.includes(previous.harness) ||
+ previous.harnesses.some((name) => !allowedHarnesses.includes(name)) ||
+ new Set(previous.harnesses).size !== previous.harnesses.length)
+ )
+ throw new Error('Invalid workspace harness manifest.');
+ const selected =
+ previous?.schemaVersion === 2 ? [...previous.harnesses] : previous ? [previous.harness] : [];
+ if (options.adopt || !previous) selected.push(harness);
+ const registrations = [...new Set(selected)].sort();
+ const projection = new Map();
+ const desired = {};
+ const runtimeFiles = new Set();
+ const knownConfigs = new Map();
+ const allowedNames = new Set([
+ 'AGENTS.md',
+ 'CLAUDE.md',
+ 'START.md',
+ '.kiln/AGENTS.md',
+ '.kiln/START.md',
+ '.kiln/.gitignore',
+ ]);
+ for (const name of allowedHarnesses) {
+ for (const [file, body] of Object.entries(projectFiles(name))) {
+ allowedNames.add(file);
+ for (const descriptor of configProjection(file, body))
+ knownConfigs.set(descriptorKey(descriptor), descriptor);
+ }
+ }
+ validatePrevious(previous, allowedNames, metadata.skills, knownConfigs, allowedHarnesses);
+ const snapshots = new Map();
+ const read = async (name) => {
+ if (!snapshots.has(name))
+ snapshots.set(name, exists ? await readProjectFile(root, name) : undefined);
+ return snapshots.get(name);
+ };
+ for (const name of registrations) {
+ for (const [file, body] of Object.entries(projectFiles(name))) {
+ const descriptors = configProjection(file, body);
+ if (!descriptors.length) {
+ desired[file] = body;
+ runtimeFiles.add(file);
+ continue;
+ }
+ for (const descriptor of descriptors) {
+ const key = descriptorKey(descriptor);
+ if (
+ projection.has(key) &&
+ JSON.stringify(projection.get(key)) !== JSON.stringify(descriptor)
+ )
+ throw new Error(
+ `The selected clients require conflicting configuration at ${file}. Keep their registrations separate until a compatible adapter is available.`,
+ );
+ projection.set(key, descriptor);
+ }
+ }
+ }
+ const configFiles = new Set([...knownConfigs.values()].map((entry) => entry.file));
+ const original =
+ previous?.schemaVersion === 2
+ ? { ...previous.ownedFiles }
+ : { ...previous?.generated, ...previous?.managedHashes };
+ if (previous?.schemaVersion === 1) {
+ for (const [name, value] of Object.entries(previous.skillHashes ?? {})) {
+ if (typeof value !== 'string' || !digestPattern.test(value))
+ throw new Error('Invalid skill manifest.');
+ for (const folder of ['skills', '.claude/skills', '.agents/skills']) {
+ const path = `${folder}/${name}`;
+ // Validate before reading paths from an older manifest.
+ validatePrevious(
+ { schemaVersion: 1, harness: previous.harness, generated: { [path]: value } },
+ allowedNames,
+ metadata.skills,
+ knownConfigs,
+ allowedHarnesses,
+ );
+ if ((await read(path)) !== undefined) original[path] ??= value;
+ }
+ }
+ }
+ for (const file of configFiles) delete original[file];
+ desired['.kiln/AGENTS.md'] = guide;
+ desired['.kiln/START.md'] = registrations.map((name) => startGuide(name)).join('\n---\n\n');
+ desired['.kiln/.gitignore'] = 'programs/\n';
+ const preserved = [];
+ for (const [file, body] of Object.entries({
+ 'AGENTS.md': guide,
+ 'CLAUDE.md':
+ (await read('AGENTS.md')) === undefined || original['AGENTS.md']
+ ? '@AGENTS.md\n'
+ : '@AGENTS.md\[email protected]/AGENTS.md\n',
+ 'START.md': desired['.kiln/START.md'],
+ })) {
+ if ((await read(file)) === undefined || original[file]) desired[file] = body;
+ else preserved.push(file);
+ }
+ const registries = new Set(['skills']);
+ for (const name of registrations) {
+ if (name === 'claude') registries.add('.claude/skills');
+ else if (name !== 'opencode') registries.add('.agents/skills');
+ }
+ const skillHashes = {};
+ for (const [name, body] of Object.entries(await skillFiles()).sort(([a], [b]) =>
+ a.localeCompare(b),
+ )) {
+ skillHashes[name] = hash(body);
+ for (const folder of registries) desired[`${folder}/${name}`] = body;
+ }
+ const edits = [],
+ files = [],
+ ownedFiles = {};
+ for (const name of [...new Set([...Object.keys(original), ...Object.keys(desired)])].sort()) {
+ if (options.repair && previous && !runtimeFiles.has(name)) {
+ if (original[name] !== undefined) ownedFiles[name] = original[name];
+ continue;
+ }
+ const before = await read(name);
+ const after = desired[name] === undefined ? undefined : Buffer.from(desired[name]);
+ const localHash = hash(before),
+ desiredHash = hash(after),
+ previousHash = original[name];
+ const status =
+ localHash === desiredHash
+ ? 'current'
+ : before === undefined
+ ? 'missing'
+ : localHash === previousHash
+ ? after === undefined
+ ? 'retired'
+ : 'outdated'
+ : previousHash === desiredHash && after !== undefined
+ ? 'customized'
+ : 'conflict';
+ if (after !== undefined) ownedFiles[name] = desiredHash;
+ if (status !== 'current') files.push({ path: name, status });
+ if (!['current', 'customized', 'conflict'].includes(status))
+ edits.push({ path: name, before, after });
+ }
+ const previousEntries = new Map(
+ (previous?.configEntries ?? []).map((value) => [descriptorKey(value), value]),
+ );
+ const configEntries = [...projection.values()];
+ for (const file of [...new Set(configEntries.map((entry) => entry.file))].sort()) {
+ const before = await read(file);
+ try {
+ let merged = text(before, file);
+ const legacyOwned =
+ previous?.schemaVersion === 1 &&
+ before !== undefined &&
+ hash(before) === (previous.generated?.[file] ?? previous.managedHashes?.[file]);
+ for (const entry of configEntries.filter((value) => value.file === file)) {
+ let prior = previousEntries.get(descriptorKey(entry));
+ if (entry.kind === 'toml') {
+ if (legacyOwned) merged = '';
+ merged = mergeTomlConfig(merged, {
+ path: entry.path,
+ fragment: entry.fragment,
+ ...(prior ? { previous: prior.fragment } : {}),
+ });
+ } else if (entry.kind === 'json') {
+ if (legacyOwned) {
+ let value = JSON.parse(text(before, file));
+ for (const part of entry.path) value = value?.[part];
+ if (value !== undefined) prior = { value };
+ }
+ merged = mergeJsonConfig(
+ merged,
+ [{ path: entry.path, value: entry.value, ...(prior ? { previous: prior.value } : {}) }],
+ { comments: entry.comments === true },
+ );
+ } else {
+ const current = listValue(merged, entry.path);
+ // Schema 1 owns the unchanged generated config as a whole. Its single
+ // skill path belongs to the original workspace, which may have moved.
+ // Never infer this ownership from a modified or adopted user config.
+ const oldPath =
+ prior?.value ?? (legacyOwned && current.length === 1 ? current[0] : undefined);
+ const value = current.filter((item) => item !== oldPath || oldPath === entry.value);
+ if (!value.includes(entry.value)) value.push(entry.value);
+ merged = mergeJsonConfig(merged, [{ path: entry.path, value, previous: current }], {
+ comments: true,
+ });
+ }
+ }
+ if (before === undefined || !before.equals(Buffer.from(merged))) {
+ files.push({ path: file, status: before === undefined ? 'missing' : 'outdated' });
+ edits.push({ path: file, before, after: merged });
+ }
+ } catch {
+ files.push({ path: file, status: 'conflict' });
+ }
+ }
+ const next = {
+ schemaVersion: 2,
+ root,
+ harness: previous?.harness ?? harness,
+ harnesses: registrations,
+ runtime,
+ runtimeVersion: metadata.runtimeVersion,
+ buildIdentity: metadata.buildIdentity,
+ runtimeHashes: metadata.runtimeHashes,
+ node: metadata.node,
+ skills: metadata.skills,
+ skillHashes: options.repair && previous ? previous.skillHashes : skillHashes,
+ ownedFiles,
+ configEntries,
+ };
+ const manifestBefore = await read('.kiln/workspace.json');
+ const manifestAfter = JSON.stringify(next);
+ const runtimeChanged =
+ !!previous &&
+ (previous.runtime !== runtime ||
+ previous.node !== next.node ||
+ previous.runtimeVersion !== next.runtimeVersion ||
+ (previous.buildIdentity ?? previous.runtimeIdentity) !== next.buildIdentity ||
+ JSON.stringify(previous.runtimeHashes) !== JSON.stringify(next.runtimeHashes) ||
+ (previous.schemaVersion === 2 && previous.root !== root));
+ const manifestChanged =
+ manifestBefore === undefined || !manifestBefore.equals(Buffer.from(manifestAfter));
+ if (manifestChanged)
+ edits.push({ path: '.kiln/workspace.json', before: manifestBefore, after: manifestAfter });
+ const conflicts = files.filter((file) => file.status === 'conflict');
+ const report = {
+ root,
+ runtime,
+ harness: next.harness,
+ harnesses: registrations,
+ store: join(root, '.kiln', 'programs'),
+ server: join(runtime, 'dist', 'mcp-server.mjs'),
+ instructions: join(root, '.kiln', 'AGENTS.md'),
+ status: edits.length || conflicts.length || runtimeChanged ? 'update-required' : 'current',
+ runtimeChanged,
+ files,
+ preserved,
+ next: 'Stop active agent/MCP sessions before setup changes. Restart afterward and accept the normal project and MCP trust prompts.',
+ };
+ if (options.check) {
+ if (exists && !conflicts.length)
+ await applyProjectEdits(root, edits, { stateDirectory: options.stateDirectory, check: true });
+ return report;
+ }
+ if (conflicts.length)
+ throw new Error(
+ `Project setup has conflicts; no files were changed: ${conflicts.map((file) => file.path).join(', ')}. Preserve and resolve these files before retrying.`,
+ );
+ if (!exists) await mkdir(root, { recursive: true });
+ await applyProjectEdits(root, edits, {
+ stateDirectory: options.stateDirectory,
+ onStep: options.onStep,
+ });
+ return { ...report, status: 'current', changed: edits.map((edit) => edit.path) };
+}
diff --git a/scripts/workspace-transaction.mjs b/scripts/workspace-transaction.mjs
new file mode 100644
index 00000000..942f1c6e
--- /dev/null
+++ b/scripts/workspace-transaction.mjs
@@ -0,0 +1,504 @@
+/** Recoverable setup writes. Private recovery data never enters diagnostics. */
+import { createHash, randomUUID } from 'node:crypto';
+import { constants } from 'node:fs';
+import {
+ chmod,
+ link,
+ lstat as nativeLstat,
+ mkdir,
+ open,
+ readFile,
+ readdir,
+ realpath,
+ rename,
+ rmdir,
+ unlink,
+} from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
+
+const active = new Set();
+const lstat = (path) => nativeLstat(path, { bigint: true });
+const maxFile = 2 * 1024 * 1024;
+const digest = (value) => createHash('sha256').update(value).digest('hex');
+const key = (value) => (process.platform === 'win32' ? value.toLowerCase() : value);
+const inside = (parent, child) => {
+ const rel = relative(key(parent), key(child));
+ return !rel || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
+};
+const equal = (a, b) => (a === undefined ? b === undefined : b !== undefined && a.equals(b));
+const maybeStat = async (path) => {
+ try {
+ return await lstat(path);
+ } catch (error) {
+ if (error.code === 'ENOENT') return undefined;
+ throw error;
+ }
+};
+
+function safePath(value) {
+ if (
+ typeof value !== 'string' ||
+ !value ||
+ value.length > 1024 ||
+ value
+ .split('/')
+ .some(
+ (part) =>
+ !part ||
+ part === '.' ||
+ part === '..' ||
+ /[\\:*?"<>|]/.test(part) ||
+ [...part].some((character) => character.charCodeAt(0) < 32) ||
+ /[. ]$/.test(part) ||
+ /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(part) ||
+ /^\.git$/i.test(part),
+ )
+ )
+ throw new Error('Unsafe project path.');
+ return value;
+}
+
+async function inspectPath(root, name) {
+ safePath(name);
+ const rootInfo = await lstat(root);
+ if (rootInfo.isSymbolicLink()) throw new Error('Refusing symbolic link at the project root.');
+ if (!rootInfo.isDirectory()) throw new Error('Project root must remain a directory.');
+ let path = root;
+ const parts = name.split('/');
+ for (let i = 0; i < parts.length; i++) {
+ path = join(path, parts[i]);
+ const info = await maybeStat(path);
+ if (!info) return undefined;
+ if (info.isSymbolicLink()) throw new Error(`Refusing symbolic link in project path: ${name}`);
+ if (i !== parts.length - 1 && !info.isDirectory())
+ throw new Error(`Not a directory in project path: ${name}`);
+ if (i === parts.length - 1) return info;
+ }
+}
+
+async function readSafe(root, name) {
+ const info = await inspectPath(root, name);
+ if (!info) return undefined;
+ if (!info.isFile() || info.nlink !== 1n)
+ throw new Error(`Expected a single regular file: ${name}`);
+ if (info.size > maxFile) throw new Error(`Project file exceeds setup size limit: ${name}`);
+ const handle = await open(join(root, name), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
+ try {
+ const current = await handle.stat({ bigint: true });
+ if (current.dev !== info.dev || current.ino !== info.ino || current.size > maxFile)
+ throw new Error(`Project file changed: ${name}`);
+ const data = await handle.readFile();
+ if (data.length > maxFile) throw new Error(`Project file exceeds setup size limit: ${name}`);
+ return data;
+ } finally {
+ await handle.close();
+ }
+}
+
+export async function readProjectFile(root, name) {
+ if ((await lstat(root)).isSymbolicLink())
+ throw new Error('Refusing symbolic link at the project root.');
+ return readSafe(await realpath(root), name);
+}
+
+async function paths(root, stateDirectory) {
+ if ((await lstat(root)).isSymbolicLink())
+ throw new Error('Refusing symbolic link at the project root.');
+ root = await realpath(root);
+ const rootInfo = await lstat(root);
+ if (!rootInfo.isDirectory()) throw new Error('Project root must be a directory.');
+ const base =
+ process.platform === 'win32'
+ ? join(
+ process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'),
+ 'InstruktLabs',
+ 'Kiln',
+ )
+ : join(
+ process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'),
+ 'instruktlabs',
+ 'kiln',
+ );
+ const state = resolve(stateDirectory ?? join(base, 'setup-transactions'));
+ // A junction in any existing ancestor must not redirect private backups.
+ let current = parse(state).root;
+ for (const part of relative(current, state).split(sep).filter(Boolean)) {
+ current = join(current, part);
+ const info = await maybeStat(current);
+ if (info?.isSymbolicLink()) throw new Error('Refusing symbolic link in recovery storage.');
+ if (info && !info.isDirectory()) throw new Error('Recovery storage must be a directory.');
+ }
+ if (inside(root, state) || inside(state, root))
+ throw new Error('Recovery storage must be outside the project.');
+ const directory = join(state, digest(key(root)));
+ return { root, state, directory, rootInfo };
+}
+
+async function assertRoot(root, journal) {
+ const info = await lstat(root);
+ if (
+ !info.isDirectory() ||
+ info.isSymbolicLink() ||
+ String(info.dev) !== journal.rootDev ||
+ String(info.ino) !== journal.rootIno
+ )
+ throw new Error('Project root changed during setup.');
+}
+
+async function durableWrite(path, value, mode = 0o600) {
+ const handle = await open(path, 'wx', mode);
+ try {
+ await handle.writeFile(value);
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+}
+
+async function saveJournal(directory, journal) {
+ const pending = join(directory, 'journal.pending');
+ await unlink(pending).catch((error) => {
+ if (error.code !== 'ENOENT') throw error;
+ });
+ await durableWrite(pending, JSON.stringify(journal));
+ await rename(pending, join(directory, 'journal.json'));
+}
+
+function bytes(value) {
+ if (value === undefined) return undefined;
+ if (typeof value !== 'string' && !Buffer.isBuffer(value))
+ throw new Error('Setup edits require text or bytes.');
+ const result = Buffer.from(value);
+ if (result.length > maxFile) throw new Error('Setup edit exceeds size limit.');
+ return result;
+}
+
+async function ensureParents(root, name, journal, directory) {
+ const parts = name.split('/').slice(0, -1);
+ for (let i = 1; i <= parts.length; i++) {
+ const path = parts.slice(0, i).join('/');
+ const info = await inspectPath(root, path);
+ if (info) {
+ if (!info.isDirectory()) throw new Error(`Not a directory in project path: ${path}`);
+ continue;
+ }
+ await mkdir(join(root, path));
+ const created = await lstat(join(root, path));
+ journal.directories.push({ path, dev: String(created.dev), ino: String(created.ino) });
+ await saveJournal(directory, journal);
+ }
+}
+
+function stageName(journal, entry) {
+ return [
+ ...entry.path.split('/').slice(0, -1),
+ `.kiln-setup-${journal.id}-${entry.index}.tmp`,
+ ].join('/');
+}
+
+async function replaceFile(root, entry, before, after, journal, directory) {
+ await assertRoot(root, journal);
+ if (!equal(await readSafe(root, entry.path), before))
+ throw new Error(`Project file changed: ${entry.path}`);
+ if (after === undefined) {
+ await unlink(join(root, entry.path));
+ return;
+ }
+ await ensureParents(root, entry.path, journal, directory);
+ const temporary = stageName(journal, entry);
+ await inspectPath(root, temporary);
+ await durableWrite(join(root, temporary), after);
+ if (entry.mode !== undefined) await chmod(join(root, temporary), entry.mode);
+ // Recheck after staging. A new destination must not replace a concurrent arrival.
+ if (!equal(await readSafe(root, entry.path), before))
+ throw new Error(`Project file changed: ${entry.path}`);
+ if (before === undefined) {
+ await link(join(root, temporary), join(root, entry.path));
+ await unlink(join(root, temporary));
+ } else {
+ await rename(join(root, temporary), join(root, entry.path));
+ }
+}
+
+async function storedBytes(directory, entry, side) {
+ if (entry[side] === null) return undefined;
+ const value = await readSafe(directory, `${entry.index}.${side}`);
+ if (value === undefined || digest(value) !== entry[side])
+ throw new Error('Recovery data failed integrity verification.');
+ return value;
+}
+
+async function removeTemporary(root, journal, entry) {
+ const name = stageName(journal, entry);
+ const info = await inspectPath(root, name);
+ if (!info) return;
+ // Two links are possible if a process stopped between exclusive publication and unlink.
+ if (!info.isFile() || info.size > maxFile) throw new Error(`Recovery conflict at ${name}`);
+ const value = await readFile(join(root, name));
+ if (![entry.before, entry.after].includes(digest(value)))
+ throw new Error(`Recovery conflict at ${name}`);
+ await unlink(join(root, name));
+}
+
+async function cleanState(directory, journal, recovery = false) {
+ // Never recursively delete private storage.
+ const known = new Set([
+ 'journal.pending',
+ 'journal.json',
+ ...(recovery ? ['recovery.lock'] : []),
+ ]);
+ for (const entry of journal.entries)
+ for (const side of ['before', 'after']) known.add(`${entry.index}.${side}`);
+ if ((await readdir(directory)).some((name) => !known.has(name)))
+ throw new Error('Unexpected recovery file; private recovery data was retained.');
+ for (const entry of journal.entries) {
+ for (const side of ['before', 'after']) {
+ await unlink(join(directory, `${entry.index}.${side}`)).catch((error) => {
+ if (error.code !== 'ENOENT') throw error;
+ });
+ }
+ }
+ for (const name of ['journal.pending', 'journal.json', ...(recovery ? ['recovery.lock'] : [])]) {
+ await unlink(join(directory, name)).catch((error) => {
+ if (error.code !== 'ENOENT') throw error;
+ });
+ }
+ await rmdir(directory);
+}
+
+async function rollback(root, directory, journal, recovery = false) {
+ await assertRoot(root, journal);
+ const restore = [];
+ for (const entry of journal.entries.filter((item) => item.started)) {
+ const before = await storedBytes(directory, entry, 'before');
+ const after = await storedBytes(directory, entry, 'after');
+ await removeTemporary(root, journal, entry);
+ const current = await readSafe(root, entry.path);
+ if (!equal(current, before) && !equal(current, after))
+ throw new Error(`Recovery conflict at ${entry.path}`);
+ restore.push({ entry, before, after, current });
+ }
+ // Check all target conflicts before restoring any target.
+ for (const { entry, before, after, current } of restore.reverse()) {
+ if (!equal(current, before)) await replaceFile(root, entry, after, before, journal, directory);
+ }
+ for (const created of [...journal.directories].reverse()) {
+ const info = await inspectPath(root, created.path);
+ if (!info || String(info.dev) !== created.dev || String(info.ino) !== created.ino) continue;
+ await rmdir(join(root, created.path)).catch((error) => {
+ if (!['ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error;
+ });
+ }
+ journal.phase = 'recovered';
+ await saveJournal(directory, journal);
+ await cleanState(directory, journal, recovery);
+}
+
+export async function applyProjectEdits(
+ root,
+ edits,
+ { stateDirectory, check = false, onStep } = {},
+) {
+ const location = await paths(root, stateDirectory);
+ root = location.root;
+ const { directory, state } = location;
+ if (!Array.isArray(edits) || edits.length > 1024) throw new Error('Invalid setup edit list.');
+ const names = new Set();
+ let size = 0;
+ const planned = [];
+ for (const edit of edits) {
+ const path = safePath(edit?.path).toLowerCase();
+ if (names.has(path)) throw new Error(`Duplicate setup path: ${edit.path}`);
+ names.add(path);
+ }
+ for (const path of names) {
+ const parts = path.split('/');
+ for (let i = 1; i < parts.length; i++)
+ if (names.has(parts.slice(0, i).join('/'))) throw new Error('Overlapping setup paths.');
+ }
+ for (const edit of edits) {
+ const path = safePath(edit.path);
+ const before = bytes(edit.before);
+ const after = bytes(edit.after);
+ size += (before?.length ?? 0) + (after?.length ?? 0);
+ if (size > 32 * maxFile) throw new Error('Setup transaction exceeds size limit.');
+ if (!equal(await readSafe(root, path), before))
+ throw new Error(`Project file changed: ${path}`);
+ const info = await inspectPath(root, path);
+ if (!equal(before, after))
+ planned.push({ path, before, after, mode: info ? Number(info.mode & 0o777n) : undefined });
+ }
+ planned.sort(
+ (a, b) => Number(a.path === '.kiln/workspace.json') - Number(b.path === '.kiln/workspace.json'),
+ );
+ if (await maybeStat(directory))
+ throw new Error(
+ 'Project setup is locked; finish the active setup or recover the interrupted update.',
+ );
+ if (check) return { status: 'planned', paths: planned.map((entry) => entry.path) };
+ if (!planned.length) return { status: 'applied', paths: [] };
+ await mkdir(state, { recursive: true, mode: 0o700 });
+ try {
+ await mkdir(directory, { mode: 0o700 });
+ } catch (error) {
+ if (error.code === 'EEXIST') throw new Error('Project setup is locked.');
+ throw error;
+ }
+ active.add(directory);
+ const { rootInfo } = location;
+ const journal = {
+ version: 1,
+ root,
+ rootDev: String(rootInfo.dev),
+ rootIno: String(rootInfo.ino),
+ pid: process.pid,
+ id: randomUUID(),
+ phase: 'preparing',
+ directories: [],
+ entries: [],
+ };
+ try {
+ await assertRoot(root, journal);
+ for (const [index, entry] of planned.entries()) {
+ journal.entries.push({
+ index,
+ path: entry.path,
+ mode: entry.mode,
+ before: entry.before === undefined ? null : digest(entry.before),
+ after: entry.after === undefined ? null : digest(entry.after),
+ started: false,
+ });
+ for (const side of ['before', 'after'])
+ if (entry[side] !== undefined)
+ await durableWrite(join(directory, `${index}.${side}`), entry[side]);
+ }
+ journal.phase = 'prepared';
+ await saveJournal(directory, journal);
+ await onStep?.({ phase: 'prepared' });
+ for (const [index, entry] of planned.entries()) {
+ if (!equal(await readSafe(root, entry.path), entry.before))
+ throw new Error(`Project file changed: ${entry.path}`);
+ journal.entries[index].started = true;
+ await saveJournal(directory, journal);
+ await replaceFile(
+ root,
+ journal.entries[index],
+ entry.before,
+ entry.after,
+ journal,
+ directory,
+ );
+ await onStep?.({ phase: 'written', path: entry.path });
+ }
+ journal.phase = 'committed';
+ await saveJournal(directory, journal);
+ await cleanState(directory, journal);
+ return { status: 'applied', paths: planned.map((entry) => entry.path) };
+ } catch {
+ if (journal.phase === 'committed')
+ throw new Error('Setup completed but private recovery cleanup is required.');
+ try {
+ await rollback(root, directory, journal);
+ } catch {
+ throw new Error(
+ 'Setup stopped; recovery required. Existing user edits and private recovery data were retained.',
+ );
+ }
+ throw new Error('Setup stopped; previous files were restored.');
+ } finally {
+ active.delete(directory);
+ }
+}
+
+function validateJournal(journal, root) {
+ const identity = (value) => typeof value === 'string' && /^[0-9]{1,40}$/.test(value);
+ if (
+ journal?.version !== 1 ||
+ journal.root !== root ||
+ !Number.isSafeInteger(journal.pid) ||
+ journal.pid < 1 ||
+ !identity(journal.rootDev) ||
+ !identity(journal.rootIno) ||
+ !/^[a-f0-9-]{36}$/.test(journal.id) ||
+ !['prepared', 'committed', 'recovered'].includes(journal.phase) ||
+ !Array.isArray(journal.entries) ||
+ journal.entries.length > 1024 ||
+ !Array.isArray(journal.directories) ||
+ journal.directories.length > 8192
+ )
+ throw new Error('Invalid recovery journal.');
+ const names = new Set();
+ for (const [index, entry] of journal.entries.entries()) {
+ safePath(entry.path);
+ if (
+ entry.index !== index ||
+ names.has(entry.path.toLowerCase()) ||
+ typeof entry.started !== 'boolean' ||
+ (entry.mode !== undefined &&
+ (!Number.isSafeInteger(entry.mode) || entry.mode < 0 || entry.mode > 0o777)) ||
+ ![entry.before, entry.after].every(
+ (value) => value === null || (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)),
+ )
+ )
+ throw new Error('Invalid recovery journal.');
+ names.add(entry.path.toLowerCase());
+ }
+ for (const dir of journal.directories) {
+ safePath(dir.path);
+ if (
+ !identity(dir.dev) ||
+ !identity(dir.ino) ||
+ !journal.entries.some((entry) => entry.path.startsWith(`${dir.path}/`))
+ )
+ throw new Error('Invalid recovery journal.');
+ }
+}
+
+export async function recoverProjectEdits(root, { stateDirectory } = {}) {
+ const location = await paths(root, stateDirectory);
+ const { directory } = location;
+ root = location.root;
+ if (active.has(directory)) throw new Error('Project setup is still active.');
+ const info = await maybeStat(directory);
+ if (!info) return { status: 'unchanged' };
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('Invalid recovery storage.');
+ let journal;
+ try {
+ journal = JSON.parse((await readSafe(directory, 'journal.json')).toString('utf8'));
+ } catch {
+ throw new Error(
+ 'Incomplete recovery journal; manual inspection is required. No project files were changed.',
+ );
+ }
+ validateJournal(journal, root);
+ await assertRoot(root, journal);
+ if (journal.pid !== process.pid) {
+ try {
+ process.kill(journal.pid, 0);
+ throw new Error('Project setup process is still active.');
+ } catch (error) {
+ if (error.code !== 'ESRCH') throw error;
+ }
+ }
+ const recoveryLock = join(directory, 'recovery.lock');
+ try {
+ await durableWrite(recoveryLock, String(process.pid));
+ } catch (error) {
+ if (error.code === 'EEXIST')
+ throw new Error('Project recovery is already active or requires manual inspection.');
+ throw error;
+ }
+ active.add(directory);
+ try {
+ if (journal.phase === 'committed' || journal.phase === 'recovered')
+ await cleanState(directory, journal, true);
+ else await rollback(root, directory, journal, true);
+ return { status: 'recovered' };
+ } finally {
+ active.delete(directory);
+ await unlink(recoveryLock).catch((error) => {
+ if (error.code !== 'ENOENT') throw error;
+ });
+ }
+}
diff --git a/scripts/workspace-transaction.test.mjs b/scripts/workspace-transaction.test.mjs
new file mode 100644
index 00000000..af2cc773
--- /dev/null
+++ b/scripts/workspace-transaction.test.mjs
@@ -0,0 +1,321 @@
+import { test, expect } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ realpath,
+ rename,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve, sep } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import {
+ applyProjectEdits,
+ readProjectFile,
+ recoverProjectEdits,
+} from './workspace-transaction.mjs';
+
+const moduleUrl = pathToFileURL(resolve(import.meta.dir, 'workspace-transaction.mjs')).href;
+async function cleanupFixture(temp) {
+ const actual = await realpath(temp);
+ const parent = await realpath(tmpdir());
+ if (
+ !actual.startsWith(parent + sep) ||
+ !actual.slice(parent.length + 1).startsWith('kiln-project-update-')
+ )
+ throw new Error('Refusing fixture cleanup outside its temporary root.');
+ await rm(actual, { recursive: true, force: true });
+}
+async function fixture(fn) {
+ const temp = await realpath(await mkdtemp(join(tmpdir(), 'kiln-project-update-')));
+ const root = join(temp, 'project');
+ const stateDirectory = join(temp, 'private-state');
+ await mkdir(root);
+ try {
+ await fn({ temp, root, stateDirectory });
+ } finally {
+ await cleanupFixture(temp);
+ }
+}
+const put = async (root, name, text) => {
+ await mkdir(dirname(join(root, name)), { recursive: true });
+ await writeFile(join(root, name), text);
+};
+
+test('updates only planned files and commits the manifest after complete configuration files', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await put(root, 'AGENTS.md', 'Owner instructions');
+ await put(root, '.mcp.json', 'old config');
+ const events = [];
+ const edits = [
+ { path: '.kiln/workspace.json', before: undefined, after: 'manifest' },
+ { path: '.mcp.json', before: 'old config', after: 'new config' },
+ { path: 'skills/kiln-author-asset/SKILL.md', before: undefined, after: '# skill' },
+ ];
+ const result = await applyProjectEdits(root, edits, {
+ stateDirectory,
+ onStep: (event) => events.push(event),
+ });
+ expect(result.status).toBe('applied');
+ expect(await readFile(join(root, 'AGENTS.md'), 'utf8')).toBe('Owner instructions');
+ expect(await readFile(join(root, '.mcp.json'), 'utf8')).toBe('new config');
+ expect(await readFile(join(root, '.kiln/workspace.json'), 'utf8')).toBe('manifest');
+ expect(events.filter((e) => e.phase === 'written').at(-1).path).toBe('.kiln/workspace.json');
+ expect(JSON.stringify(events)).not.toContain('old config');
+ expect(await readdir(stateDirectory)).toEqual([]);
+ }));
+
+test('a check makes no directories or writes, and a stale plan fails before mutation', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await put(root, 'existing.txt', 'owner edit');
+ const edits = [{ path: 'new.txt', after: 'new' }];
+ expect((await applyProjectEdits(root, edits, { stateDirectory, check: true })).status).toBe(
+ 'planned',
+ );
+ expect(await readdir(root)).toEqual(['existing.txt']);
+ await expect(readdir(stateDirectory)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(
+ applyProjectEdits(
+ root,
+ [...edits, { path: 'existing.txt', before: 'stale', after: 'replacement' }],
+ { stateDirectory },
+ ),
+ ).rejects.toThrow(/changed.*existing.txt/i);
+ expect(await readdir(root)).toEqual(['existing.txt']);
+ }));
+
+test('a caught partial failure restores previous bytes and removes only its newly created files', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await put(root, 'existing.txt', 'original');
+ const edits = [
+ { path: 'existing.txt', before: 'original', after: 'updated' },
+ { path: 'nested/new.txt', after: 'created' },
+ ];
+ await expect(
+ applyProjectEdits(root, edits, {
+ stateDirectory,
+ onStep: (event) => {
+ if (event.phase === 'written' && event.path === 'nested/new.txt')
+ throw new Error('Injected failure');
+ },
+ }),
+ ).rejects.toThrow(/restored/i);
+ expect(await readFile(join(root, 'existing.txt'), 'utf8')).toBe('original');
+ expect(await readdir(root)).toEqual(['existing.txt']);
+ expect(await readdir(stateDirectory)).toEqual([]);
+ }));
+
+test('rollback retains a conflicting user edit and private recovery data until explicitly resolved', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await put(root, 'existing.txt', 'original');
+ await expect(
+ applyProjectEdits(root, [{ path: 'existing.txt', before: 'original', after: 'updated' }], {
+ stateDirectory,
+ onStep: async (event) => {
+ if (event.phase === 'written') {
+ await put(root, 'existing.txt', 'new owner edit');
+ throw new Error('Injected');
+ }
+ },
+ }),
+ ).rejects.toThrow(/recovery required/i);
+ expect(await readFile(join(root, 'existing.txt'), 'utf8')).toBe('new owner edit');
+ await expect(recoverProjectEdits(root, { stateDirectory })).rejects.toThrow(
+ /conflict.*existing.txt/i,
+ );
+ expect(await readFile(join(root, 'existing.txt'), 'utf8')).toBe('new owner edit');
+ await put(root, 'existing.txt', 'updated');
+ expect((await recoverProjectEdits(root, { stateDirectory })).status).toBe('recovered');
+ expect(await readFile(join(root, 'existing.txt'), 'utf8')).toBe('original');
+ expect(await readdir(stateDirectory)).toEqual([]);
+ }));
+
+test('rejects traversal, aliases, protected paths and project-local backup storage before mutation', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ for (const path of [
+ '../escape',
+ '/absolute',
+ 'C:/escape',
+ 'a\\b',
+ '.git/config',
+ 'file:stream',
+ 'nested/../escape',
+ 'NUL',
+ 'file.',
+ ])
+ await expect(
+ applyProjectEdits(root, [{ path, after: 'x' }], { stateDirectory }),
+ ).rejects.toThrow(/unsafe.*path/i);
+ await expect(
+ applyProjectEdits(
+ root,
+ [
+ { path: 'A', after: 'a' },
+ { path: 'a', after: 'b' },
+ ],
+ { stateDirectory },
+ ),
+ ).rejects.toThrow(/duplicate/i);
+ await expect(
+ applyProjectEdits(root, [{ path: 'a', after: 'a' }], {
+ stateDirectory: join(root, '.state'),
+ }),
+ ).rejects.toThrow(/outside/i);
+ expect(await readdir(root)).toEqual([]);
+ }));
+
+test('never follows a directory junction or symbolic link to read or mutate an outside file', () =>
+ fixture(async ({ temp, root, stateDirectory }) => {
+ const outside = join(temp, 'outside');
+ await mkdir(outside);
+ await put(outside, 'config.json', 'outside');
+ await symlink(outside, join(root, '.codex'), process.platform === 'win32' ? 'junction' : 'dir');
+ await expect(readProjectFile(root, '.codex/config.json')).rejects.toThrow(/symbolic link/i);
+ await expect(
+ applyProjectEdits(root, [{ path: '.codex/config.json', before: 'outside', after: 'wrong' }], {
+ stateDirectory,
+ }),
+ ).rejects.toThrow(/symbolic link/i);
+ expect(await readFile(join(outside, 'config.json'), 'utf8')).toBe('outside');
+ }));
+
+test('serializes setup and refuses recovery while an update is still active', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await applyProjectEdits(root, [{ path: 'one.txt', after: 'one' }], {
+ stateDirectory,
+ onStep: async (event) => {
+ if (event.phase !== 'prepared') return;
+ await expect(
+ applyProjectEdits(root, [{ path: 'two.txt', after: 'two' }], { stateDirectory }),
+ ).rejects.toThrow(/locked/i);
+ await expect(recoverProjectEdits(root, { stateDirectory })).rejects.toThrow(/active/i);
+ },
+ });
+ expect(await readdir(root)).toEqual(['one.txt']);
+ }));
+
+test('recovers after the setup process exits mid-update without putting backups in the project', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await put(root, '.mcp.json', 'original secret-fixture');
+ const script = `import {applyProjectEdits} from ${JSON.stringify(moduleUrl)}; await applyProjectEdits(process.argv[1],[{path:'.mcp.json',before:'original secret-fixture',after:'updated'},{path:'.kiln/workspace.json',after:'manifest'}],{stateDirectory:process.argv[2],onStep:event=>{if(event.phase==='written')process.exit(37)}});`;
+ const child = spawnSync('node', ['--input-type=module', '-e', script, root, stateDirectory], {
+ encoding: 'utf8',
+ timeout: 10000,
+ windowsHide: true,
+ });
+ expect(child.status).toBe(37);
+ expect(child.stdout + child.stderr).not.toContain('secret-fixture');
+ expect(await readdir(root)).toEqual(['.mcp.json']);
+ expect(await readFile(join(root, '.mcp.json'), 'utf8')).toBe('updated');
+ expect((await recoverProjectEdits(root, { stateDirectory })).status).toBe('recovered');
+ expect(await readFile(join(root, '.mcp.json'), 'utf8')).toBe('original secret-fixture');
+ expect(await readdir(stateDirectory)).toEqual([]);
+ }));
+
+test('deletion is reversible and never recursively removes a target directory', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await put(root, 'retired.txt', 'old');
+ await applyProjectEdits(root, [{ path: 'retired.txt', before: 'old', after: undefined }], {
+ stateDirectory,
+ });
+ expect(await readdir(root)).toEqual([]);
+ await mkdir(join(root, 'directory'));
+ await expect(
+ applyProjectEdits(root, [{ path: 'directory', after: 'wrong' }], { stateDirectory }),
+ ).rejects.toThrow(/regular file/i);
+ }));
+
+test('rejects file and directory overlaps before creating recovery storage or writing', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await expect(
+ applyProjectEdits(
+ root,
+ [
+ { path: 'nested', after: 'file' },
+ { path: 'nested/new.txt', after: 'child' },
+ ],
+ { stateDirectory },
+ ),
+ ).rejects.toThrow(/overlap/i);
+ expect(await readdir(root)).toEqual([]);
+ await expect(readdir(stateDirectory)).rejects.toMatchObject({ code: 'ENOENT' });
+ }));
+
+test('a directory replaced by a junction during setup cannot redirect writes', () =>
+ fixture(async ({ temp, root, stateDirectory }) => {
+ const outside = join(temp, 'outside');
+ await mkdir(outside);
+ await put(outside, 'target.txt', 'outside');
+ await expect(
+ applyProjectEdits(root, [{ path: 'target.txt', after: 'wrong' }], {
+ stateDirectory,
+ onStep: async (event) => {
+ if (event.phase !== 'prepared') return;
+ await rename(root, join(temp, 'original-project'));
+ await symlink(outside, root, process.platform === 'win32' ? 'junction' : 'dir');
+ },
+ }),
+ ).rejects.toThrow(/recovery required/i);
+ expect(await readFile(join(outside, 'target.txt'), 'utf8')).toBe('outside');
+ await expect(readProjectFile(root, 'target.txt')).rejects.toThrow(/symbolic link/i);
+ }));
+
+test('tampered backups prevent every recovery write and disclose no configuration values', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await put(root, 'one.txt', 'first original');
+ await put(root, 'two.txt', 'second original');
+ await expect(
+ applyProjectEdits(
+ root,
+ [
+ { path: 'one.txt', before: 'first original', after: 'first update' },
+ { path: 'two.txt', before: 'second original', after: 'second update' },
+ ],
+ {
+ stateDirectory,
+ onStep: async (event) => {
+ if (event.phase !== 'written' || event.path !== 'two.txt') return;
+ await put(root, 'two.txt', 'conflicting owner edit');
+ throw new Error('Stop');
+ },
+ },
+ ),
+ ).rejects.toThrow(/recovery required/i);
+ await put(root, 'two.txt', 'second update');
+ const transaction = join(stateDirectory, (await readdir(stateDirectory))[0]);
+ await writeFile(join(transaction, '1.before'), 'SYNTHETIC-SECRET-NOT-FOR-LOGS');
+ await expect(recoverProjectEdits(root, { stateDirectory })).rejects.toThrow(
+ 'Recovery data failed integrity verification.',
+ );
+ expect(await readFile(join(root, 'one.txt'), 'utf8')).toBe('first update');
+ expect(await readFile(join(root, 'two.txt'), 'utf8')).toBe('second update');
+ }));
+
+test('an unmodified second file edited after planning is preserved while earlier setup writes roll back', () =>
+ fixture(async ({ root, stateDirectory }) => {
+ await put(root, 'one.txt', 'first original');
+ await put(root, 'two.txt', 'second original');
+ await expect(
+ applyProjectEdits(
+ root,
+ [
+ { path: 'one.txt', before: 'first original', after: 'first update' },
+ { path: 'two.txt', before: 'second original', after: 'second update' },
+ ],
+ {
+ stateDirectory,
+ onStep: async (event) => {
+ if (event.phase === 'written') await put(root, 'two.txt', 'owner edit');
+ },
+ },
+ ),
+ ).rejects.toThrow(/restored/i);
+ expect(await readFile(join(root, 'one.txt'), 'utf8')).toBe('first original');
+ expect(await readFile(join(root, 'two.txt'), 'utf8')).toBe('owner edit');
+ expect(await readdir(stateDirectory)).toEqual([]);
+ }));
diff --git a/skills/kiln-setup-workspace/SKILL.md b/skills/kiln-setup-workspace/SKILL.md
index b1e637f9..3f6efd58 100644
--- a/skills/kiln-setup-workspace/SKILL.md
+++ b/skills/kiln-setup-workspace/SKILL.md
@@ -1,6 +1,6 @@
---
name: kiln-setup-workspace
-description: Create and verify a Kiln asset workspace for a chosen coding-agent harness. Use before authoring when the current directory is the engine repository, an empty folder, or any project without a working kiln_workspace server.
+description: Configure and verify Kiln in an existing project or a new asset workspace for the selected coding agent. Use before authoring when the project has no working kiln_workspace server or needs another agent integration; engine development stays in the engine checkout.
license: MIT
metadata:
kiln-workflow: workspace
@@ -20,13 +20,16 @@ Do not author assets inside the engine checkout. The authoring skills assume a w
When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `bin/kiln-setup-workspace.mjs` (plugin 1.0.0 used `scripts/setup-workspace.mjs`). Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.
-Choose an absolute path to an empty directory outside the checkout.
+Choose the user's existing project or an absolute path for a new workspace outside the engine installation. Check the installed initializer's `--help`: this setup version supports `--adopt`; older engines support only empty destinations. Upgrade an older installation explicitly before adopting a populated project.
```bash
-node scripts/create-workspace.mjs /absolute/empty-workspace --harness claude
+node scripts/create-workspace.mjs /absolute/project --adopt --harness claude --check
+node scripts/create-workspace.mjs /absolute/project --adopt --harness claude
```
-From an installed package, the equivalent is `kiln-init /absolute/empty-workspace --harness claude`. Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional scene-composition and trial-dispatch workflows. Use the harness already selected by the user or current host; ask only when it is unknown. The choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+From an installed package, use `kiln-init` with the same arguments. Check reports planned changes and exits 1 when changes are needed; it writes nothing. Adoption preserves existing instruction files, unrelated settings, assets and skills. Read the returned `instructions` file (`.kiln/AGENTS.md`) and `.kiln/START.md`, alongside the project's existing instructions. Conflicts stop setup before writes; do not delete or replace owner configuration to make the command pass.
+
+Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional workflows. Use the agent selected by the user or current host; ask only when it is unknown. Repeat `--adopt --harness codex` (or another supported adapter) to add that integration around the same program store. It explicitly migrates a legacy managed workspace while preserving assets. A combination whose config formats conflict is reported before changes; do not force one client's configuration into another. The plain empty-directory setup command remains compatible with older workflows.
CLI/MCP workspaces use the shared skills under `skills/`. Kiln's optional built-in Strands agent adds its workflow internally, outside that directory. Do not copy its system prompt, native workflow skill or completion protocol into another harness's skills or instructions. This applies to manual setup and plugin installs too; the engine's `src/agent/` directory is not a skill source.
@@ -37,24 +40,18 @@ CLI/MCP workspaces use the shared skills under `skills/`. Kiln's optional built-
| `cursor-agent` | `cursor-agent` |
| `opencode` | `opencode` |
| `agy` | `node agy.mjs` |
-| `codex` | `node codex.mjs` |
+| `codex` | `codex` after project trust; `node codex.mjs "TASK"` for a headless run |
| `hermes` | `node hermes.mjs` |
-**Use the launcher where the table names one, and read the workspace's own START.md over this table.** Antigravity, Codex and Hermes keep all configuration in a user-level home and read nothing from a project directory, so their workspace configuration is applied per invocation by the generated launcher. Running their bare command inside the workspace reaches no Kiln tools at all. None of the three writes outside the workspace, and none touches the user's existing configuration or authentication.
+Read `.kiln/START.md` for an adopted project, or `START.md` in a legacy workspace. Codex reads trusted project configuration from `.codex/config.toml`; its optional headless launcher supplies the same settings per invocation without relocating authentication. Antigravity and Hermes use their generated launchers for the measured workspace flow. Setup does not grant project trust or edit global credentials. Skill registration is client-specific: Claude uses `.claude/skills`, Codex uses `.agents/skills`, and OpenCode uses its configured skills path, all copied from the same maintained Kiln skills.
Hermes needs one user-level registration for the MCP server, because it has no project-scoped equivalent and no per-invocation flag for one. Its START.md prints the exact `hermes mcp add` command; offer to run it, and verify with `hermes mcp list`. Never redirect `HERMES_HOME` at the workspace: that one variable resolves the configuration path and the credential path together, so pointing it at a workspace leaves the run with no provider.
-## Start the GPU render service
-
-Setup asks for render mode `auto`: textured or metallic scenes use a compatible GPU service, starting one lazily when available. Ordinary untextured scenes with zero metalness and no advanced material extensions use CPU views, even with a GPU available. CPU views support silhouette, proportion and contact review, but cannot confirm PBR appearance. Use CLI `--render gpu` when material review is required, including roughness on nonmetallic surfaces.
-
-The renderer code is included with Kiln; its native GPU dependency is optional at the Kiln package root. For material-dependent tasks, check `node kiln.mjs service status` before starting the authoring session. If dependencies are missing or incompatible, reinstall the official Kiln package with optional dependencies enabled. npm 11 may print an `install-scripts` warning for the optional `webgpu` package; its postinstall only clears the macOS download quarantine from the prebuilt Dawn binary the package ships, so Windows and Linux need nothing and the warning is not an install failure. Read `runtime` from `.kiln/workspace.json` to identify the installation. A source checkout uses `bun install --frozen-lockfile` at that root. Setup checks dependency resolution without loading native code; ready dependencies alone do not prove the device can render.
+## Check rendering readiness
-Once dependencies are available, local CLI/MCP auto mode starts a managed service lazily for a view that needs PBR shading. Compatible clients share it; it survives the initiating session and exits after five minutes without admitted uploads, queued jobs or active renders. From the installation root, `node --import ./render-service/src/register-hooks.mjs render-service/src/server.mjs` starts a manual service that remains running while idle. It binds loopback; widening `HOST` requires `RENDER_SERVICE_TOKEN`.
+Setup selects render mode `auto`. Textured or metallic scenes use a compatible render service; plain scenes use CPU geometry views. CPU views cannot confirm PBR appearance. Check `node kiln.mjs service status` before material-dependent work and require a real `viewFidelity` result before claiming material evidence.
-`node kiln.mjs service status` reports installation, verified health and lifetime. `node kiln.mjs service start` joins a compatible service or starts a managed one the way an on-demand view does, and prints its port, renderer, pid, lifetime and build; it starts nothing when a stale, foreign or unknown listener holds the socket. After dependency repair or a cached startup failure, call `kiln_renderer({action:"reprobe"})` inside the MCP session to refresh its existing route. It neither installs dependencies nor starts a renderer; the next view starts one if needed. CLI `service reprobe` checks only its own process. Restart the session after changing Kiln, environment variables or credentials. Unknown or incompatible listeners are reported and left alone. `service stop` explicitly stops a verified local service. If no usable GPU is available, report the material-review limitation and continue on CPU views when that fits the task.
-
-A `KILN_RENDER_PORT_URL` whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) takes the local route: it starts on demand and restarts after an idle exit. For rendering on another device, configure the MCP server process's `KILN_RENDER_PORT_URL` and, when needed, `KILN_RENDER_TOKEN` through the chosen harness. CLI accepts `--render-port URL` and reads `KILN_RENDER_TOKEN`. Start a compatible Kiln renderer on that device; its wider bind requires `RENDER_SERVICE_TOKEN` unless an authenticated proxy is explicitly configured. Manage the remote service on its own device. Verify the selected route with capabilities and require an actual `viewFidelity` receipt for material evidence.
+Read [local renderer setup](references/renderer-setup.md) when dependencies are missing, a service is unavailable, or the task uses a renderer on another device. It covers dependency repair, shared-service lifetime, reprobe and authenticated remote rendering. Do not replace an unknown listener or install dependencies merely to clear a diagnostic.
## Verify the loadout before authoring
@@ -97,7 +94,9 @@ node /current/kiln/scripts/create-workspace.mjs /absolute/empty-workspace --repa
Repair rewrites generated runtime paths only. It preserves copied skills, saved revisions and assets, refuses configuration that was edited by hand, and does not upgrade the skills.
-For an existing workspace, stop its harness/MCP session and run setup from the desired installation with `--check`, then `--upgrade`. Check returns JSON and exits 1 when an update is required. Upgrade refreshes unchanged configuration, instructions and all registered skill copies while preserving assets and source stores. Conflicting local edits stop the whole upgrade before writing. Older instruction files without ownership hashes also require explicit resolution: preserve them separately, compare against a fresh temporary workspace, then move them aside or supply the current version before retrying. Reapply compatible customizations after upgrading. Do not overwrite an edited file merely to clear a conflict.
+For an existing workspace, stop its harness/MCP session and run setup from the desired installation with `--check`, then `--upgrade`. Check returns JSON and exits 1 when an update is required. Upgrade refreshes unchanged owned configuration, instructions and registered skill copies while preserving assets and source stores. Conflicting local edits stop the whole upgrade before writing. Adopted projects preserve unrelated configuration changes and leave pre-existing instruction files alone. Legacy instruction files without ownership hashes can require explicit resolution; preserve them before resolving the named conflict. Do not overwrite an edited file merely to clear a diagnostic.
+
+If adopted-project setup stops partway through writing, it attempts rollback. When it reports recovery required, preserve the project and run `kiln-init /absolute/project --recover` after confirming setup has stopped. Recovery refuses conflicting edits and retains its private snapshots outside the project. Resolve named conflicts explicitly; do not delete a lock or journal to force another setup. Recovery is for interrupted setup, not a general asset backup.
New managed launchers reject runtime/skill mismatches before serving tools; older workspaces need this explicit check first. Restart the harness/MCP session after upgrading so cached tool schemas and instructions match. `--repair` alone does not refresh copied skills or a running session. For independent model evaluations, create a fresh workspace from the candidate.
@@ -105,4 +104,4 @@ Discovery replaces the removed `kiln_list_primitives` tool; its old `name`, `nam
## What isolation means
-A separate workspace limits task context. It is not an operating-system sandbox, and it is not a git repository. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md` in the engine checkout, which covers recording inherited context and reporting trials.
+A separate workspace limits task context; an adopted project retains its existing application context and Git repository. Neither is an operating-system sandbox. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, use a fresh workspace and read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md`, which covers inherited context and reporting trials.
diff --git a/skills/kiln-setup-workspace/references/plugin-install.md b/skills/kiln-setup-workspace/references/plugin-install.md
index c3f933f7..5050fcca 100644
--- a/skills/kiln-setup-workspace/references/plugin-install.md
+++ b/skills/kiln-setup-workspace/references/plugin-install.md
@@ -17,8 +17,11 @@ installation, confirm and use that file instead. Plugin and engine versions are
independent. `runtime.json` always names the exact engine to install.
For a fresh workspace, use an absolute empty destination outside both the plugin
-and its runtime data directory. Select `claude` or `codex` from the current host
-or the user's stated choice:
+and its runtime data directory. Select the current host or the user's stated
+adapter. New bundles list the engine's supported adapters in `runtime.json`;
+older bundles without that list accept `claude` or `codex` only. The plugin itself
+is installed in Claude Code or Codex, but its helper can configure another adapter
+supported by the pinned engine:
```sh
node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --harness codex
@@ -32,11 +35,23 @@ or `$XDG_DATA_HOME/instruktlabs/kiln` on other systems, falling back to
Do not place it or the asset workspace inside a removable plugin version directory.
Read the returned workspace's `START.md`. Open Claude Code in that workspace, or
-launch Codex there with `node codex.mjs`. Accept the host's ordinary project/MCP
+launch Codex there with `codex`. The `node codex.mjs "TASK"` launcher is for
+headless execution with an explicit prompt. Accept the host's ordinary project/MCP
trust prompts, then call `kiln_discover({capabilities:true})` on `kiln_workspace`.
Compare its installation identity to `.kiln/workspace.json`; a config file alone
does not prove the server loaded. The plugin itself starts no global MCP server.
+For an existing project, use a plugin whose helper advertises `--adopt` and whose
+pinned engine supports project adoption. The published engine 1.0.0 predates this
+feature. The helper checks the engine capability and refuses unsupported adoption
+instead of silently falling back to empty-folder setup. Preview with
+`--adopt --check --harness codex`, then apply with `--adopt --harness codex`.
+Use the same path with another `--harness` to add an integration around the same
+assets. Read the returned `instructions` path and `.kiln/START.md`; existing project
+instruction files remain intact. The helper still leaves normal client trust
+prompts to the host. No manual changes to a plugin's runtime pin are needed or
+appropriate.
+
If the current workspace already has a working `kiln_workspace`, keep it. Do not
create a second server. Use its installed authoring skills, which come from its
engine version. The plugin supplies only setup, so authoring instructions are not
diff --git a/skills/kiln-setup-workspace/references/renderer-setup.md b/skills/kiln-setup-workspace/references/renderer-setup.md
new file mode 100644
index 00000000..8cdd06cd
--- /dev/null
+++ b/skills/kiln-setup-workspace/references/renderer-setup.md
@@ -0,0 +1,11 @@
+# Local renderer setup
+
+Setup asks for render mode `auto`: textured or metallic scenes use a compatible GPU service, starting one lazily when available. Ordinary untextured scenes with zero metalness and no advanced material extensions use CPU views, even with a GPU available. CPU views support silhouette, proportion and contact review, but cannot confirm PBR appearance. Use CLI `--render gpu` when material review is required, including roughness on nonmetallic surfaces.
+
+The renderer code is included with Kiln; its native GPU dependency is optional at the Kiln package root. For material-dependent tasks, check `node kiln.mjs service status` before starting the authoring session. If dependencies are missing or incompatible, reinstall the official Kiln package with optional dependencies enabled. npm 11 may print an `install-scripts` warning for the optional `webgpu` package; its postinstall only clears the macOS download quarantine from the prebuilt Dawn binary the package ships, so Windows and Linux need nothing and the warning is not an install failure. Read `runtime` from `.kiln/workspace.json` to identify the installation. A source checkout uses `bun install --frozen-lockfile` at that root. Setup checks dependency resolution without loading native code; ready dependencies alone do not prove the device can render.
+
+Once dependencies are available, local CLI/MCP auto mode starts a managed service lazily for a view that needs PBR shading. Compatible clients share it; it survives the initiating session and exits after five minutes without admitted uploads, queued jobs or active renders. From the installation root, `node --import ./render-service/src/register-hooks.mjs render-service/src/server.mjs` starts a manual service that remains running while idle. It binds loopback; widening `HOST` requires `RENDER_SERVICE_TOKEN`.
+
+`node kiln.mjs service status` reports installation, verified health and lifetime. `node kiln.mjs service start` joins a compatible service or starts a managed one the way an on-demand view does, and prints its port, renderer, pid, lifetime and build; it starts nothing when a stale, foreign or unknown listener holds the socket. After dependency repair or a cached startup failure, call `kiln_renderer({action:"reprobe"})` inside the MCP session to refresh its existing route. It neither installs dependencies nor starts a renderer; the next view starts one if needed. CLI `service reprobe` checks only its own process. Restart the session after changing Kiln, environment variables or credentials. Unknown or incompatible listeners are reported and left alone. `service stop` explicitly stops a verified local service. If no usable GPU is available, report the material-review limitation and continue on CPU views when that fits the task.
+
+A `KILN_RENDER_PORT_URL` whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) takes the local route: it starts on demand and restarts after an idle exit. For rendering on another device, configure the MCP server process's `KILN_RENDER_PORT_URL` and, when needed, `KILN_RENDER_TOKEN` through the chosen harness. CLI accepts `--render-port URL` and reads `KILN_RENDER_TOKEN`. Start a compatible Kiln renderer on that device; its wider bind requires `RENDER_SERVICE_TOKEN` unless an authenticated proxy is explicitly configured. Manage the remote service on its own device. Verify the selected route with capabilities and require an actual `viewFidelity` receipt for material evidence.
diff --git a/src/engine-identity.ts b/src/engine-identity.ts
index 909b701b..c73e1585 100644
--- a/src/engine-identity.ts
+++ b/src/engine-identity.ts
@@ -27,7 +27,7 @@
* `src/__tests__/package-contents.test.ts` fails if it disagrees with the manifest
* or with any plugin manifest, which is what keeps the literal honest.
*/
-export const ENGINE_VERSION = '1.0.0';
+export const ENGINE_VERSION = '1.1.0-dev.1';
/**
* Where this engine was loaded from, as a `file://` URL of the package root.
diff --git a/src/evaluator/isolated-validator.test.ts b/src/evaluator/isolated-validator.test.ts
new file mode 100644
index 00000000..13da0c82
--- /dev/null
+++ b/src/evaluator/isolated-validator.test.ts
@@ -0,0 +1,53 @@
+import { expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { resolve } from 'node:path';
+import { renderGLBInProcess } from '../render';
+import { isolatedEvaluatorLaunch } from './isolation';
+
+test('isolated Node flags retain Khronos validation and remove the prototype mutation accessor', async () => {
+ const launch = isolatedEvaluatorLaunch(
+ '/app/node_modules/@instruktlabs/kiln/lib/evaluator/worker.js',
+ { platform: 'linux', pathExists: () => true },
+ );
+ const nodeIndex = launch.args.lastIndexOf('/usr/local/bin/node');
+ expect(nodeIndex).toBeGreaterThan(0);
+ const runtimeFlags = launch.args.slice(nodeIndex + 1, -1);
+ const { glb } = await renderGLBInProcess(
+ 'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}',
+ );
+ // Exercise the actual dependency with the launcher's Node flags on every OS.
+ // This does not claim to qualify Linux namespaces or replace the real VM job.
+ const child = spawnSync(
+ 'node',
+ [
+ ...runtimeFlags,
+ '--input-type=module',
+ '--eval',
+ `import assert from 'node:assert/strict';
+ import { validateBytes } from 'gltf-validator';
+ const report = await validateBytes(Buffer.from('${glb.toString('base64')}', 'base64'));
+ assert.equal(report.issues.numErrors, 0);
+ assert.equal(Object.hasOwn(Object.prototype, '__proto__'), false);
+ const target = Object.assign({}, JSON.parse('{"__proto__":{"polluted":true}}'));
+ assert.equal(Object.getPrototypeOf(target), Object.prototype);
+ assert.equal(target.polluted, undefined);
+ console.log('validator-passed-prototype-accessor-absent');`,
+ ],
+ {
+ cwd: resolve(import.meta.dir, '../..'),
+ encoding: 'utf8',
+ timeout: 10000,
+ maxBuffer: 16 * 1024,
+ windowsHide: true,
+ env: {
+ PATH: process.env['PATH'] ?? process.env['Path'],
+ ...(process.platform === 'win32' ? { SystemRoot: process.env['SystemRoot'] } : {}),
+ NODE_ENV: 'production',
+ NO_COLOR: '1',
+ },
+ },
+ );
+ expect(child.stderr).toBe('');
+ expect(child.status).toBe(0);
+ expect(child.stdout.trim()).toBe('validator-passed-prototype-accessor-absent');
+});
diff --git a/src/evaluator/isolation.test.ts b/src/evaluator/isolation.test.ts
index 714ce302..2a4cdb99 100644
--- a/src/evaluator/isolation.test.ts
+++ b/src/evaluator/isolation.test.ts
@@ -17,6 +17,7 @@ const PATHS = new Set([
'/usr/local/bin/bwrap',
'/usr/bin/setpriv',
'/usr/bin/prlimit',
+ '/usr/bin/env',
'/usr/local/bin/node',
'/app/node_modules/@instruktlabs/kiln/src/evaluator/worker.ts',
]);
@@ -138,7 +139,10 @@ describe('isolated evaluator process contract', () => {
expect(spec.args).toContain('--clearenv');
expect(spec.args).toContain('--tmpfs');
expect(spec.args).toContain('--ro-bind');
- expect(spec.args).toContain('--preserve-fds');
+ // Bubblewrap inherits the explicit fd3 pipe; --preserve-fds is an OCI-runtime
+ // option, and --sync-fd would consume the descriptor for its own monitor.
+ expect(spec.args).not.toContain('--preserve-fds');
+ expect(spec.args).not.toContain('--sync-fd');
expect(spec.args).toContain('--cpu=65:65');
expect(spec.args).toContain('--as=6442450944:6442450944');
expect(spec.args).toContain('--nproc=64:64');
@@ -147,6 +151,19 @@ describe('isolated evaluator process contract', () => {
expect(spec.args).not.toContain('/etc');
});
+ test('clears wrapper-generated environment before starting the isolated worker', () => {
+ const spec = launch();
+ const envIndex = spec.args.indexOf('/usr/bin/env');
+ expect(envIndex).toBeGreaterThan(spec.args.indexOf('/usr/bin/prlimit'));
+ expect(spec.args.slice(envIndex, envIndex + 5)).toEqual([
+ '/usr/bin/env',
+ '-i',
+ 'NODE_ENV=production',
+ 'NO_COLOR=1',
+ '/usr/local/bin/node',
+ ]);
+ });
+
test('compiled workers retain isolation controls without requiring a TypeScript loader', () => {
const worker = '/app/node_modules/@instruktlabs/kiln/lib/evaluator/worker.js';
const spec = isolatedEvaluatorLaunch(worker, {
diff --git a/src/evaluator/isolation.ts b/src/evaluator/isolation.ts
index 45457911..6df3de12 100644
--- a/src/evaluator/isolation.ts
+++ b/src/evaluator/isolation.ts
@@ -1,5 +1,5 @@
import { spawn } from 'node:child_process';
-import { existsSync } from 'node:fs';
+import { existsSync, readlinkSync } from 'node:fs';
import { posix } from 'node:path';
import { fileURLToPath } from 'node:url';
import { isolatedWorkerUrls } from './worker-urls';
@@ -17,6 +17,7 @@ const DEFAULT_BWRAP_PATH = '/usr/local/bin/bwrap';
const DEFAULT_SETPRIV_PATH = '/usr/bin/setpriv';
const DEFAULT_PRLIMIT_PATH = '/usr/bin/prlimit';
const DEFAULT_NODE_PATH = '/usr/local/bin/node';
+const ENV_PATH = '/usr/bin/env';
const READINESS_VERSION = 'kiln.evaluator.isolation-readiness.v1';
const TRANSPORT_VERSION = 'kiln.evaluator.isolation-transport.v1';
const TRANSPORT_STDOUT_MARKER = 'kiln-evaluator-transport-boot-v1\n';
@@ -159,7 +160,7 @@ function isolatedEvaluatorLaunchWithLoader(
const setprivPath = requiredAbsolutePath(host.setprivPath ?? DEFAULT_SETPRIV_PATH);
const prlimitPath = requiredAbsolutePath(host.prlimitPath ?? DEFAULT_PRLIMIT_PATH);
const nodePath = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);
- for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath]) {
+ for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath, ENV_PATH]) {
if (!pathExists(executable)) isolationUnavailable();
}
const resolvedWorkerPath = workerInsideRuntime(workerPath, runtimeRoot);
@@ -195,14 +196,16 @@ function isolatedEvaluatorLaunchWithLoader(
for (const mount of runtimeMounts(runtimeRoot, pathExists)) {
bwrapArgs.push('--ro-bind', mount, mount);
}
- const nodeArgs = [nodePath, '--max-old-space-size=512', '--disable-proto=throw'];
+ // Remove the legacy mutation accessor. Throw mode breaks the Khronos
+ // validator's feature detection before any GLB can be validated.
+ const nodeArgs = [nodePath, '--max-old-space-size=512', '--disable-proto=delete'];
if (loader === 'tsx') nodeArgs.push('--import', 'tsx');
nodeArgs.push(resolvedWorkerPath);
bwrapArgs.push(
'--chdir',
runtimeRoot,
- '--preserve-fds',
- '1',
+ // Bubblewrap passes inherited fds to the command. The spawn caller supplies
+ // only stdio and the fd3 protocol pipe; no descriptor-preservation flag exists.
'--',
prlimitPath,
'--cpu=65:65',
@@ -211,6 +214,12 @@ function isolatedEvaluatorLaunchWithLoader(
'--nofile=64:64',
'--nproc=64:64',
'--',
+ // Bubblewrap adds PWD after --clearenv. Clear the final worker environment
+ // again instead of weakening the exact two-variable readiness invariant.
+ ENV_PATH,
+ '-i',
+ 'NODE_ENV=production',
+ 'NO_COLOR=1',
...nodeArgs,
);
@@ -435,7 +444,11 @@ async function runIsolationProbe(
export async function assertIsolatedEvaluatorReady(
host: IsolatedEvaluatorHost = {},
): Promise<EvaluatorIsolationReadiness> {
- if (typeof process.getuid !== 'function' || process.getuid() === 0) {
+ if (
+ typeof process.getuid !== 'function' ||
+ process.getuid() === 0 ||
+ process.geteuid?.() !== process.getuid()
+ ) {
throw new EvaluatorIsolationReadinessError('invariant-namespace');
}
const workers = isolatedWorkerUrls(import.meta.url);
@@ -446,6 +459,14 @@ export async function assertIsolatedEvaluatorReady(
try {
transportLaunch = isolatedEvaluatorLaunchWithLoader(transportPath, host, 'module');
probeLaunch = isolatedEvaluatorLaunch(probePath, host);
+ // Trusted parent evidence is passed as bounded probe arguments, never
+ // through the source worker's environment or generated-source protocol.
+ probeLaunch.args.push(
+ '--kiln-host-uid',
+ String(process.getuid()),
+ '--kiln-host-userns',
+ readlinkSync('/proc/self/ns/user'),
+ );
} catch {
throw new EvaluatorIsolationReadinessError('wrapper-launch');
}
diff --git a/src/evaluator/probe-invariants.test.ts b/src/evaluator/probe-invariants.test.ts
new file mode 100644
index 00000000..483723e4
--- /dev/null
+++ b/src/evaluator/probe-invariants.test.ts
@@ -0,0 +1,47 @@
+import { expect, test } from 'bun:test';
+import { parseProbeHostIdentity, processUserNamespaceIsIsolated } from './probe-invariants';
+
+const host = { uid: 1001, userNamespace: 'user:[4026531837]' };
+const child = {
+ uid: 1001,
+ effectiveUid: 1001,
+ userNamespace: 'user:[4026532441]',
+ uidMap: ' 1001 0 1\n',
+};
+
+test('the nested Bubblewrap map retains the non-root host identity in a different namespace', () => {
+ expect(processUserNamespaceIsIsolated(child, host)).toBe(true);
+ expect(processUserNamespaceIsIsolated({ ...child, uidMap: '1001 1001 1\n' }, host)).toBe(true);
+});
+
+test('a host namespace, broad map, changed user or elevated effective user cannot qualify', () => {
+ for (const override of [
+ { userNamespace: host.userNamespace },
+ { userNamespace: undefined },
+ { uidMap: '0 0 4294967295\n' },
+ { uidMap: '1001 0 1\n1002 2 1\n' },
+ { uidMap: '1001 99 1' },
+ { uidMap: undefined },
+ { uid: 0 },
+ { uid: 1002 },
+ { effectiveUid: 0 },
+ ])
+ expect(processUserNamespaceIsIsolated({ ...child, ...override }, host)).toBe(false);
+ expect(processUserNamespaceIsIsolated(child, undefined)).toBe(false);
+ expect(processUserNamespaceIsIsolated(child, { ...host, uid: 0 })).toBe(false);
+});
+
+test('probe host identity accepts only the exact bounded launch envelope', () => {
+ const argv = ['--kiln-host-uid', '1001', '--kiln-host-userns', host.userNamespace];
+ expect(parseProbeHostIdentity(argv)).toEqual(host);
+ for (const invalid of [
+ [],
+ [...argv, 'extra'],
+ ['--kiln-host-uid', '0', '--kiln-host-userns', host.userNamespace],
+ ['--kiln-host-uid', '1001junk', '--kiln-host-userns', host.userNamespace],
+ ['--kiln-host-uid', '4294967295', '--kiln-host-userns', host.userNamespace],
+ ['--kiln-host-uid', '1001', '--kiln-host-userns', 'user:[1]\n'],
+ ['--kiln-host-uid', '1001', '--kiln-host-userns', 'other:[1]'],
+ ])
+ expect(parseProbeHostIdentity(invalid)).toBeUndefined();
+});
diff --git a/src/evaluator/probe-invariants.ts b/src/evaluator/probe-invariants.ts
index 6c3fa5c1..d947ef77 100644
--- a/src/evaluator/probe-invariants.ts
+++ b/src/evaluator/probe-invariants.ts
@@ -1,5 +1,55 @@
const CAPABILITY_STATUS_FIELDS = ['CapInh', 'CapPrm', 'CapEff', 'CapBnd', 'CapAmb'] as const;
+export interface ProbeHostIdentity {
+ uid: number;
+ userNamespace: string;
+}
+
+const namespacePattern = /^user:\[[0-9]{1,20}\](?![\s\S])/;
+const nonRootUid = (uid: number) => Number.isSafeInteger(uid) && uid > 0 && uid < 0xffff_ffff;
+
+export function parseProbeHostIdentity(argv: readonly string[]): ProbeHostIdentity | undefined {
+ if (
+ argv.length !== 4 ||
+ argv[0] !== '--kiln-host-uid' ||
+ argv[2] !== '--kiln-host-userns' ||
+ !argv[1] ||
+ !/^[1-9][0-9]{0,9}(?![\s\S])/.test(argv[1]) ||
+ !argv[3] ||
+ !namespacePattern.test(argv[3])
+ )
+ return undefined;
+ const uid = Number(argv[1]);
+ return nonRootUid(uid) ? { uid, userNamespace: argv[3] } : undefined;
+}
+
+export function processUserNamespaceIsIsolated(
+ current: { uid: number; effectiveUid: number; userNamespace?: string; uidMap?: string },
+ host: ProbeHostIdentity | undefined,
+): boolean {
+ if (
+ !host ||
+ !nonRootUid(host.uid) ||
+ !namespacePattern.test(host.userNamespace) ||
+ current.uid !== host.uid ||
+ current.effectiveUid !== host.uid ||
+ typeof current.userNamespace !== 'string' ||
+ !namespacePattern.test(current.userNamespace) ||
+ current.userNamespace === host.userNamespace ||
+ typeof current.uidMap !== 'string' ||
+ current.uidMap.length > 256
+ )
+ return false;
+ const map = /^\s*([0-9]{1,10})\s+([0-9]{1,10})\s+([0-9]{1,10})\s*$/.exec(current.uidMap);
+ if (!map) return false;
+ const [, inside, outside, count] = map.map(Number);
+ // --disable-userns creates a second user namespace. With --dev, that maps
+ // our non-root UID to UID 0 in Bubblewrap's intermediate namespace, not host
+ // root. Require a different namespace, the exact unprivileged caller identity
+ // and a single-ID map; never accept an initial-namespace or broad mapping.
+ return inside === host.uid && count === 1 && (outside === 0 || outside === host.uid);
+}
+
/** Require every capability set exposed by /proc to be present and empty. */
export function processCapabilitiesAreEmpty(status: string | undefined): boolean {
if (typeof status !== 'string') return false;
diff --git a/src/evaluator/probe-worker.ts b/src/evaluator/probe-worker.ts
index 25c51c62..05cc2db2 100644
--- a/src/evaluator/probe-worker.ts
+++ b/src/evaluator/probe-worker.ts
@@ -1,9 +1,13 @@
-import { readFile, writeFile } from 'node:fs/promises';
+import { readFile, readlink, writeFile } from 'node:fs/promises';
import { connect } from 'node:net';
import { networkInterfaces } from 'node:os';
import { validate } from '../validation';
import { writeFileSync } from 'node:fs';
-import { processCapabilitiesAreEmpty } from './probe-invariants';
+import {
+ parseProbeHostIdentity,
+ processCapabilitiesAreEmpty,
+ processUserNamespaceIsIsolated,
+} from './probe-invariants';
const VERSION = 'kiln.evaluator.isolation-readiness.v1';
type ProbeFailure =
@@ -105,12 +109,14 @@ function groupedFailure(failedChecks: readonly string[]): ProbeFailure {
}
function generatedDenials(): boolean {
+ if (Object.hasOwn(Object.prototype, '__proto__')) return false;
const prelude = "const meta = { name: 'probe' }; function build(){ return createRoot('probe'); }";
const probes = [
`const leak = process.env; ${prelude}`,
`const leak = fetch('http://169.254.169.254/'); ${prelude}`,
`const leak = globalThis.process.mainModule.require('fs'); ${prelude}`,
`const leak = globalThis.process.mainModule.require('child_process'); ${prelude}`,
+ `const leak = ({}).constructor.constructor('return process')(); ${prelude}`,
];
return probes.every((source) => !validate(source).valid);
}
@@ -119,11 +125,23 @@ async function main(): Promise<void> {
const status = await optionalRead('/proc/self/status');
const uidMap = await optionalRead('/proc/self/uid_map');
const envKeys = Object.keys(process.env).sort();
- const outsideUid = Number(uidMap?.trim().split(/\s+/)[1]);
+ const userNamespace = await readlink('/proc/self/ns/user').catch(() => undefined);
+ const hostIdentity = parseProbeHostIdentity(process.argv.slice(2));
const interfaceMap = isolationInterfaces();
const interfaces = interfaceMap ? Object.values(interfaceMap).flat().filter(Boolean) : undefined;
const checks: Array<[string, boolean]> = [
- ['user-namespace', Number.isInteger(outsideUid) && outsideUid > 0],
+ [
+ 'user-namespace',
+ processUserNamespaceIsIsolated(
+ {
+ uid: process.getuid?.() ?? -1,
+ effectiveUid: process.geteuid?.() ?? -1,
+ uidMap,
+ userNamespace,
+ },
+ hostIdentity,
+ ),
+ ],
['no-new-privileges', typeof status === 'string' && /^NoNewPrivs:\s+1$/m.test(status)],
['capabilities-empty', processCapabilitiesAreEmpty(status)],
['environment-exact', envKeys.join(',') === 'NODE_ENV,NO_COLOR'],