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.

Prepare Kiln v1 package, plugins and hosted MCP (#145)

Matthew Kissingerce640ccae0c6
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
new file mode 100644
index 00000000..7b6c68de
--- /dev/null
+++ b/.agents/plugins/marketplace.json
@@ -0,0 +1,20 @@
+{
+ "name": "instruktlabs",
+ "interface": {
+ "displayName": "Instrukt Labs"
+ },
+ "plugins": [
+ {
+ "name": "kiln-engine",
+ "source": {
+ "source": "local",
+ "path": "./plugins/kiln-engine"
+ },
+ "policy": {
+ "installation": "AVAILABLE",
+ "authentication": "ON_INSTALL"
+ },
+ "category": "Developer Tools"
+ }
+ ]
+}
diff --git a/.agents/skills/kiln-setup-workspace/SKILL.md b/.agents/skills/kiln-setup-workspace/SKILL.md
index d675789f..2f0aef1c 100644
--- a/.agents/skills/kiln-setup-workspace/SKILL.md
+++ b/.agents/skills/kiln-setup-workspace/SKILL.md
@@ -8,7 +8,7 @@ metadata:
# Set up a workspace for asset authoring
-This repository is the engine. Asset authoring happens in a separate workspace, and the two are different tasks with different tools. Establish which one is being asked before running anything.
+Kiln's engine installation and its asset workspaces serve different tasks. Establish whether the user wants asset authoring or engine development before running anything.
Authoring an asset needs a workspace. Changing the engine's own behaviour does not; read `AGENTS.md` at the repository root instead and stay in the checkout.
@@ -18,13 +18,15 @@ Do not author assets inside the engine checkout. The authoring skills assume a w
## Create the workspace
+When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `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.
```bash
node scripts/create-workspace.mjs /absolute/empty-workspace --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. Ask the user which harness they use rather than assuming; the choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+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.
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.
diff --git a/.agents/skills/kiln-setup-workspace/references/plugin-install.md b/.agents/skills/kiln-setup-workspace/references/plugin-install.md
new file mode 100644
index 00000000..09df1184
--- /dev/null
+++ b/.agents/skills/kiln-setup-workspace/references/plugin-install.md
@@ -0,0 +1,66 @@
+# Local plugin setup
+
+The local `kiln-engine` plugin installs Kiln's exact pinned npm version and creates
+an asset workspace. It carries setup guidance and a small installer; the engine,
+source stores and authored assets live outside the plugin cache. It needs a
+supported Node.js installation with npm, network access for first installation,
+and no separate model API key.
+
+Resolve the plugin root from this installed skill's absolute path: it is two
+directories above `skills/kiln-setup-workspace`. Confirm `runtime.json` and
+`scripts/setup-workspace.mjs` exist there. Do not assume plugin path variables are
+available in an ordinary shell, and do not substitute an engine checkout.
+
+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:
+
+```sh
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --harness codex
+```
+
+The installer verifies the package name and exact version from `runtime.json`.
+It uses npm with lifecycle scripts disabled and optional dependencies included.
+The versioned engine stays under `%LOCALAPPDATA%/InstruktLabs/Kiln` on Windows,
+or `$XDG_DATA_HOME/instruktlabs/kiln` on other systems, falling back to
+`~/.local/share/instruktlabs/kiln`. `--data-dir` selects another persistent directory.
+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
+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.
+
+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
+registered twice. An old global plugin/server named `kiln` is a separate
+installation: explain the conflict and surface its removal or disabling before
+continuing; do not silently redirect stores or edit global configuration.
+
+For an existing managed workspace, stop its harness session and run the new
+plugin's helper with `--check`, then `--upgrade` when an update is intended:
+
+```sh
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --check
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --upgrade
+```
+
+Check is read-only and reports a missing pinned engine without installing it.
+Upgrade installs that version when needed, then delegates to Kiln's managed
+upgrade. It preserves sources and saved assets and refuses conflicting edits to
+managed files. Resolve those conflicts explicitly rather than overwriting them.
+Use the same `--data-dir` if setup used a custom location. `--repair` corrects
+relocated paths without updating copied skills. Restart the harness afterward.
+
+For release qualification only, `--archive /absolute/candidate.tgz` installs a
+reviewed local archive with the same required identity. Different archive bytes
+at the same version need a separate data directory. An unpublished development
+plugin is not a working registry release; use its reviewed development archive.
+
+If installation fails, report the error. An unknown existing runtime is never
+replaced automatically. A setup lock may belong to another running installer;
+verify that process has stopped before removing a stale lock. If npm cannot be
+located, fix the Node/npm installation or pass `--npm-cli` with its actual
+`npm-cli.js` path. Never request registry credentials for this public package.
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index be97dbae..6bf74632 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -1,17 +1,19 @@
{
"$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "kiln",
- "description": "Kiln: local tools and skills for building, inspecting and revising procedural 3D assets.",
+ "name": "instruktlabs",
+ "description": "Instrukt Labs developer tools, including Kiln Engine for editable 3D assets.",
"owner": {
- "name": "Matthew Kissinger"
+ "name": "Instrukt Labs"
},
"plugins": [
{
- "name": "kiln",
- "description": "Build 3D assets, inspect selected views, edit saved source revisions and export GLB files with your coding agent.",
- "author": { "name": "Matthew Kissinger" },
+ "name": "kiln-engine",
+ "description": "Set up a pinned local Kiln engine and an asset workspace with MCP tools and authoring skills.",
+ "author": {
+ "name": "Instrukt Labs"
+ },
"category": "development",
- "source": "./"
+ "source": "./plugins/kiln-engine"
}
]
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index a0bd60db..3966c063 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,11 +1,11 @@
{
"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": "0.10.0",
+ "version": "1.0.0-rc.1",
"author": {
"name": "Matthew Kissinger"
},
- "homepage": "https://github.com/matthew-kissinger/kiln",
+ "homepage": "https://github.com/instruktlabs/kiln",
"license": "MIT",
"keywords": [
"3d",
diff --git a/.claude/skills/kiln-setup-workspace/SKILL.md b/.claude/skills/kiln-setup-workspace/SKILL.md
index d675789f..2f0aef1c 100644
--- a/.claude/skills/kiln-setup-workspace/SKILL.md
+++ b/.claude/skills/kiln-setup-workspace/SKILL.md
@@ -8,7 +8,7 @@ metadata:
# Set up a workspace for asset authoring
-This repository is the engine. Asset authoring happens in a separate workspace, and the two are different tasks with different tools. Establish which one is being asked before running anything.
+Kiln's engine installation and its asset workspaces serve different tasks. Establish whether the user wants asset authoring or engine development before running anything.
Authoring an asset needs a workspace. Changing the engine's own behaviour does not; read `AGENTS.md` at the repository root instead and stay in the checkout.
@@ -18,13 +18,15 @@ Do not author assets inside the engine checkout. The authoring skills assume a w
## Create the workspace
+When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `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.
```bash
node scripts/create-workspace.mjs /absolute/empty-workspace --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. Ask the user which harness they use rather than assuming; the choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+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.
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.
diff --git a/.claude/skills/kiln-setup-workspace/references/plugin-install.md b/.claude/skills/kiln-setup-workspace/references/plugin-install.md
new file mode 100644
index 00000000..09df1184
--- /dev/null
+++ b/.claude/skills/kiln-setup-workspace/references/plugin-install.md
@@ -0,0 +1,66 @@
+# Local plugin setup
+
+The local `kiln-engine` plugin installs Kiln's exact pinned npm version and creates
+an asset workspace. It carries setup guidance and a small installer; the engine,
+source stores and authored assets live outside the plugin cache. It needs a
+supported Node.js installation with npm, network access for first installation,
+and no separate model API key.
+
+Resolve the plugin root from this installed skill's absolute path: it is two
+directories above `skills/kiln-setup-workspace`. Confirm `runtime.json` and
+`scripts/setup-workspace.mjs` exist there. Do not assume plugin path variables are
+available in an ordinary shell, and do not substitute an engine checkout.
+
+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:
+
+```sh
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --harness codex
+```
+
+The installer verifies the package name and exact version from `runtime.json`.
+It uses npm with lifecycle scripts disabled and optional dependencies included.
+The versioned engine stays under `%LOCALAPPDATA%/InstruktLabs/Kiln` on Windows,
+or `$XDG_DATA_HOME/instruktlabs/kiln` on other systems, falling back to
+`~/.local/share/instruktlabs/kiln`. `--data-dir` selects another persistent directory.
+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
+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.
+
+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
+registered twice. An old global plugin/server named `kiln` is a separate
+installation: explain the conflict and surface its removal or disabling before
+continuing; do not silently redirect stores or edit global configuration.
+
+For an existing managed workspace, stop its harness session and run the new
+plugin's helper with `--check`, then `--upgrade` when an update is intended:
+
+```sh
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --check
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --upgrade
+```
+
+Check is read-only and reports a missing pinned engine without installing it.
+Upgrade installs that version when needed, then delegates to Kiln's managed
+upgrade. It preserves sources and saved assets and refuses conflicting edits to
+managed files. Resolve those conflicts explicitly rather than overwriting them.
+Use the same `--data-dir` if setup used a custom location. `--repair` corrects
+relocated paths without updating copied skills. Restart the harness afterward.
+
+For release qualification only, `--archive /absolute/candidate.tgz` installs a
+reviewed local archive with the same required identity. Different archive bytes
+at the same version need a separate data directory. An unpublished development
+plugin is not a working registry release; use its reviewed development archive.
+
+If installation fails, report the error. An unknown existing runtime is never
+replaced automatically. A setup lock may belong to another running installer;
+verify that process has stopped before removing a stale lock. If npm cannot be
+located, fix the Node/npm installation or pass `--npm-cli` with its actual
+`npm-cli.js` path. Never request registry credentials for this public package.
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 5e064a9d..9452e8ad 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "kiln",
- "version": "0.10.0",
+ "version": "1.0.0-rc.1",
"description": "Create, review, save, and refine procedural 3D assets with portable source and GLB collections.",
"author": {
"name": "Matthew Kissinger"
@@ -10,7 +10,7 @@
"displayName": "Kiln",
"shortDescription": "Build and collect editable 3D assets",
"longDescription": "Author JavaScript, inspect camera views, and save GLBs with source revisions for later refinement.",
- "developerName": "Matthew Kissinger",
+ "developerName": "Instrukt Labs",
"category": "Developer Tools",
"capabilities": [
"Read",
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6918096f..2c4e4fdf 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -47,6 +47,9 @@ jobs:
- name: Install
run: bun install --frozen-lockfile
+ - name: Build compiled SDK for public-entrypoint checks
+ run: bun run build:sdk
+
- name: Typecheck
run: bun run typecheck
@@ -126,6 +129,9 @@ jobs:
- name: Install
run: bun install --frozen-lockfile
+ - name: Build compiled SDK for public-entrypoint checks
+ run: bun run build:sdk
+
- name: Typecheck
run: bun run typecheck
@@ -201,10 +207,17 @@ jobs:
run: |
mkdir candidate
npm pack --ignore-scripts --pack-destination candidate
+ - name: Verify installed SDK and consumer types
+ run: |
+ set -- candidate/*.tgz
+ test "$#" -eq 1
+ node scripts/smoke-package.mjs --tarball "$1" --types > candidate/candidate-sdk-receipt.json
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: node-package-candidate
- path: candidate/*.tgz
+ path: |
+ candidate/*.tgz
+ candidate/candidate-sdk-receipt.json
if-no-files-found: error
retention-days: 14
@@ -388,7 +401,7 @@ jobs:
# This explicit probe permits software adapters. Production rendering still
# rejects them; this tests native Vulkan plumbing, not physical GPU support.
- name: Exercise textured readback on software Vulkan
- run: node scripts/smoke-renderer.mjs ./installation/node_modules/@kiln/engine renderer-receipt software
+ run: node scripts/smoke-renderer.mjs ./installation/node_modules/@instruktlabs/kiln renderer-receipt software
- name: Retain renderer identity and images
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
diff --git a/.github/workflows/hosted-gateway.yml b/.github/workflows/hosted-gateway.yml
new file mode 100644
index 00000000..7a95002a
--- /dev/null
+++ b/.github/workflows/hosted-gateway.yml
@@ -0,0 +1,74 @@
+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
new file mode 100644
index 00000000..9654d6d7
--- /dev/null
+++ b/.github/workflows/hosting-probe.yml
@@ -0,0 +1,194 @@
+name: Native hosting preflight
+
+on:
+ pull_request:
+ branches: [main]
+ paths:
+ - .github/workflows/hosting-probe.yml
+ - scripts/hosting/**
+ - scripts/smoke-renderer.mjs
+ - src/evaluator/**
+ - render-service/**
+ - package.json
+ - bun.lock
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+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.
+jobs:
+ image-preflight:
+ name: Linux image isolation and software rendering
+ runs-on: ubuntu-24.04
+ timeout-minutes: 25
+ 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 a six-file context and record candidate identity
+ shell: bash
+ run: |
+ set -euo pipefail
+ mkdir -p .cache/hosting-ci/context .cache/hosting-ci/receipts
+ context="$PWD/.cache/hosting-ci/context"
+ receipts="$PWD/.cache/hosting-ci/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 scripts/hosting/Dockerfile scripts/hosting/native-qualification.mjs \
+ scripts/hosting/run-native-qualification.mjs scripts/smoke-renderer.mjs "$context/"
+ test "$(find "$context" -mindepth 1 -maxdepth 1 -type f | wc -l)" -eq 6
+ cp "$context/candidate.sha256" "$receipts/"
+ node --input-type=module -e '
+ import { writeFileSync } from "node:fs";
+ writeFileSync(".cache/hosting-ci/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-docker",
+ cloudflareQualified: false
+ }, null, 2) + "\n");'
+
+ - name: Build the non-root image without publishing it
+ id: image
+ shell: bash
+ run: |
+ set -euo pipefail
+ docker build --platform linux/amd64 --tag kiln-native-probe:ci \
+ .cache/hosting-ci/context 2>&1 | tee .cache/hosting-ci/receipts/image-build.log
+ docker image inspect kiln-native-probe:ci --format \
+ '{"id":{{json .Id}},"os":{{json .Os}},"arch":{{json .Architecture}},"user":{{json .Config.User}},"layers":{{json .RootFS.Layers}}}' \
+ > .cache/hosting-ci/receipts/image.json
+ test "$(docker image inspect kiln-native-probe:ci --format '{{.Config.User}}')" = node
+ # A never-started container lets us retain the image inventories even if
+ # source isolation fails before the renderer is reached.
+ docker create --name kiln-probe-inventory kiln-native-probe:ci
+ docker cp kiln-probe-inventory:/app/package-lock.json .cache/hosting-ci/receipts/package-lock.json
+ docker cp kiln-probe-inventory:/probe/os-packages.txt .cache/hosting-ci/receipts/os-packages.txt
+ docker cp kiln-probe-inventory:/probe/node-version.txt .cache/hosting-ci/receipts/node-version.txt
+ docker rm kiln-probe-inventory
+
+ - name: Record bounded namespace diagnostics without changing restrictions
+ if: ${{ !cancelled() && steps.image.outcome == 'success' }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ docker create --name kiln-probe-diagnostics --network none --cpus 1 \
+ --memory 6g --memory-swap 6g --pids-limit 256 --cap-drop ALL \
+ --security-opt no-new-privileges kiln-native-probe:ci \
+ node --input-type=module -e '
+ import { spawnSync } from "node:child_process";
+ import { readFileSync } from "node:fs";
+ const commands = [
+ ["/usr/bin/bwrap", "--version"],
+ ["/usr/bin/unshare", "--user", "--map-root-user", "/usr/bin/true"],
+ ["/usr/bin/bwrap", "--unshare-all", "--unshare-user", "--disable-userns", "--die-with-parent",
+ "--ro-bind", "/usr", "/usr", "--symlink", "usr/lib", "/lib",
+ "--symlink", "usr/lib64", "/lib64", "--", "/usr/bin/true"]
+ ];
+ const checks = commands.map(([command, ...args]) => {
+ const r = spawnSync(command, args, {env: {}, encoding: "utf8", timeout: 5000, maxBuffer: 16384});
+ return {command, args, status: r.status, signal: r.signal, error: r.error?.code,
+ stdout: r.stdout, stderr: r.stderr};
+ });
+ const files = {};
+ for (const path of ["/proc/sys/user/max_user_namespaces", "/proc/sys/kernel/unprivileged_userns_clone",
+ "/proc/sys/kernel/apparmor_restrict_unprivileged_userns", "/sys/fs/cgroup/cpu.stat"]) {
+ try { files[path] = readFileSync(path, "utf8").slice(0, 4096); } catch { files[path] = null; }
+ }
+ console.log(JSON.stringify({scope: "fixed diagnostics only; not isolation qualification", uid: process.getuid(), checks, files}));'
+ 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
+ if: ${{ !cancelled() && steps.image.outcome == 'success' }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ 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
+ set +e
+ timeout --signal=TERM --kill-after=15s 240s docker start --attach kiln-probe-isolation \
+ > "$receipts/isolation.log" 2>&1
+ attached_status=$?
+ set -e
+ if [ "$(docker inspect kiln-probe-isolation --format '{{.State.Running}}')" = true ]; then
+ docker kill kiln-probe-isolation
+ fi
+ docker inspect kiln-probe-isolation --format '{{json .State}}' > "$receipts/isolation-state.json"
+ printf '%s\n' "$attached_status" > "$receipts/isolation-attach-exit.txt"
+ # A missing receipt is a failed probe; the log/state above still survives.
+ 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)'
+
+ - name: Diagnose the trusted software-renderer fixture independently
+ if: ${{ !cancelled() && steps.image.outcome == 'success' }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ receipts="$PWD/.cache/hosting-ci/receipts"
+ # Fixed repository fixture only. This run does not qualify untrusted source.
+ docker create --name kiln-probe-renderer --network none --cpus 1 \
+ --memory 6g --memory-swap 6g --pids-limit 256 --cap-drop ALL \
+ --security-opt no-new-privileges kiln-native-probe:ci \
+ node /probe/smoke-renderer.mjs /app/node_modules/@instruktlabs/kiln /tmp/renderer software
+ set +e
+ timeout --signal=TERM --kill-after=15s 180s docker start --attach kiln-probe-renderer \
+ > "$receipts/renderer.log" 2>&1
+ attached_status=$?
+ set -e
+ if [ "$(docker inspect kiln-probe-renderer --format '{{.State.Running}}')" = true ]; then
+ docker kill kiln-probe-renderer
+ fi
+ docker inspect kiln-probe-renderer --format '{{json .State}}' > "$receipts/renderer-state.json"
+ printf '%s\n' "$attached_status" > "$receipts/renderer-attach-exit.txt"
+ docker cp kiln-probe-renderer:/tmp/renderer "$receipts/renderer"
+ test "$attached_status" -eq 0
+ test "$(docker inspect kiln-probe-renderer --format '{{.State.ExitCode}}')" -eq 0
+ node --input-type=module -e 'import{readFileSync}from"node:fs";const r=JSON.parse(readFileSync(".cache/hosting-ci/receipts/renderer/receipt.json"));if(r.status!=="passed"||r.software!==true)process.exit(1)'
+
+ - name: Retain evidence, including unsuccessful qualification
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: native-hosting-preflight
+ path: |
+ .cache/hosting-ci/receipts/
+ .cache/hosting-ci/context/candidate.tgz
+ include-hidden-files: true
+ if-no-files-found: error
+ retention-days: 14
+
+ - name: Remove only this job's probe containers
+ if: always()
+ shell: bash
+ run: |
+ for name in kiln-probe-inventory kiln-probe-diagnostics kiln-probe-isolation kiln-probe-renderer; do
+ if docker container inspect "$name" >/dev/null 2>&1; then
+ docker rm --force "$name"
+ fi
+ done
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 00000000..e1d6ff2f
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,98 @@
+name: Prepare npm release
+
+on:
+ workflow_dispatch:
+ inputs:
+ ci_run_id:
+ description: Successful main CI run for this exact commit
+ required: true
+ type: string
+ sha256:
+ description: Reviewed SHA-256 of its node-package-candidate tarball
+ required: true
+ type: string
+ mode:
+ description: Verify evidence, or stage the qualified archive for owner npm approval
+ required: true
+ type: choice
+ default: verify
+ options: [verify, stage]
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: kiln-npm-release
+ cancel-in-progress: false
+
+env:
+ CI_RUN_ID: ${{ inputs.ci_run_id }}
+ CANDIDATE_SHA256: ${{ inputs.sha256 }}
+ RELEASE_MODE: ${{ inputs.mode }}
+
+jobs:
+ verify:
+ if: github.repository == 'instruktlabs/kiln' && github.ref == 'refs/heads/main'
+ runs-on: ubuntu-latest
+ 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: Verify exact archive and all qualification receipts
+ id: prepare
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: node scripts/prepare-npm-release.mjs
+ - name: Retain review candidate
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: npm-release-review
+ path: ${{ steps.prepare.outputs.directory }}
+ if-no-files-found: error
+ retention-days: 30
+
+ stage:
+ if: inputs.mode == 'stage'
+ needs: verify
+ environment: npm-release
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ permissions:
+ contents: read
+ actions: read
+ id-token: write
+ 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] --ignore-scripts
+ # Recheck live CI/environment state and download fresh bytes after approval.
+ - name: Verify the approved candidate again
+ id: prepare
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: node scripts/prepare-npm-release.mjs
+ - name: Stage the verified archive with npm trusted publishing
+ shell: bash
+ env:
+ TARBALL: ${{ steps.prepare.outputs.tarball }}
+ TAG: ${{ steps.prepare.outputs.tag }}
+ REPORT_DIR: ${{ steps.prepare.outputs.directory }}
+ run: |
+ npm stage publish "$TARBALL" --ignore-scripts --access public --provenance --tag "$TAG" --registry=https://registry.npmjs.org --json | tee "$REPORT_DIR/npm-stage.json"
+ - name: Retain staging receipt
+ if: always() && steps.prepare.outcome == 'success'
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: npm-staged-candidate
+ path: ${{ steps.prepare.outputs.directory }}
+ if-no-files-found: error
+ retention-days: 30
diff --git a/.gitignore b/.gitignore
index 2bafbbe1..01991506 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,6 @@
node_modules/
+# Compiled module-preserving SDK and declarations, built for the release tarball.
+/lib/
# `dist/*` and not `dist/`: git never descends into an excluded DIRECTORY, so a
# negation under `dist/` can never match and the bundle below stayed ignored
# while the docs said it was committed.
diff --git a/AGENTS.md b/AGENTS.md
index 664d2591..6ec63151 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,15 +2,14 @@
## Scope
-This repository turns model-authored source into GLBs: deterministic rendering, QA,
-primitives, agent tools, arena ranking, scene composition, CLI and MCP + skills.
+This engine turns model-authored source into GLBs: rendering, QA, primitives,
+agent tools, arena, scenes, CLI, MCP and skills.
-Read [README.md](./README.md) before changing exports or package contents. Runtime and tests
-live under `src/`; repository checks under `scripts/`. `package.json` lists shipped files
-through `files` and `exports`. [CHANGELOG.md](./CHANGELOG.md) states what each
-release changed. Dated files under `docs/plans/` and `docs/reviews/` are records of their
-day: they never override current code, this guide or the changelog, and never imply release
-acceptance.
+Read [README.md](./README.md) before changing exports or shipped files. `src/` holds
+runtime/tests; `scripts/` holds repo checks. `package.json` owns `files` and `exports`;
+[CHANGELOG.md](./CHANGELOG.md) records releases. Dated `docs/plans/` and `docs/reviews/`
+are historical records, never overrides of code, this guide or the changelog, and
+never release acceptance.
## Authoring an asset is a different task from changing the engine
@@ -161,6 +160,7 @@ canary or implicit latest for a release gate.
bun install --frozen-lockfile
bun run check:toolchain
bun run check:skills
+bun run build:sdk
bun run typecheck
bun run lint
bun run test
@@ -168,9 +168,10 @@ bun run test:render-service
bun run test:coverage
```
-`bun run build` is a typecheck only and refreshes neither `dist/` nor its build identity. After
-runtime source changes, rebuild the Node bundles with `node scripts/build-runtime.mjs all`
-(`bun run build:runtime` when viewer assets also changed) before CLI/MCP dogfood and full gates.
+`bun run build` only typechecks. After runtime changes, run `node scripts/build-runtime.mjs all`
+to rebuild `dist/`, its identity and SDK `lib/` before CLI/MCP dogfood and full gates.
+Use `bun run build:runtime` when viewer assets also changed. Fresh checkouts need
+`bun run build:sdk` before typechecking or public-entrypoint tests.
Fast loop: nearest test file first, then `bun run typecheck && bun run lint && bun run test`.
The full offline gate adds `bun run test:coverage`, which emits `coverage/lcov.info` and
@@ -180,6 +181,8 @@ 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).
+
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
coverage ratchet cannot vary with the runner's GPU; coverage is measured over `src/` alone, and
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0a6484c4..8eda8dee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,14 +1,42 @@
# Changelog
-Changes to `@kiln/engine`. Source releases and installable package publication are
+Changes to `@instruktlabs/kiln` (previously the private `@kiln/engine` package).
+Source releases and installable package publication are
separate milestones. The package is not published on the npm registry.
## Unreleased
-Changes since the 0.10.0 tagged package release. The package version stays 0.10.0
-until the next package release; source/main and website deployment are separate
+Changes since the 0.10.0 tagged package release. The checkout uses the unpublished
+`1.0.0-rc.1` release candidate. Source/main and website deployment are separate
from publishing a new installable package.
+- **Breaking:** the npm identity is now `@instruktlabs/kiln`, with compiled ESM and
+ TypeScript declarations for its public subpaths. The root is a library entrypoint;
+ use the `kiln` executable for the CLI. `kiln-mcp` starts the stdio MCP server.
+- Consumer archives contain the maintained installation/API/workflow documentation;
+ historical plans, reviews and model traces remain in the repository. Current
+ repository links and package publisher metadata point to Instrukt Labs.
+- Installed isolated evaluation resolves compiled workers and readiness probes
+ without a TypeScript loader. Host isolation still requires its own readiness proof.
+- The stdio executable cancels pending engine warmup when its client disconnects;
+ a tool-list-only session no longer starts unused engine work after closing stdin.
+- Isolated evaluation explicitly requires a user namespace before disabling nested
+ namespaces, satisfying Bubblewrap's launch precondition. Unsupported hosts still
+ fail closed before source execution.
+- Windows asset saves retry transient directory-rename denials within a bounded
+ delay, preserving atomic publication and existing immutable revisions.
+- Source restoration, MCP source resources, reviewed saves and CLI rebuild
+ observations preserve an authored UTF-8 BOM instead of silently changing the
+ source and its program reference. Invalid source UTF-8 is rejected on those reads.
+- Custom asset-library hosts can reuse the canonical saved-material resolver
+ through `@instruktlabs/kiln/assets/node`.
+- The `kiln-engine` local plugin uses the Instrukt Labs marketplace and installs a
+ pinned engine outside its disposable cache. It registers setup only; managed
+ workspaces own the authoring skills and one MCP server. Upgrades preserve stores
+ and refuse conflicts. The npm archive includes the small bundle and both catalogs.
+ Replacing an older `kiln@kiln` installation requires the explicit plugin migration;
+ public directory submission and hosted access remain separate release work.
+
- Blind-run receipts recognize OpenCode's recorded code-mode MCP calls and AGY's
generic MCP dispatcher without inferring execution from source or output text.
Setup and authoring guidance now covers waiting for independent authors, checking
@@ -16,7 +44,7 @@ from publishing a new installable package.
before exporting. The eight-asset campaign records its incomplete handoffs and
visual defects separately from valid exports.
-- **Breaking (planned 0.11):** `optimize: 'full'` replaces flatten/join with rigid-group
+- **Breaking (v1 candidate):** `optimize: 'full'` replaces flatten/join with rigid-group
merging. Its rigid-merge pass preserves node names, hierarchy and transforms, including animated targets,
named joint pivots, semantic nodes, composition placements and LOD levels. Ordinary
named mesh nodes can become empty or hold merged geometry. When geometry must remain
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c6512cad..0005ec3d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -14,6 +14,7 @@ Read [AGENTS.md](AGENTS.md) and the [README](README.md). Contributor checks use
bun install --frozen-lockfile
bun run check:toolchain
bun run check:skills
+bun run build:sdk
bun run typecheck
bun run lint
bun run test
@@ -57,6 +58,9 @@ count read off the output is a floor.
### Version
+Maintainers should follow the [v1 release runbook](https://github.com/instruktlabs/kiln/blob/main/docs/releasing.md) for exact
+archive qualification, npm staging and owner promotion.
+
`version` in `package.json` identifies the installable release. Changes on `main`
ahead of that release go in the changelog's `Unreleased` section and can retain the
released version until the next release is prepared. A new release must bump the
diff --git a/README.md b/README.md
index 49f5299b..952b1fd0 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,16 @@
# Kiln
-[![CI](https://github.com/matthew-kissinger/kiln/actions/workflows/ci.yml/badge.svg)](https://github.com/matthew-kissinger/kiln/actions/workflows/ci.yml)
+[![CI](https://github.com/instruktlabs/kiln/actions/workflows/ci.yml/badge.svg)](https://github.com/instruktlabs/kiln/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
**Build and revise 3D assets with your coding agent.**
+**The v1 package is a release candidate.** This checkout prepares `@instruktlabs/[email protected]`,
+which is not published to npm yet. npm 1.0 publication and the
+hosted service remain separate, uncompleted release steps. The [SDK guide](docs/sdk.md)
+describes the compiled ESM library; use the [local package build](docs/install.md#install-a-local-package)
+to test this checkout. The 0.10.0 release described below remains a historical release.
+
The agent writes JavaScript using Kiln's geometry and material helpers. Kiln runs the
program and returns rendered views and structural checks so the agent can review its
work. Export the asset as a GLB and keep the source for later changes.
@@ -70,9 +76,9 @@ each breaking one marked, and the [migration notes](docs/migration.md#changes-in
list what an existing author will notice.
**0.10.0 is the source and site release for dogfooding.** Its package tarball is attached
-to the [v0.10.0 release](https://github.com/matthew-kissinger/kiln/releases/tag/v0.10.0)
+to the [v0.10.0 release](https://github.com/instruktlabs/kiln/releases/tag/v0.10.0)
with `SHA256SUMS.txt` and the installed-package receipts, as later releases' tarballs are
-on the [releases page](https://github.com/matthew-kissinger/kiln/releases); registry
+on the [releases page](https://github.com/instruktlabs/kiln/releases); registry
publication is deferred to v1.0 after feedback, and the site deployment publishes no
package.
@@ -89,7 +95,7 @@ model API key are not required to install the tarball:
mkdir kiln-install
cd kiln-install
npm init -y
-npm install /absolute/path/to/kiln-engine-VERSION.tgz --omit=dev --include=optional
+npm install /absolute/path/to/PACKAGE.tgz --omit=dev --include=optional
npm exec --offline -- kiln-init ../my-assets --harness opencode # or claude, codex, hermes, agy, copilot, cursor-agent
cd ../my-assets
# Follow START.md for your harness
@@ -107,7 +113,7 @@ compatibility accommodates existing distribution-managed installations.
For engine development, install [Bun](https://bun.sh) 1.4.2, then:
```sh
-git clone --filter=blob:none https://github.com/matthew-kissinger/kiln
+git clone --filter=blob:none https://github.com/instruktlabs/kiln
cd kiln
bun install --frozen-lockfile
bun run kiln render examples/crate.kiln.js --out crate.glb --views sheet.png
@@ -387,7 +393,7 @@ review; unresolved obligations prevent activation. See [migration](docs/migratio
The
[generated tool reference](docs/tools.md) covers source editing, validation,
rendering, part inspection, animation and interior views. The shared factory is
-`createKilnProgramToolRegistry` in `@kiln/engine/tools`.
+`createKilnProgramToolRegistry` in `@instruktlabs/kiln/tools`.
## Uses and limitations
diff --git a/ROADMAP.md b/ROADMAP.md
index 699fb815..51850528 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,6 +1,7 @@
# Kiln roadmap
-Updated 5 October 2026, against main `7ed880f` and the published website.
+Updated 6 October 2026 for the active 1.0 publication cycle. Delivered website
+evidence below remains the 5 October checkpoint; it does not attest to a new release.
[CHANGELOG.md](CHANGELOG.md) defines engine release behavior.
The [backlog](docs/backlog.md) separates completed work, known limits and future decisions.
Dated plans and reviews retain their original candidate scopes.
@@ -10,7 +11,8 @@ Dated plans and reviews retain their original candidate scopes.
Kiln 0.10.0 remains the current engine tag. Standalone authoring, optional projects,
materials, Live Review, calibrated review lighting, bounded tool results and the
current CLI/MCP contracts are implemented. Subsequent core fixes and compatible
-dependency upgrades are on main; the planned 0.11 package release is separate.
+dependency upgrades are on main. The owner selected 1.0 as the next publication
+target, incorporating the previously planned 0.11 changes.
The completed scene optimization pass landed in #131, ORM UV/transform fixes in
#132 and the core/stabilization/site follow-ups in #133. Their bounded qualification
@@ -42,14 +44,20 @@ this dated list is not a substitute for inspecting them.
## Next engine and product milestones
-1. Release the main-only breaking optimizer changes as the planned 0.11 package,
- with explicit saved-source replay/migration guidance and installed-package gates.
- Website deployment did not publish a new engine tag or npm package.
+1. Publish `@instruktlabs/[email protected]` with the compiled SDK, CLI, local MCP and skills,
+ including the main-only optimizer changes and explicit saved-source migration.
+ Qualify the RC, upgrades, platform gates and exact registry artifact. Follow the
+ [publication plan](docs/plans/2026-10-05-v1-publication-plan.md) and
+ [execution record](docs/reviews/2026-10-06-v1-execution.md). A source candidate or
+ website deployment does not establish npm publication.
2. Qualify broader destination/importer support when adopted, especially LOD,
visibility and optional compressed runtime derivatives. Current scene delivery
does not imply universal Meshopt, Draco or KTX2 loader support.
-3. Develop further packs and the public v1 package as separate milestones.
- Ten-pack production is not unfinished work in the current Troy release.
+3. Qualify and deploy the authenticated Cloudflare service, distribute the Claude
+ Code/Codex plugins and submit applicable vendor directory candidates. Hosted
+ access stays free within quotas, with optional sponsorship and no user billing.
+ Track npm publication, hosting, plugin distribution and vendor review separately.
+ Further packs and community contribution triage stay outside this release cycle.
The full optimizer now preserves semantic nodes, hierarchy, placements, animated
targets and LOD relationships; ordinary named meshes can become empty semantic
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 8705754e..cdbd80dd 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -37,7 +37,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## Candidate native/WASM dependency inventory
-Inspected September 23, 2026. Runtime bundles keep npm dependencies external;
+Inspected October 6, 2026. Runtime bundles keep npm dependencies external;
installation retains their own package files and notices. This table identifies
the native/WASM packages used by this candidate, not a replacement license for
their transitive components. Optional Strands/provider dependencies are separate
@@ -45,11 +45,11 @@ and are not required for CLI/MCP authoring.
| Package inspected | Package license metadata | Distributed notice / provenance |
| --- | --- | --- |
-| `[email protected]` | MIT metadata; distributed Dawn/Tint notice is BSD-3-Clause | `webgpu/LICENSE.md`, reproduced above; native Dawn/Tint supplied by the package |
-| `@napi-rs/[email protected]` | MIT | `@napi-rs/canvas/LICENSE`; platform package contains the Skia-based native binding |
-| `[email protected]` | Apache-2.0 | `sharp/LICENSE` |
-| `@img/[email protected]` | Apache-2.0 AND LGPL-3.0-or-later | package `LICENSE` and `versions.json`; the inspected binary includes libvips 8.18.6 and additional native libraries |
-| `[email protected]` | Apache-2.0 | `manifold-3d/LICENSE`, JavaScript and WASM distribution |
+| `[email protected]` | MIT metadata; distributed Dawn/Tint notice is BSD-3-Clause | `webgpu/LICENSE.md`, reproduced above; native Dawn/Tint supplied by the package |
+| `@napi-rs/[email protected]` | MIT | `@napi-rs/canvas/LICENSE`; platform package contains the Skia-based native binding |
+| `[email protected]` | Apache-2.0 | `sharp/LICENSE` |
+| `@img/[email protected]` | Apache-2.0 AND LGPL-3.0-or-later | package `LICENSE` and `versions.json`; the inspected binary includes libvips 8.18.7 and additional native libraries |
+| `[email protected]` | Apache-2.0 | `manifold-3d/LICENSE`, JavaScript and WASM distribution |
| `[email protected]` | MIT | `xatlasjs/LICENSE`, copyright Jonathan Young; JavaScript and WASM distribution |
Sharp selects platform-specific binaries during installation; consult the
diff --git a/biome.json b/biome.json
index 58d4ff51..86158620 100644
--- a/biome.json
+++ b/biome.json
@@ -8,6 +8,9 @@
"site/*.ts",
"scripts/**/*.mjs",
"scripts/**/*.ts",
+ "hosting/src/**/*.ts",
+ "hosting/test/**/*.{ts,mjs}",
+ "hosting/scripts/**/*.mjs",
"render-service/src/**/*.mjs",
"render-service/test/**/*.mjs"
],
diff --git a/bun.lock b/bun.lock
index 0e3ad2fb..5f848c95 100644
--- a/bun.lock
+++ b/bun.lock
@@ -3,7 +3,7 @@
"configVersion": 1,
"workspaces": {
"": {
- "name": "@kiln/engine",
+ "name": "@instruktlabs/kiln",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
diff --git a/bunfig.toml b/bunfig.toml
index 5658eb27..aabb839f 100644
--- a/bunfig.toml
+++ b/bunfig.toml
@@ -22,6 +22,8 @@ coveragePathIgnorePatterns = [
"**/generated/**",
"**/*.generated.ts",
"dist/**",
+ # Compiled SDK mirrors src/; installed-import tests must not count it twice.
+ "lib/**",
"coverage/**",
"vendor/**",
]
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index ae8dfa88..0435548d 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -28467,7 +28467,6 @@ var init_subprocess = __esm(() => {
DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
MAX_STDERR_BYTES = 16 * 1024;
});
-
// src/evaluator/isolation.ts
var MAX_READINESS_PROTOCOL_BYTES;
var init_isolation = __esm(() => {
@@ -28490,7 +28489,7 @@ function engineVersion() {
try {
const raw = readFileSync(new URL(path, import.meta.url), "utf8");
const pkg = JSON.parse(raw);
- if (pkg.name === "@kiln/engine" && typeof pkg.version === "string" && pkg.version) {
+ if (pkg.name === "@instruktlabs/kiln" && typeof pkg.version === "string" && pkg.version) {
return pkg.version;
}
} catch {}
@@ -32089,7 +32088,7 @@ async function programReference(code) {
const bytes = new TextEncoder().encode(code);
if (bytes.length > MAX_PROGRAM_BYTES)
throw new Error("Program exceeds the 1 MiB source limit.");
- if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== code)
+ if (new TextDecoder("utf-8", { fatal: false, ignoreBOM: true }).decode(bytes) !== code)
throw new Error("Program must be valid Unicode.");
const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
return `sha256:${Array.from(hash, (b) => b.toString(16).padStart(2, "0")).join("")}`;
@@ -32940,7 +32939,7 @@ function createKilnSourceDef(store) {
}
// src/engine-identity.ts
-var ENGINE_VERSION = "0.10.0";
+var ENGINE_VERSION = "1.0.0-rc.1";
var ENGINE_INSTALL_URL = new URL("../", import.meta.url).href;
function engineIdentity() {
return { version: ENGINE_VERSION, installUrl: ENGINE_INSTALL_URL };
@@ -36572,7 +36571,7 @@ Not returned, over the result size: ${omitted.join(", ")}. Fetch them with anoth
...guidance,
`Families: ${orientation.families.join(", ")}. Tags: ${orientation.tags.join(", ")}.`
] : [],
- ...page.map((entry) => `${entry.id}${entry.execution ? ` (${entry.execution === "async" ? "async; await the result" : "sync"})` : ""}: ${entry.summary}${entry.limitations.length ? ` Limits: ${entry.limitations.join(" ")}` : ""}${formatMatch(entry.match)}`),
+ ...page.map((entry) => `${entry.id} [${entry.stability}]${entry.execution ? ` (${entry.execution === "async" ? "async; await the result" : "sync"})` : ""}: ${entry.summary}${entry.limitations.length ? ` Limits: ${entry.limitations.join(" ")}` : ""}${formatMatch(entry.match)}`),
...input.query && !page.length ? [
"No lexical matches on this page. Try a narrower modeling operation, browse the overview for families/tags, or use custom geometry. This is not proof that the asset is impossible."
] : [],
@@ -37368,7 +37367,7 @@ function createKilnReviewDef(context) {
throw new Error("Reviewed requirements do not match the current trusted host binding");
if (input.assetId && input.parentRevision)
assertSavedRequirementsAuthorized((await context.assetLibrary.read(collection, input.assetId, input.parentRevision)).manifest, active);
- const code = new TextDecoder().decode(source);
+ const code = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(source);
const checkpoint = evaluation.requirements.binding ? createRequirementsCheckpoint(await programReference(code), evaluation.requirements.binding) : undefined;
const dependencies = [
...evaluation.materialResourceProvenance ?? [],
@@ -39497,7 +39496,7 @@ function createKilnAssetDefs(context) {
throw new Error("Source unavailable: this asset contains only a GLB");
return {
...await links(input.collection, record.manifest),
- programRef: await retainProgram(context.programStore, new TextDecoder().decode(code)),
+ programRef: await retainProgram(context.programStore, new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(code)),
requirements: activeRequirements,
savedRequirements: saved,
acceptance: "reevaluation-required"
diff --git a/dist/build.json b/dist/build.json
index 6d97166a..b1157c30 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,12 +2,12 @@
"schemaVersion": 1,
"entries": {
"worker": {
- "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
- "engineVersion": "0.10.0",
+ "identity": "sha256:a0456b139322272b252798a0b71ab5f82d864af7bd7635c4664098169ae5917b",
+ "engineVersion": "1.0.0-rc.1",
"toolchain": "[email protected]",
- "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "sourceHash": "c53eb2a566184d53c3d28b3c5b940b8dc7e68a6ec2add972f50140736658b30e",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
+ "dependencyHash": "66fa080538b44a4cc1b0655bb23c097cda70041d879e085f2dec0aadccb8abed",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -34,15 +34,15 @@
},
"target": "node",
"file": "evaluator-worker.mjs",
- "bundleHash": "sha256:efb67be70d07325ecd824a451e2852ed50b50f2a8c1516b529ea66d5074577ab"
+ "bundleHash": "sha256:37098a17b5304a5f5746131c9652498d937a5181c0fb0975861dec999721d5be"
},
"agent-run": {
- "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
- "engineVersion": "0.10.0",
+ "identity": "sha256:a0456b139322272b252798a0b71ab5f82d864af7bd7635c4664098169ae5917b",
+ "engineVersion": "1.0.0-rc.1",
"toolchain": "[email protected]",
- "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "sourceHash": "c53eb2a566184d53c3d28b3c5b940b8dc7e68a6ec2add972f50140736658b30e",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
+ "dependencyHash": "66fa080538b44a4cc1b0655bb23c097cda70041d879e085f2dec0aadccb8abed",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -69,15 +69,15 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:a9228e007de71e69dc8cff8ccc38d244631d49854745acc667a4a5bcfea7a035"
+ "bundleHash": "sha256:68aa4031b98e722ac9d4191b6bc5611452b816cac474bd1c678af5c2c371c9ac"
},
"agent-providers": {
- "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
- "engineVersion": "0.10.0",
+ "identity": "sha256:a0456b139322272b252798a0b71ab5f82d864af7bd7635c4664098169ae5917b",
+ "engineVersion": "1.0.0-rc.1",
"toolchain": "[email protected]",
- "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "sourceHash": "c53eb2a566184d53c3d28b3c5b940b8dc7e68a6ec2add972f50140736658b30e",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
+ "dependencyHash": "66fa080538b44a4cc1b0655bb23c097cda70041d879e085f2dec0aadccb8abed",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -107,12 +107,12 @@
"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"
},
"mcp": {
- "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
- "engineVersion": "0.10.0",
+ "identity": "sha256:a0456b139322272b252798a0b71ab5f82d864af7bd7635c4664098169ae5917b",
+ "engineVersion": "1.0.0-rc.1",
"toolchain": "[email protected]",
- "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "sourceHash": "c53eb2a566184d53c3d28b3c5b940b8dc7e68a6ec2add972f50140736658b30e",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
+ "dependencyHash": "66fa080538b44a4cc1b0655bb23c097cda70041d879e085f2dec0aadccb8abed",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -139,15 +139,15 @@
},
"target": "node",
"file": "mcp-server.mjs",
- "bundleHash": "sha256:aff8b03e5146a9e7bc32f0fcb7dea5e46d1e47634046b1df09b86f4cdc73b772"
+ "bundleHash": "sha256:58f697718e4e609439c6d22378d6b9bcb698f6675f87d76ac317fcaa2e44e14b"
},
"cli": {
- "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
- "engineVersion": "0.10.0",
+ "identity": "sha256:a0456b139322272b252798a0b71ab5f82d864af7bd7635c4664098169ae5917b",
+ "engineVersion": "1.0.0-rc.1",
"toolchain": "[email protected]",
- "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "sourceHash": "c53eb2a566184d53c3d28b3c5b940b8dc7e68a6ec2add972f50140736658b30e",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
+ "dependencyHash": "66fa080538b44a4cc1b0655bb23c097cda70041d879e085f2dec0aadccb8abed",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -174,15 +174,15 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:e09ee8f1d6808c29903f3da884062955742b0a6fb3a0e8da4ddcef4eb8278a06"
+ "bundleHash": "sha256:7ddfaf5c0d412b35e44a99c5183eef389209baac4fbe9f690cbe53e51ec1dad6"
},
"engine": {
- "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
- "engineVersion": "0.10.0",
+ "identity": "sha256:a0456b139322272b252798a0b71ab5f82d864af7bd7635c4664098169ae5917b",
+ "engineVersion": "1.0.0-rc.1",
"toolchain": "[email protected]",
- "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "sourceHash": "c53eb2a566184d53c3d28b3c5b940b8dc7e68a6ec2add972f50140736658b30e",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
- "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
+ "dependencyHash": "66fa080538b44a4cc1b0655bb23c097cda70041d879e085f2dec0aadccb8abed",
"dependencies": {
"@gltf-transform/core": "4.5.1",
"@gltf-transform/extensions": "4.5.1",
@@ -209,7 +209,7 @@
},
"target": "node",
"file": "mcp-engine.mjs",
- "bundleHash": "sha256:8dd44a83867607428b548fe2deb78208dde50e70dfe83092fd97ce4cad0fcfc7"
+ "bundleHash": "sha256:e426a9ef1f39ded71849c7c5575e8036e9fb6bb2eb36d5bdf9080a8933d2cf1b"
}
}
}
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 422138d3..1c7f2571 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -29328,6 +29328,19 @@ var init_handler = __esm(() => {
init_protocol();
});
+// src/evaluator/worker-urls.ts
+function isolatedWorkerUrls(moduleUrl) {
+ const source = new URL(moduleUrl).pathname.endsWith(".ts");
+ const sdk = new URL(moduleUrl).pathname.endsWith("/isolation.js");
+ const base = new URL(source || sdk ? "./" : "../lib/evaluator/", moduleUrl);
+ const extension = source ? "ts" : "js";
+ return {
+ worker: new URL(`worker.${extension}`, base),
+ probe: new URL(`probe-worker.${extension}`, base),
+ transport: new URL("transport-worker.mjs", base)
+ };
+}
+
// src/evaluator/isolation.ts
import { existsSync } from "node:fs";
import { posix } from "node:path";
@@ -29380,6 +29393,7 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"
isolationUnavailable();
const bwrapArgs = [
"--unshare-all",
+ "--unshare-user",
"--die-with-parent",
"--new-session",
"--disable-userns",
@@ -29426,10 +29440,10 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"
};
}
function isolatedEvaluatorLaunch(workerPath, host = {}) {
- return isolatedEvaluatorLaunchWithLoader(workerPath, host, "tsx");
+ return isolatedEvaluatorLaunchWithLoader(workerPath, host, /\.tsx?$/.test(workerPath) ? "tsx" : "module");
}
async function renderGLBViaIsolatedEvaluator(code, options = {}, controls = {}) {
- const workerPath = fileURLToPath2(new URL("./worker.ts", import.meta.url));
+ const workerPath = fileURLToPath2(isolatedWorkerUrls(import.meta.url).worker);
const launch = isolatedEvaluatorLaunch(workerPath, controls.host);
const { host: _, ...processControls } = controls;
return renderGLBViaProcessLaunch(code, options, processControls, launch);
@@ -29573,7 +29587,7 @@ function engineVersion() {
try {
const raw = readFileSync(new URL(path, import.meta.url), "utf8");
const pkg = JSON.parse(raw);
- if (pkg.name === "@kiln/engine" && typeof pkg.version === "string" && pkg.version) {
+ if (pkg.name === "@instruktlabs/kiln" && typeof pkg.version === "string" && pkg.version) {
return pkg.version;
}
} catch {}
@@ -31903,7 +31917,8 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, laun
throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator request exceeds its size limit.");
}
const sourceModule = import.meta.url.endsWith(".ts");
- const workerPath = fileURLToPath3(new URL(process.versions.bun && sourceModule ? "./worker.ts" : sourceModule ? "../../dist/evaluator-worker.mjs" : "./evaluator-worker.mjs", import.meta.url));
+ const sdkModule = import.meta.url.endsWith("/subprocess.js");
+ const workerPath = fileURLToPath3(new URL(process.versions.bun && sourceModule ? "./worker.ts" : sourceModule || sdkModule ? "../../dist/evaluator-worker.mjs" : "./evaluator-worker.mjs", import.meta.url));
const maxHeapMb = boundedInteger(controls.maxHeapMb, 512, 4096);
if (maxHeapMb < 64 || process.versions.bun && controls.maxHeapMb !== undefined) {
throw new EvaluatorSubprocessError("INPUT_INVALID", "Heap limits require a Node worker and 64–4096 MiB.");
@@ -32070,7 +32085,7 @@ async function programReference(code) {
const bytes = new TextEncoder().encode(code);
if (bytes.length > MAX_PROGRAM_BYTES)
throw new Error("Program exceeds the 1 MiB source limit.");
- if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== code)
+ if (new TextDecoder("utf-8", { fatal: false, ignoreBOM: true }).decode(bytes) !== code)
throw new Error("Program must be valid Unicode.");
const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
return `sha256:${Array.from(hash, (b) => b.toString(16).padStart(2, "0")).join("")}`;
@@ -32593,7 +32608,7 @@ async function installedRuntimeIdentity(root, limits = {}) {
};
try {
const pkg = await manifest(root);
- if (pkg.name !== "@kiln/engine")
+ if (pkg.name !== "@instruktlabs/kiln")
throw new Error("Not a Kiln installation.");
const build = JSON.parse(await readFile4(join6(root, "dist", "build.json"), "utf8"));
const worker = build.entries?.worker;
@@ -34273,6 +34288,32 @@ var init_asset_materials_node = __esm(() => {
init_material_library_node();
});
+// src/atomic-directory.ts
+import { lstat as lstat7, rename as rename5 } from "node:fs/promises";
+import { setTimeout as pause } from "node:timers/promises";
+async function renameDirectoryAtomically(source, destination, controls = {}) {
+ const renameOperation = controls.renameOperation ?? rename5;
+ const platform = controls.platform ?? process.platform;
+ const wait = controls.pause ?? pause;
+ const delays = [20, 50, 100, 200, 400];
+ for (let attempt = 0;; attempt++) {
+ try {
+ await renameOperation(source, destination);
+ return;
+ } catch (error) {
+ const delay = delays[attempt];
+ const code = error?.code;
+ if (platform !== "win32" || delay === undefined || !["EPERM", "EACCES", "EBUSY"].includes(code ?? ""))
+ throw error;
+ const absent = await lstat7(destination).then(() => false, (statError) => statError.code === "ENOENT");
+ if (!absent)
+ throw error;
+ await wait(delay);
+ }
+ }
+}
+var init_atomic_directory = () => {};
+
// src/assets-node.ts
var exports_assets_node = {};
__export(exports_assets_node, {
@@ -34284,17 +34325,7 @@ __export(exports_assets_node, {
});
import { createHash as createHash14, randomUUID as randomUUID7 } from "node:crypto";
import { readFileSync as readFileSync2 } from "node:fs";
-import {
- link as link5,
- lstat as lstat7,
- mkdir as mkdir7,
- readFile as readFile6,
- readdir as readdir7,
- realpath as realpath6,
- rename as rename5,
- rm as rm3,
- writeFile as writeFile6
-} from "node:fs/promises";
+import { link as link5, lstat as lstat8, mkdir as mkdir7, readFile as readFile6, readdir as readdir7, realpath as realpath6, rm as rm3, writeFile as writeFile6 } from "node:fs/promises";
import { homedir, platform } from "node:os";
import { dirname as dirname5, join as join10, relative as relative5, resolve as resolve9, sep as sep4, win32 } from "node:path";
function assertMaterialAllocation(records) {
@@ -34351,7 +34382,7 @@ class FileAssetLibrary {
assetIdSchema.parse(part);
path = join10(path, part);
try {
- const entry = await lstat7(path);
+ const entry = await lstat8(path);
if (entry.isSymbolicLink())
throw new Error("Collection symlinks are not supported");
const rel = relative5(canonical, await realpath6(path));
@@ -34393,7 +34424,7 @@ class FileAssetLibrary {
}
async file(dir, name, limit = ASSET_LIMIT) {
const path = join10(dir, name);
- const info = await lstat7(path);
+ const info = await lstat8(path);
if (!info.isFile() || info.isSymbolicLink() || info.size > limit)
throw new Error("Invalid collection file");
return new Uint8Array(await readFile6(path));
@@ -34520,7 +34551,7 @@ class FileAssetLibrary {
flag: "wx"
});
try {
- await rename5(stage, dest);
+ await renameDirectoryAtomically(stage, dest);
} catch (error) {
const existing = await this.read(collection, manifest.assetId, manifest.revisionId).catch(() => {
return;
@@ -34603,6 +34634,8 @@ var init_assets_node = __esm(() => {
init_assets();
init_material_library_node();
init_asset_materials_node();
+ init_atomic_directory();
+ init_asset_materials_node();
windowsDrivePath = /^[A-Za-z]:[\\/]/;
windowsSharePath = /^[\\/]{2}[^\\/]+[\\/][^\\/]+/;
});
@@ -34990,7 +35023,7 @@ var init_project_bundle = __esm(() => {
// src/project-bundle-node.ts
import { randomUUID as randomUUID8 } from "node:crypto";
-import { link as link6, lstat as lstat8, mkdir as mkdir8, readFile as readFile7, realpath as realpath7, unlink as unlink6, writeFile as writeFile7 } from "node:fs/promises";
+import { link as link6, lstat as lstat9, mkdir as mkdir8, readFile as readFile7, realpath as realpath7, unlink as unlink6, writeFile as writeFile7 } from "node:fs/promises";
import { join as join11, relative as relative6, resolve as resolve10, sep as sep5 } from "node:path";
async function assetMaterials(workspace, asset) {
return resolveSavedAssetMaterials(asset, workspace.materials);
@@ -35046,7 +35079,7 @@ async function retainArchive(workspace, bytes, digest) {
if (error.code !== "EEXIST")
throw error;
});
- const info = await lstat8(directory);
+ const info = await lstat9(directory);
const rel = relative6(canonical, await realpath7(directory));
if (!info.isDirectory() || info.isSymbolicLink() || rel === ".." || rel.startsWith(`..${sep5}`))
throw new Error("Unsafe project import directory");
@@ -35060,7 +35093,7 @@ async function retainArchive(workspace, bytes, digest) {
} catch (error) {
if (error.code !== "EEXIST")
throw error;
- const info = await lstat8(file);
+ const info = await lstat9(file);
if (!info.isFile() || info.isSymbolicLink() || info.size !== bytes.length || await projectBundleHash(new Uint8Array(await readFile7(file))) !== digest)
throw new Error("Imported archive integrity mismatch");
}
@@ -36138,7 +36171,7 @@ var init_program_artifacts = __esm(() => {
function engineIdentity() {
return { version: ENGINE_VERSION, installUrl: ENGINE_INSTALL_URL };
}
-var ENGINE_VERSION = "0.10.0", ENGINE_INSTALL_URL;
+var ENGINE_VERSION = "1.0.0-rc.1", ENGINE_INSTALL_URL;
var init_engine_identity = __esm(() => {
ENGINE_INSTALL_URL = new URL("../", import.meta.url).href;
});
@@ -39795,7 +39828,7 @@ Not returned, over the result size: ${omitted.join(", ")}. Fetch them with anoth
...guidance,
`Families: ${orientation.families.join(", ")}. Tags: ${orientation.tags.join(", ")}.`
] : [],
- ...page.map((entry) => `${entry.id}${entry.execution ? ` (${entry.execution === "async" ? "async; await the result" : "sync"})` : ""}: ${entry.summary}${entry.limitations.length ? ` Limits: ${entry.limitations.join(" ")}` : ""}${formatMatch(entry.match)}`),
+ ...page.map((entry) => `${entry.id} [${entry.stability}]${entry.execution ? ` (${entry.execution === "async" ? "async; await the result" : "sync"})` : ""}: ${entry.summary}${entry.limitations.length ? ` Limits: ${entry.limitations.join(" ")}` : ""}${formatMatch(entry.match)}`),
...input.query && !page.length ? [
"No lexical matches on this page. Try a narrower modeling operation, browse the overview for families/tags, or use custom geometry. This is not proof that the asset is impossible."
] : [],
@@ -40584,7 +40617,7 @@ function createKilnReviewDef(context) {
throw new Error("Reviewed requirements do not match the current trusted host binding");
if (input.assetId && input.parentRevision)
assertSavedRequirementsAuthorized((await context.assetLibrary.read(collection, input.assetId, input.parentRevision)).manifest, active);
- const code = new TextDecoder().decode(source);
+ const code = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(source);
const checkpoint = evaluation.requirements.binding ? createRequirementsCheckpoint(await programReference(code), evaluation.requirements.binding) : undefined;
const dependencies = [
...evaluation.materialResourceProvenance ?? [],
@@ -43682,7 +43715,7 @@ function createKilnAssetDefs(context) {
throw new Error("Source unavailable: this asset contains only a GLB");
return {
...await links(input.collection, record.manifest),
- programRef: await retainProgram(context.programStore, new TextDecoder().decode(code)),
+ programRef: await retainProgram(context.programStore, new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(code)),
requirements: activeRequirements,
savedRequirements: saved,
acceptance: "reevaluation-required"
@@ -44906,7 +44939,7 @@ function refuse(res, message) {
`);
}
async function startAssetViewer(library, options = {}) {
- const staticDirectory = options.staticDirectory ?? (import.meta.url.endsWith(".ts") ? join17(dirname8(fileURLToPath7(import.meta.url)), "..", "dist", "viewer") : join17(dirname8(fileURLToPath7(import.meta.url)), "viewer"));
+ const staticDirectory = options.staticDirectory ?? (!import.meta.url.endsWith(".mjs") ? join17(dirname8(fileURLToPath7(import.meta.url)), "..", "dist", "viewer") : join17(dirname8(fileURLToPath7(import.meta.url)), "viewer"));
const server = createServer(async (req, res) => {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "no-referrer");
@@ -45218,7 +45251,7 @@ async function assetMain(argv) {
throw new Error("Saved revision uses an unversioned full optimization pipeline; rebuild with its original pinned engine, or explicitly author and save a new child revision to migrate.");
const { optimizationPipeline: _pipeline, ...renderOptions } = parsed.data;
const materialResources = await resolveAssetMaterialPayload(new FileWorkspace(localWorkspaceRoot()), record);
- const code = new TextDecoder().decode(source);
+ const code = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(source);
const rendered = await context.evaluatorPort.render(code, {
...renderOptions,
materialResources,
diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjs
index 7d7674a3..eacfb599 100644
--- a/dist/evaluator-worker.mjs
+++ b/dist/evaluator-worker.mjs
@@ -25694,7 +25694,6 @@ var init_subprocess = __esm(() => {
DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
MAX_STDERR_BYTES = 16 * 1024;
});
-
// src/evaluator/isolation.ts
var MAX_READINESS_PROTOCOL_BYTES;
var init_isolation = __esm(() => {
@@ -25720,7 +25719,7 @@ function engineVersion() {
try {
const raw = readFileSync(new URL(path, import.meta.url), "utf8");
const pkg = JSON.parse(raw);
- if (pkg.name === "@kiln/engine" && typeof pkg.version === "string" && pkg.version) {
+ if (pkg.name === "@instruktlabs/kiln" && typeof pkg.version === "string" && pkg.version) {
return pkg.version;
}
} catch {}
diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjs
index 3ee07988..113a1d50 100644
--- a/dist/mcp-engine.mjs
+++ b/dist/mcp-engine.mjs
@@ -28511,6 +28511,19 @@ var init_handler = __esm(() => {
init_protocol();
});
+// src/evaluator/worker-urls.ts
+function isolatedWorkerUrls(moduleUrl) {
+ const source = new URL(moduleUrl).pathname.endsWith(".ts");
+ const sdk = new URL(moduleUrl).pathname.endsWith("/isolation.js");
+ const base = new URL(source || sdk ? "./" : "../lib/evaluator/", moduleUrl);
+ const extension = source ? "ts" : "js";
+ return {
+ worker: new URL(`worker.${extension}`, base),
+ probe: new URL(`probe-worker.${extension}`, base),
+ transport: new URL("transport-worker.mjs", base)
+ };
+}
+
// src/evaluator/isolation.ts
import { existsSync as existsSync3 } from "node:fs";
import { posix } from "node:path";
@@ -28563,6 +28576,7 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"
isolationUnavailable();
const bwrapArgs = [
"--unshare-all",
+ "--unshare-user",
"--die-with-parent",
"--new-session",
"--disable-userns",
@@ -28609,10 +28623,10 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"
};
}
function isolatedEvaluatorLaunch(workerPath, host = {}) {
- return isolatedEvaluatorLaunchWithLoader(workerPath, host, "tsx");
+ return isolatedEvaluatorLaunchWithLoader(workerPath, host, /\.tsx?$/.test(workerPath) ? "tsx" : "module");
}
async function renderGLBViaIsolatedEvaluator(code, options = {}, controls = {}) {
- const workerPath = fileURLToPath3(new URL("./worker.ts", import.meta.url));
+ const workerPath = fileURLToPath3(isolatedWorkerUrls(import.meta.url).worker);
const launch = isolatedEvaluatorLaunch(workerPath, controls.host);
const { host: _, ...processControls } = controls;
return renderGLBViaProcessLaunch(code, options, processControls, launch);
@@ -28756,7 +28770,7 @@ function engineVersion() {
try {
const raw = readFileSync4(new URL(path, import.meta.url), "utf8");
const pkg = JSON.parse(raw);
- if (pkg.name === "@kiln/engine" && typeof pkg.version === "string" && pkg.version) {
+ if (pkg.name === "@instruktlabs/kiln" && typeof pkg.version === "string" && pkg.version) {
return pkg.version;
}
} catch {}
@@ -31086,7 +31100,8 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, laun
throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator request exceeds its size limit.");
}
const sourceModule = import.meta.url.endsWith(".ts");
- const workerPath = fileURLToPath4(new URL(process.versions.bun && sourceModule ? "./worker.ts" : sourceModule ? "../../dist/evaluator-worker.mjs" : "./evaluator-worker.mjs", import.meta.url));
+ const sdkModule = import.meta.url.endsWith("/subprocess.js");
+ const workerPath = fileURLToPath4(new URL(process.versions.bun && sourceModule ? "./worker.ts" : sourceModule || sdkModule ? "../../dist/evaluator-worker.mjs" : "./evaluator-worker.mjs", import.meta.url));
const maxHeapMb = boundedInteger(controls.maxHeapMb, 512, 4096);
if (maxHeapMb < 64 || process.versions.bun && controls.maxHeapMb !== undefined) {
throw new EvaluatorSubprocessError("INPUT_INVALID", "Heap limits require a Node worker and 64–4096 MiB.");
@@ -32894,17 +32909,7 @@ import { fileURLToPath as fileURLToPath6 } from "node:url";
// src/assets-node.ts
import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
import { readFileSync } from "node:fs";
-import {
- link,
- lstat as lstat2,
- mkdir as mkdir2,
- readFile as readFile2,
- readdir as readdir2,
- realpath as realpath2,
- rename as rename2,
- rm as rm2,
- writeFile as writeFile2
-} from "node:fs/promises";
+import { link, lstat as lstat3, mkdir as mkdir2, readFile as readFile2, readdir as readdir2, realpath as realpath2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
import { homedir, platform } from "node:os";
import { dirname as dirname3, join as join3, relative as relative2, resolve as resolve3, sep as sep2, win32 } from "node:path";
@@ -32976,6 +32981,31 @@ async function resolveSavedAssetMaterials(asset, library) {
}));
}
+// src/atomic-directory.ts
+import { lstat as lstat2, rename as rename2 } from "node:fs/promises";
+import { setTimeout as pause } from "node:timers/promises";
+async function renameDirectoryAtomically(source, destination, controls = {}) {
+ const renameOperation = controls.renameOperation ?? rename2;
+ const platform = controls.platform ?? process.platform;
+ const wait = controls.pause ?? pause;
+ const delays = [20, 50, 100, 200, 400];
+ for (let attempt = 0;; attempt++) {
+ try {
+ await renameOperation(source, destination);
+ return;
+ } catch (error) {
+ const delay = delays[attempt];
+ const code = error?.code;
+ if (platform !== "win32" || delay === undefined || !["EPERM", "EACCES", "EBUSY"].includes(code ?? ""))
+ throw error;
+ const absent = await lstat2(destination).then(() => false, (statError) => statError.code === "ENOENT");
+ if (!absent)
+ throw error;
+ await wait(delay);
+ }
+ }
+}
+
// src/assets-node.ts
var digest2 = (bytes) => `sha256:${createHash3("sha256").update(bytes).digest("hex")}`;
function assertMaterialAllocation(records) {
@@ -33032,7 +33062,7 @@ class FileAssetLibrary {
assetIdSchema.parse(part);
path = join3(path, part);
try {
- const entry = await lstat2(path);
+ const entry = await lstat3(path);
if (entry.isSymbolicLink())
throw new Error("Collection symlinks are not supported");
const rel = relative2(canonical, await realpath2(path));
@@ -33074,7 +33104,7 @@ class FileAssetLibrary {
}
async file(dir, name, limit = ASSET_LIMIT) {
const path = join3(dir, name);
- const info = await lstat2(path);
+ const info = await lstat3(path);
if (!info.isFile() || info.isSymbolicLink() || info.size > limit)
throw new Error("Invalid collection file");
return new Uint8Array(await readFile2(path));
@@ -33201,7 +33231,7 @@ class FileAssetLibrary {
flag: "wx"
});
try {
- await rename2(stage, dest);
+ await renameDirectoryAtomically(stage, dest);
} catch (error) {
const existing = await this.read(collection, manifest.assetId, manifest.revisionId).catch(() => {
return;
@@ -33988,7 +34018,7 @@ import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypt
import {
link as link2,
mkdir as mkdir3,
- lstat as lstat3,
+ lstat as lstat4,
readdir as readdir3,
readFile as readFile3,
rename as rename3,
@@ -34253,7 +34283,7 @@ class FileLiveReview {
if (!collision(error))
throw error;
});
- const info = await lstat3(path);
+ const info = await lstat4(path);
if (!info.isDirectory() || info.isSymbolicLink())
throw new Error("Unsafe live directory");
const rel = relative4(canonical, await realpath3(path));
@@ -34262,7 +34292,7 @@ class FileLiveReview {
}
}
async boundedFile(path, limit) {
- const info = await lstat3(path);
+ const info = await lstat4(path);
if (!info.isFile() || info.isSymbolicLink() || info.size > limit)
throw new Error("Invalid live file");
const data = new Uint8Array(await readFile3(path));
@@ -34290,7 +34320,7 @@ class FileLiveReview {
if (!collision(error))
throw error;
});
- const info = await lstat3(directory);
+ const info = await lstat4(directory);
if (!info.isDirectory() || info.isSymbolicLink())
throw new Error("Unsafe live lock directory");
const candidate = join8(directory, `.candidate-${process.pid}-${token}.tmp`);
@@ -34311,7 +34341,7 @@ class FileLiveReview {
if (latest) {
try {
const prior = z3.object({ pid: z3.number().int().positive(), token: z3.string().uuid() }).strict().parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join8(directory, latest), 1024))));
- const released = await lstat3(join8(directory, `${latest}.released`)).then((entry) => {
+ const released = await lstat4(join8(directory, `${latest}.released`)).then((entry) => {
if (!entry.isFile() || entry.isSymbolicLink() || entry.size !== 0)
throw new Error("Invalid lock release");
return true;
@@ -34598,7 +34628,7 @@ class FileLiveReview {
async record(operationId) {
await this.root();
const directory = this.path(operationId);
- const info = await lstat3(directory);
+ const info = await lstat4(directory);
if (!info.isDirectory() || info.isSymbolicLink())
throw new Error("Unsafe live directory");
const raw = JSON.parse(new TextDecoder().decode(await this.boundedFile(join8(directory, "record.json"), metadataLimit)));
@@ -34620,7 +34650,7 @@ class FileLiveReview {
throw new Error("Invalid artifact descriptor");
if (state.operation.captures.some((file) => !/^capture-\d{1,2}\.png$/.test(file.name)))
throw new Error("Invalid capture descriptor");
- state.operation.pinned = await lstat3(join8(directory, "pinned")).then((s) => {
+ state.operation.pinned = await lstat4(join8(directory, "pinned")).then((s) => {
if (!s.isFile() || s.isSymbolicLink())
throw new Error("Invalid live pin");
return true;
@@ -34642,7 +34672,7 @@ class FileLiveReview {
for (const entry of await readdir3(directory, { withFileTypes: true })) {
if (!entry.isFile() || entry.isSymbolicLink())
throw new Error("Invalid live directory entry");
- bytes += (await lstat3(join8(directory, entry.name))).size;
+ bytes += (await lstat4(join8(directory, entry.name))).size;
}
this.storedSizes.set(state, bytes);
return state;
@@ -34757,7 +34787,7 @@ class FileLiveReview {
if (!collision(error))
throw error;
});
- if ((await lstat3(directory)).isSymbolicLink())
+ if ((await lstat4(directory)).isSymbolicLink())
throw new Error("Unsafe live directory");
for (const [name, data] of Object.entries(blobs))
await this.atomic(join8(directory, name), data);
@@ -34766,7 +34796,7 @@ class FileLiveReview {
}
async remove(operationId) {
const directory = this.path(operationId);
- const info = await lstat3(directory);
+ const info = await lstat4(directory);
if (!info.isDirectory() || info.isSymbolicLink())
throw new Error("Unsafe live directory");
await rm3(directory, { recursive: true, force: true });
@@ -34831,7 +34861,7 @@ init_isolation();
init_render();
// src/program-store-node.ts
-import { link as link3, lstat as lstat4, mkdir as mkdir4, readFile as readFile4, readdir as readdir4, stat, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
+import { link as link3, lstat as lstat5, mkdir as mkdir4, readFile as readFile4, readdir as readdir4, stat, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
import { randomUUID as randomUUID4 } from "node:crypto";
import { join as join9 } from "node:path";
@@ -34860,7 +34890,7 @@ async function programReference(code) {
const bytes = new TextEncoder().encode(code);
if (bytes.length > MAX_PROGRAM_BYTES)
throw new Error("Program exceeds the 1 MiB source limit.");
- if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== code)
+ if (new TextDecoder("utf-8", { fatal: false, ignoreBOM: true }).decode(bytes) !== code)
throw new Error("Program must be valid Unicode.");
const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
return `sha256:${Array.from(hash, (b) => b.toString(16).padStart(2, "0")).join("")}`;
@@ -34974,7 +35004,7 @@ class FileProgramStore {
async readHandle(handle) {
const path = join9(this.directory, "refs", `${handle}.ref`);
try {
- const info = await lstat4(path);
+ const info = await lstat5(path);
if (!info.isFile() || info.size !== 71)
throw new Error(`Program handle integrity check failed: ${handle}`);
const canonical = await readFile4(path, "utf8");
@@ -35330,7 +35360,7 @@ class FileBuildCache {
// src/runtime-identity.ts
import { createHash as createHash16 } from "node:crypto";
-import { lstat as lstat5, readFile as readFile6, readdir as readdir6, realpath as realpath4, stat as stat3 } from "node:fs/promises";
+import { lstat as lstat6, readFile as readFile6, readdir as readdir6, realpath as realpath4, stat as stat3 } from "node:fs/promises";
import { createRequire as createRequire2 } from "node:module";
import { dirname as dirname5, join as join11, relative as relative5 } from "node:path";
var digest6 = (bytes) => createHash16("sha256").update(bytes).digest("hex");
@@ -35365,7 +35395,7 @@ async function installedRuntimeIdentity(root, limits = {}) {
};
try {
const pkg = await manifest(root);
- if (pkg.name !== "@kiln/engine")
+ if (pkg.name !== "@instruktlabs/kiln")
throw new Error("Not a Kiln installation.");
const build = JSON.parse(await readFile6(join11(root, "dist", "build.json"), "utf8"));
const worker = build.entries?.worker;
@@ -35388,7 +35418,7 @@ async function installedRuntimeIdentity(root, limits = {}) {
for (const modules of require2.resolve.paths(name) ?? []) {
const candidate = join11(modules, name);
try {
- await lstat5(candidate);
+ await lstat6(candidate);
} catch (error) {
if (error.code === "ENOENT")
continue;
@@ -35507,7 +35537,7 @@ import { join as join13 } from "node:path";
// src/projects-node.ts
import { createHash as createHash17, randomUUID as randomUUID6 } from "node:crypto";
-import { link as link4, lstat as lstat6, mkdir as mkdir6, open, readdir as readdir7, realpath as realpath5, unlink as unlink4 } from "node:fs/promises";
+import { link as link4, lstat as lstat7, mkdir as mkdir6, open, readdir as readdir7, realpath as realpath5, unlink as unlink4 } from "node:fs/promises";
import { join as join12, relative as relative6, resolve as resolve6, sep as sep4 } from "node:path";
init_projects();
var missing2 = (error) => error.code === "ENOENT";
@@ -35548,7 +35578,7 @@ class FileProjectStore {
if (!exists(error))
throw error;
});
- const info = await lstat6(path);
+ const info = await lstat7(path);
if (info.isSymbolicLink())
throw new Error("Project symlinks are not supported");
if (!info.isDirectory())
@@ -35575,7 +35605,7 @@ class FileProjectStore {
}
async load(projectId, directory, sequence) {
const path = join12(directory, filename(sequence));
- const info = await lstat6(path);
+ const info = await lstat7(path);
if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_PROJECT_BYTES)
throw new Error("Invalid or oversized project revision file");
const handle = await open(path, "r");
@@ -36072,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 = "0.10.0";
+var ENGINE_VERSION = "1.0.0-rc.1";
var ENGINE_INSTALL_URL = new URL("../", import.meta.url).href;
function engineIdentity() {
return { version: ENGINE_VERSION, installUrl: ENGINE_INSTALL_URL };
@@ -40542,7 +40572,7 @@ Not returned, over the result size: ${omitted.join(", ")}. Fetch them with anoth
...guidance,
`Families: ${orientation.families.join(", ")}. Tags: ${orientation.tags.join(", ")}.`
] : [],
- ...page.map((entry) => `${entry.id}${entry.execution ? ` (${entry.execution === "async" ? "async; await the result" : "sync"})` : ""}: ${entry.summary}${entry.limitations.length ? ` Limits: ${entry.limitations.join(" ")}` : ""}${formatMatch(entry.match)}`),
+ ...page.map((entry) => `${entry.id} [${entry.stability}]${entry.execution ? ` (${entry.execution === "async" ? "async; await the result" : "sync"})` : ""}: ${entry.summary}${entry.limitations.length ? ` Limits: ${entry.limitations.join(" ")}` : ""}${formatMatch(entry.match)}`),
...input.query && !page.length ? [
"No lexical matches on this page. Try a narrower modeling operation, browse the overview for families/tags, or use custom geometry. This is not proof that the asset is impossible."
] : [],
@@ -41342,7 +41372,7 @@ function createKilnReviewDef(context) {
throw new Error("Reviewed requirements do not match the current trusted host binding");
if (input.assetId && input.parentRevision)
assertSavedRequirementsAuthorized((await context.assetLibrary.read(collection, input.assetId, input.parentRevision)).manifest, active);
- const code = new TextDecoder().decode(source);
+ const code = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(source);
const checkpoint = evaluation.requirements.binding ? createRequirementsCheckpoint(await programReference(code), evaluation.requirements.binding) : undefined;
const dependencies = [
...evaluation.materialResourceProvenance ?? [],
@@ -43158,7 +43188,7 @@ function createKilnAssetDefs(context) {
throw new Error("Source unavailable: this asset contains only a GLB");
return {
...await links(input.collection, record.manifest),
- programRef: await retainProgram(context.programStore, new TextDecoder().decode(code)),
+ programRef: await retainProgram(context.programStore, new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(code)),
requirements: activeRequirements,
savedRequirements: saved,
acceptance: "reevaluation-required"
@@ -43430,7 +43460,7 @@ function createKilnToolHost(context = {}, options = {}) {
};
}
function resourceText(name, bytes) {
- const text = new TextDecoder().decode(bytes);
+ const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: name.endsWith(".js") }).decode(bytes);
if (!name.endsWith(".json"))
return text;
try {
diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjs
index d5537d9f..1168f029 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 = "0.10.0";
+var ENGINE_VERSION = "1.0.0-rc.1";
var ENGINE_INSTALL_URL = new URL("../", import.meta.url).href;
// src/requirements-json.ts
@@ -2355,12 +2355,27 @@ if (isDirectEntry(import.meta.url)) {
process.exit(1);
}
const host = packagedEngineHost({ requirements });
+ let warmup;
+ const cancelWarmup = () => {
+ if (warmup !== undefined)
+ clearTimeout(warmup);
+ warmup = undefined;
+ };
+ process.stdin.once("end", cancelWarmup);
+ process.stdin.once("close", cancelWarmup);
console.error(`kiln MCP server ${MCP_SERVER_VERSION} on stdio`);
serveKilnStdio({
manifest: manifestFor(process.env),
host,
afterFirstToolList: () => {
- setTimeout(() => void host().catch(() => {}), 50);
+ if (process.stdin.readableEnded || process.stdin.destroyed)
+ return;
+ warmup = setTimeout(() => {
+ warmup = undefined;
+ if (!process.stdin.readableEnded && !process.stdin.destroyed)
+ host().catch(() => {});
+ }, 50);
+ warmup.unref();
}
});
}
diff --git a/docs/architecture.md b/docs/architecture.md
index efad5ffb..e2b03f9e 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -4,26 +4,30 @@ Kiln builds JavaScript programs into GLB assets, validates structure, and render
## Entry points
-The checkout is `@kiln/engine`; its package exports point to TypeScript source. Use a compatible TypeScript runtime or bundler. There is no published npm release yet.
+The v1 checkout prepares `@instruktlabs/kiln` with compiled ESM and TypeScript
+declarations. Node consumers need no source loader. Build the SDK on a fresh source
+checkout before using package imports; the installed archive already contains it.
+See the [SDK contract](sdk.md) for runtime and experimental-feature boundaries.
+There is no published npm release yet.
| Subpath | Purpose |
|---|---|
-| `@kiln/engine/tools` | SDK-independent tool definitions and registry factories |
-| `@kiln/engine/agent` | Optional Strands program-reference loop, model factory and exact-revision completion |
-| `@kiln/engine/discovery` | Offline ranked catalog search and exact helper/recipe contracts |
-| `@kiln/engine/requirements` | Host-bound, category-independent asset requirements |
-| `@kiln/engine/render` | Build, serialize, inspect, and compose GLBs |
-| `@kiln/engine/views` | Shared cameras, CPU images, capture limits, GPU port helpers and cell caches |
-| `@kiln/engine/validation` | Syntax and structural checks |
-| `@kiln/engine/primitives` | Geometry and helper catalog |
-| `@kiln/engine/geometry`, `/deform`, `/sweep` | Custom mesh/surface helpers, deformation and profile modeling |
-| `@kiln/engine/implicit` | Experimental bounded field sampling |
-| `@kiln/engine/programs`, `/programs/node` | Immutable memory/file stores and storage statistics |
-| `@kiln/engine/cache`, `/cache/node` | Disposable memory/file build caches |
-| `@kiln/engine/contracts` | Asset and integration manifests |
-| `@kiln/engine/composer` | Layout and overlap helpers |
-| `@kiln/engine/qa` | Deterministic QA gates and corpora |
-| `@kiln/engine/arena` | Pairwise model evaluation |
+| `@instruktlabs/kiln/tools` | SDK-independent tool definitions and registry factories |
+| `@instruktlabs/kiln/agent` | Optional Strands program-reference loop, model factory and exact-revision completion |
+| `@instruktlabs/kiln/discovery` | Offline ranked catalog search and exact helper/recipe contracts |
+| `@instruktlabs/kiln/requirements` | Host-bound, category-independent asset requirements |
+| `@instruktlabs/kiln/render` | Build, serialize, inspect, and compose GLBs |
+| `@instruktlabs/kiln/views` | Shared cameras, CPU images, capture limits, GPU port helpers and cell caches |
+| `@instruktlabs/kiln/validation` | Syntax and structural checks |
+| `@instruktlabs/kiln/primitives` | Geometry and helper catalog |
+| `@instruktlabs/kiln/geometry`, `/deform`, `/sweep` | Custom mesh/surface helpers, deformation and profile modeling |
+| `@instruktlabs/kiln/implicit` | Experimental bounded field sampling |
+| `@instruktlabs/kiln/programs`, `/programs/node` | Immutable memory/file stores and storage statistics |
+| `@instruktlabs/kiln/cache`, `/cache/node` | Disposable memory/file build caches |
+| `@instruktlabs/kiln/contracts` | Asset and integration manifests |
+| `@instruktlabs/kiln/composer` | Layout and overlap helpers |
+| `@instruktlabs/kiln/qa` | Deterministic QA gates and corpora |
+| `@instruktlabs/kiln/arena` | Pairwise model evaluation |
See [package.json](../package.json) for all exports.
@@ -68,6 +72,6 @@ bun run test
bun run test:coverage
```
-Offline tests pin CPU rendering and exercise the checked-in example programs. The coverage ratchet lives in [scripts/check-coverage.mjs](../scripts/check-coverage.mjs). Threshold decreases require an explicit measured rationale. Live provider tests require an explicit opt-in.
+Offline tests pin CPU rendering and exercise the checked-in example programs. The coverage ratchet lives in [scripts/check-coverage.mjs](https://github.com/instruktlabs/kiln/blob/main/scripts/check-coverage.mjs). Threshold decreases require an explicit measured rationale. Live provider tests require an explicit opt-in.
Core dependencies include Three.js, glTF Transform, Manifold, Acorn, and Zod. The agent SDK is an optional peer. Keep provider adapters compatible with the SDK's declared interface version; a TypeScript cast cannot fix a runtime protocol mismatch.
diff --git a/docs/community-exporter.md b/docs/community-exporter.md
index 8050bf43..4d6377f9 100644
--- a/docs/community-exporter.md
+++ b/docs/community-exporter.md
@@ -82,8 +82,8 @@ choice guarantees identical materials after conversion.
Reusable tools:
-- [Existing-source corpus comparison](evaluation/community-exporter.md)
-- [Blender/Unity importer assertions](../scripts/integration/README.md)
+- [Existing-source corpus comparison](https://github.com/instruktlabs/kiln/blob/main/docs/evaluation/community-exporter.md)
+- [Blender/Unity importer assertions](https://github.com/instruktlabs/kiln/blob/main/scripts/integration/README.md)
- `node scripts/exporter-cli-check.mjs`: built CLI, worker and cross-backend disk-cache smoke.
KTX2/runtime optimization is a separate packaging concern. The exporter migration does not change
diff --git a/docs/engine-handoff.md b/docs/engine-handoff.md
index 858c7dff..3780a4c7 100644
--- a/docs/engine-handoff.md
+++ b/docs/engine-handoff.md
@@ -64,7 +64,7 @@ try {
`--render gpu` requires a working GPU renderer and fails if unavailable; it does not accept
a CPU fallback as material evidence. See Kiln's
-[GPU setup](https://github.com/matthew-kissinger/kiln/blob/main/docs/rendering.md#running-the-gpu-renderer).
+[GPU setup](https://github.com/instruktlabs/kiln/blob/main/docs/rendering.md#running-the-gpu-renderer).
In a repository clone, use `node dist/cli.mjs` instead of `node kiln.mjs`, after
`bun install --frozen-lockfile` and `bun run build:runtime`. For an installed distribution,
use the CLI launcher you already use, from a distribution containing this feature.
diff --git a/docs/examples.md b/docs/examples.md
index f079495c..f635b958 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -1,6 +1,6 @@
# Example collection
-[How credits and build records work](example-provenance.md).
+[How credits and build records work](https://github.com/instruktlabs/kiln/blob/main/docs/example-provenance.md).
The public gallery contains 62 selected examples. Archived studies remain in the
repository but are not presented in this gallery.
@@ -130,7 +130,7 @@ Still images are rendered from the source by `bun scripts/hero-shots.ts`. The [i
The collection includes historical studies and current authoring runs. Each example retains its recorded model credit and any known refinement history; missing isolation evidence is marked as unrecorded. These examples are not a comparative model benchmark.
-These are examples, not a controlled model ranking. The [dogfooding notes](dogfooding.md) distinguish new-asset generation from targeted editing and explain the context supplied for the latest runs.
+These are examples, not a controlled model ranking. The [dogfooding notes](https://github.com/instruktlabs/kiln/blob/main/docs/dogfooding.md) distinguish new-asset generation from targeted editing and explain the context supplied for the latest runs.
## Animation
@@ -160,7 +160,7 @@ refits every frame. Because the projection is orthographic and the fit is exact,
put back onto one shared camera by a scale and a translation that are both computable, which is a
correction rather than an approximation.
-![Six-view contact sheet of a procedurally generated field gun](../examples/hero-sheet.png)
+![Six-view contact sheet of a procedurally generated field gun](https://github.com/instruktlabs/kiln/blob/main/examples/hero-sheet.png)
*The contact sheet the model looks at. `../examples/field-gun.kiln.js`, 15,544 triangles: a revolved
bronze barrel bored with a boolean, a stepped oak carriage carrying strapwork and bolt heads, and
diff --git a/docs/export-profiles.md b/docs/export-profiles.md
index 02ad1ea2..e7ceeb87 100644
--- a/docs/export-profiles.md
+++ b/docs/export-profiles.md
@@ -103,7 +103,7 @@ when the client cannot save them. No binary data is put into tool text.
## TypeScript library
```ts
-import { exportAssetGlb } from '@kiln/engine/asset-export';
+import { exportAssetGlb } from '@instruktlabs/kiln/asset-export';
const record = await library.read('project', assetId, revisionId);
const output = await exportAssetGlb(record, {
@@ -219,5 +219,5 @@ of exporter backend qualification and optional geometry/texture compression.
5. Report the files, measured sizes, checks performed and remaining limits. A smaller
GLB does not establish lower draw calls, texture memory or higher frame rate.
-[Qualification results and repeatable local dogfood](https://github.com/matthew-kissinger/kiln/blob/main/docs/evaluation/export-profiles.md)
+[Qualification results and repeatable local dogfood](https://github.com/instruktlabs/kiln/blob/main/docs/evaluation/export-profiles.md)
cover generated source, CLI/MCP/HTTP delivery, native playback and a full Jaeger asset.
diff --git a/docs/extending.md b/docs/extending.md
index cbc61510..5a45e3ce 100644
--- a/docs/extending.md
+++ b/docs/extending.md
@@ -23,8 +23,8 @@ Inspect the exported GLB as well as the authored scene. Topology diagnostics do
The package exposes TypeScript source through explicit subpaths. Use a TypeScript runtime or bundler for library imports; the packaged CLI and MCP entry points run on Node.
```ts
-import { createKilnProgramToolRegistry } from '@kiln/engine/tools';
-import { MemoryProgramStore } from '@kiln/engine/programs';
+import { createKilnProgramToolRegistry } from '@instruktlabs/kiln/tools';
+import { MemoryProgramStore } from '@instruktlabs/kiln/programs';
const tools = createKilnProgramToolRegistry({
programStore: new MemoryProgramStore(),
diff --git a/docs/geometry.md b/docs/geometry.md
index be2682e2..bc2fa17a 100644
--- a/docs/geometry.md
+++ b/docs/geometry.md
@@ -225,7 +225,7 @@ edges while leaving all topology counts green. `extrudeProfile` adds no side-wal
rings unless `divisions` asks for them (default 0, or 16 when it twists). Holed `extrudeProfile` supports
twist/taper, but twist accuracy depends on `divisions`, and its output needs UV
projection or unwrapping before directional textures. See the
-[bounded construction comparison](reviews/2026-09-22-loft-alternatives.md) for
+[bounded construction comparison](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-22-loft-alternatives.md) for
measured alternatives and limits.
Lofts and profile sweeps reject corresponding profile edges that collapse between
@@ -343,7 +343,7 @@ toward -Z; its new surfaces have no inherited UVs. Converting angle units alone
therefore does not make partial surface and solid revolutions interchangeable.
These distinctions are preserved rather than hidden behind a mode-dependent
-return contract. The [bounded comparison](reviews/2026-09-23-path-revolution-contracts.md)
+return contract. The [bounded comparison](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-23-path-revolution-contracts.md)
records the shared implementations and unchanged geometry/export checks.
## Experiment with implicit fields
@@ -357,7 +357,7 @@ const blob = await implicitSurface(
The field is **positive inside**. Bounds and `edgeLength` are required. Smaller spacing can increase cost sharply and is necessary for thin features. The default limits are one million estimated grid cells and eight million actual callback evaluations; `maxCells` and `maxEvaluations` are explicit overrides. An evaluation counter cannot stop a callback that never returns: use the host's process-bounded evaluator for untrusted source.
-Output is experimental, has no UVs, and records resolution and evaluation counts. A finite grid cannot guarantee preservation of every thin feature or exact CAD dimensions. See the [candidate measurements and adoption decisions](experiments/geometry-frontier.md) for implicit surfaces, general beveling, normal-offset shells, and mesh-to-field remeshing.
+Output is experimental, has no UVs, and records resolution and evaluation counts. A finite grid cannot guarantee preservation of every thin feature or exact CAD dimensions. See the [candidate measurements and adoption decisions](https://github.com/instruktlabs/kiln/blob/main/docs/experiments/geometry-frontier.md) for implicit surfaces, general beveling, normal-offset shells, and mesh-to-field remeshing.
### Computational bounds
@@ -415,7 +415,7 @@ Specialized factories also check finite dimensions and bounded counts. Cards acc
pivots outside their panel when the resulting coordinates remain finite. Wings
accept a zero tip chord; stairs accept signed rise/run for descending or reversed
flights. Blade bevels produce one closed cross-section, with partial bevels and a
-full diamond at `edgeBevel: 1`. See the [specialized-domain evidence](reviews/2026-09-21-specialized-primitive-domains.md) for limits and changed bevel topology.
+full diamond at `edgeBevel: 1`. See the [specialized-domain evidence](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-21-specialized-primitive-domains.md) for limits and changed bevel topology.
## Generate UVs in an explicit frame
diff --git a/docs/google.md b/docs/google.md
index d20a0ae2..320fca06 100644
--- a/docs/google.md
+++ b/docs/google.md
@@ -11,7 +11,7 @@ Install Kiln using the [installation guide](install.md). For the current tool se
from a checkout:
```sh
-git clone https://github.com/matthew-kissinger/kiln
+git clone https://github.com/instruktlabs/kiln
cd kiln
bun install --frozen-lockfile
bun run build:runtime
diff --git a/docs/harnesses.md b/docs/harnesses.md
index 040dfee7..c428808d 100644
--- a/docs/harnesses.md
+++ b/docs/harnesses.md
@@ -2,11 +2,11 @@
Seven coding-agent CLIs can drive Kiln unattended. This is the operational reference for
keeping exactly one install of each, invoking them headlessly, and running the repeatable
-checks. For what a dispatch run *is*, see [headless asset generation](dispatch.md); for how
+checks. For what a dispatch run *is*, see [headless asset generation](https://github.com/instruktlabs/kiln/blob/main/docs/dispatch.md); for how
to compare runs fairly, see the `kiln-batch-dispatch` skill; for dated results, see
-[harness checks](dogfooding.md).
+[harness checks](https://github.com/instruktlabs/kiln/blob/main/docs/dogfooding.md).
-The registry of record is [scripts/harness.mjs](../scripts/harness.mjs). Every flag below is
+The registry of record is [scripts/harness.mjs](https://github.com/instruktlabs/kiln/blob/main/scripts/harness.mjs). Every flag below is
there with the diagnosis that put it there. When the two disagree, that file is right.
**September 23 qualification note:** OpenCode dispatch now targets V2 using the
@@ -15,20 +15,20 @@ requested edits have completed with frozen checkout runtimes: 36 main authorings
and 12 held-outs, each with two edits. Native13 also completed generation and two
refinements through the official Google adapter. These are bounded checkout
results; asset-quality defects, broader provider/platform support and installed
-qualification remain explicit. See the [native trace audit](reviews/2026-09-23-native-trace-audit.md),
-[campaign and trace review](reviews/2026-09-22-opencode-main-campaign.md) and
-[migration receipt](reviews/2026-09-22-linux-and-opencode-v2.md).
+qualification remain explicit. See the [native trace audit](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-23-native-trace-audit.md),
+[campaign and trace review](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-22-opencode-main-campaign.md) and
+[migration receipt](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-22-linux-and-opencode-v2.md).
Cline CLI 3.0.64 is an additional experimental route: Kiln CLI plus native image-file
loading completed a correction, but Cline's MCP adapter serializes image results
as text before inference. Do not treat those MCP results as visual review or
increase text limits to carry base64. See the
-[reproduction and supported route](reviews/2026-09-22-cline-image-qualification.md).
+[reproduction and supported route](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-22-cline-image-qualification.md).
OpenCode 2.0.14 preserves standard MCP images in captured provider requests.
Hermes 0.21.4 preserves MCP images as cached files; its vision tool can load them
for the main model when that route supports images. Activated Cline VS Code 4.1.20
tests preserve MCP images in Legacy and reproduce the CLI defect in Next/SDK.
The shared SDK conversion is implicated, not every Cline implementation. See the
-[cross-harness evidence and limits](reviews/2026-09-22-mcp-image-cross-harness.md).
+[cross-harness evidence and limits](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-22-mcp-image-cross-harness.md).
## Cline CLI and Next: image review
@@ -350,14 +350,14 @@ the images. Provider metadata alone verifies neither.
## Adding a harness
-1. Add an entry to `HARNESSES` in [scripts/harness.mjs](../scripts/harness.mjs): `bin`,
+1. Add an entry to `HARNESSES` in [scripts/harness.mjs](https://github.com/instruktlabs/kiln/blob/main/scripts/harness.mjs): `bin`,
`defaultModel` (`null` when account entitlement is unknowable), `probe`, `argv`, and
`fallbackModels`. Record *why* each flag is there.
2. Add its MCP config spelling to `managedFiles` in
[scripts/create-workspace.mjs](../scripts/create-workspace.mjs) and its name to the
`harnesses` list beside it.
3. Add a case to the workspace test in
- [src/\_\_tests\_\_/workspace-bootstrap.test.ts](../src/__tests__/workspace-bootstrap.test.ts)
+ [src/\_\_tests\_\_/workspace-bootstrap.test.ts](https://github.com/instruktlabs/kiln/blob/main/src/__tests__/workspace-bootstrap.test.ts)
asserting the generated config names the runtime's `dist/mcp-server.mjs`.
4. Run `bun run smoke:harness -- --harness <name>` before trusting it with a brief.
diff --git a/docs/install.md b/docs/install.md
index db6de880..0f7af77e 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1,20 +1,22 @@
# Install Kiln for your coding agent
-This guide installs Kiln **0.10.0**: standalone authoring with optional projects, a
-material library and Live Review in the local dashboard, served to a coding agent over
-the 2026-07-28 and 2025 protocol revisions. [CHANGELOG.md](../CHANGELOG.md)
-lists what changed. Existing users should read the [migration notes](migration.md)
-before upgrading a workspace. **0.10.0 is a source and site preview for dogfooding**, with its
-package tarball attached to the
-[v0.10.0 release](https://github.com/matthew-kissinger/kiln/releases/tag/v0.10.0).
-Package publication is deferred to v1.0.
+This checkout prepares **Kiln 1.0** under the package name `@instruktlabs/kiln`.
+Its development build is not published to npm. Build a [local package](#install-a-local-package)
+to test this checkout, or use a previously released tarball with that release's
+documentation. [CHANGELOG.md](../CHANGELOG.md) lists changes; read the
+[migration notes](migration.md) before upgrading an existing workspace.
+
+Kiln supports standalone authoring with optional projects, a material library and
+Live Review in the local dashboard. The [SDK](sdk.md), CLI and MCP server use the
+same engine and saved-source contracts.
## Install the package
-Kiln is distributed as a tarball, `kiln-engine-VERSION.tgz`, installed with Node.js and
+The unpublished candidate packs as `instruktlabs-kiln-VERSION.tgz`; earlier releases
+used `kiln-engine-VERSION.tgz`. Install the actual tarball with Node.js and
npm. Use the tarball and checksum actually attached to the current
-[release](https://github.com/matthew-kissinger/kiln/releases) (for 0.10.0, the
-[v0.10.0 release](https://github.com/matthew-kissinger/kiln/releases/tag/v0.10.0)): download
+[release](https://github.com/instruktlabs/kiln/releases) (for 0.10.0, the
+[v0.10.0 release](https://github.com/instruktlabs/kiln/releases/tag/v0.10.0)): download
the tarball and `SHA256SUMS.txt`, check the tarball against the checksum file before
installing (`sha256sum -c SHA256SUMS.txt` beside it, or `Get-FileHash` on Windows), and read
that release's documentation; the release also attaches the installed-package receipts that
@@ -29,13 +31,17 @@ use the CLI/MCP tools. Use the real tarball path and filename:
mkdir kiln-install
cd kiln-install
npm init -y
-npm install /absolute/path/to/kiln-engine-VERSION.tgz --omit=dev --include=optional
+npm install /absolute/path/to/PACKAGE.tgz --omit=dev --include=optional
npm exec --offline -- kiln-init ../my-assets --harness opencode # or claude, codex, hermes, agy, copilot, cursor-agent
cd ../my-assets
# Follow START.md for your harness
```
-Kiln is not published to the npm registry; do not run a registry install command.
+Kiln is not published to the npm registry; do not run a registry install command yet.
+The installed package exposes `kiln`, `kiln-init` and `kiln-mcp`. The last command is
+a stdio server for MCP clients, not an interactive shell. A client can launch it
+from an existing installation with `npm exec --offline -- kiln-mcp`; package-based
+plugin definitions will pin an exact published version once the registry release exists.
npm 11 may warn that the optional `webgpu` package's install script is not covered by
`allowScripts` (`npm warn install-scripts`). That script only clears the macOS download
quarantine from the prebuilt Dawn binary the package ships; Windows and Linux need
@@ -49,7 +55,7 @@ and `--upgrade` as described below to refresh managed workspace skills and launc
Do not point an old package at new documentation and assume its tools have changed.
Released-package checks cover Windows, Linux, and hosted Apple Silicon/Intel Mac;
-see the [dated platform receipts](evaluation/platform-matrix.md). A receipt qualifies
+see the [dated platform receipts](https://github.com/instruktlabs/kiln/blob/main/docs/evaluation/platform-matrix.md). A receipt qualifies
the tarball it names, not a later build. Community reports on local Mac installations
are welcome. CPU package setup and optional GPU support are separate checks.
@@ -103,18 +109,19 @@ node -p "process.platform + ' ' + process.arch"
```
The last line should say `darwin arm64` or `darwin x64`. The npm supplied with Node
-can install the package; contributor CI pins npm 12.0.2 for reproducible receipts.
+can install the package; contributor CI pins npm 12.2.0 for reproducible receipts.
You do not need to change global npm or install Homebrew for this workflow.
-The optional built-in Strands agent requires Node **22.2.0+** and its optional SDK
-and provider dependencies. Using Kiln from Cline or another MCP/CLI agent does not
-require Strands or its model-provider packages. TypeScript library exports require
-a TypeScript-capable loader or build system; the installed commands are compiled.
+The optional built-in Strands agent and SDK subpaths `agent` and `composer/agent`
+require Node **22.2.0+** and their optional SDK and provider dependencies.
+Using Kiln from Cline or another MCP/CLI agent does not
+require Strands or its model-provider packages. The v1 library and commands are
+compiled; package imports need no TypeScript loader.
Maintainer release checks still use the exact versions in the source repository's
-`toolchain.json`. Current Node 20/22-minimum/24 evidence is from
-fresh Windows package installations (Node 20.15.0 and 22.23.2); Linux floor and
-macOS package jobs qualify the current release through CI. Physical GPU coverage
-and distribution-specific Debian/Cline setup remain separate checks.
+`toolchain.json`. Package CI checks Linux Node 20.15.0, 22.2.0 and 24.20.0,
+plus Node 22.23.3 on Linux, Windows and both macOS architectures. Each receipt
+qualifies only its named tarball; a later candidate needs its own passing checks.
+Physical GPU coverage and distribution-specific Debian/Cline setup remain separate checks.
Cline CLI 3.0.64 and VS Code 4.1.20 Next/SDK have a known MCP-to-model limitation:
image responses become text, with larger results also truncated. The tested
@@ -134,7 +141,7 @@ Choose a permanent installation directory and use the real tarball filename:
mkdir -p "$HOME/Developer/kiln-install"
cd "$HOME/Developer/kiln-install"
npm init -y
-npm install "/absolute/path/to/kiln-engine-VERSION.tgz" --omit=dev --include=optional
+npm install "/absolute/path/to/PACKAGE.tgz" --omit=dev --include=optional
npm exec --offline -- kiln-init ../my-assets --harness codex
cd ../my-assets
node kiln.mjs --help
@@ -168,7 +175,7 @@ by the package smoke alongside the native image dependency.
## Install from the repository
```sh
-git clone --filter=blob:none https://github.com/matthew-kissinger/kiln
+git clone --filter=blob:none https://github.com/instruktlabs/kiln
cd kiln
bun install --frozen-lockfile
bun run build:runtime
@@ -215,17 +222,38 @@ Use the actual tarball path and filename returned by `npm pack`:
mkdir kiln-install
cd kiln-install
npm init -y
-npm install /absolute/path/to/kiln-engine-VERSION.tgz --omit=dev --include=optional
+npm install /absolute/path/to/PACKAGE.tgz --omit=dev --include=optional
npm exec --offline -- kiln-init ../my-assets --harness opencode # or claude, codex, hermes, agy, copilot, cursor-agent
```
`kiln` renders programs and imports/exports source revisions. `kiln-init` creates a
-workspace. These are installed package commands, not currently published npm
-package names. Library exports remain TypeScript source for Bun or a compatible
-bundler; ordinary Node callers should use the CLI/MCP bundles. The optional
+workspace, and `kiln-mcp` starts the stdio server. These are installed commands from
+the still-unpublished `@instruktlabs/kiln` package. Library consumers use its compiled
+ESM and TypeScript declarations through the [SDK entrypoints](sdk.md), without a
+source loader. The optional
`kiln generate` adapter is separate and needs its agent/provider dependencies;
connecting an existing harness does not load that stack.
+### Optional built-in agent dependencies
+
+Install these only when using Kiln's own generation loop or OpenRouter model
+adapter. Run npm in the engine installation directory created above, where its
+`package.json` lists `@instruktlabs/kiln`, rather than in an asset workspace or
+the disposable plugin cache:
+
+```sh
+npm install @strands-agents/[email protected] @openrouter/[email protected] @ai-sdk/[email protected]
+```
+
+These exact versions passed a fresh installed-package check for all SDK imports
+and declarations, native render/completion tools and offline OpenRouter adapter
+construction. The declared minimum peers (Strands 1.18.0, OpenRouter 2.10.0,
+provider 3.0.0) passed the same bounded check. Native Anthropic, OpenAI, Google and
+Bedrock routes additionally require their selected adapter's dependencies.
+Live model availability and provider credentials are separate from installation;
+the package does not supply a model subscription. External Claude Code, Codex and
+other CLI/MCP workflows do not need any of these peers.
+
## Choose a harness
| Harness | Project configuration | Launch from the workspace |
@@ -241,7 +269,7 @@ separate profile needs its own authentication or provider credentials supplied
through the environment; setup does not copy credentials. The Antigravity launcher
sets the absolute project directory and disables automatic skill expansion in print
mode. Name `kiln_workspace` in the brief, use the project skill copies, and pass
-absolute task-file paths. See [clean-room setup](clean-room.md) for evaluation controls and limitations.
+absolute task-file paths. See [clean-room setup](https://github.com/instruktlabs/kiln/blob/main/docs/clean-room.md) for evaluation controls and limitations.
## Verify the connection
@@ -370,10 +398,55 @@ server session; changing the file requires a new session. The default remains
neutral authoring. See [host requirements](migration.md#migrate-evaluator-integrations-together)
for the binding format and task/asset lineage boundary.
-The Claude plugin manifest also launches the Node bundle. A plugin clone alone does
-not establish that its runtime dependencies were installed: verify tool discovery
-and a render before considering that path ready. Use project setup when the host
-cannot install the plugin's dependencies.
+The legacy root plugin manifests launch the Node bundle from an engine installation.
+The v1 local plugin below uses a smaller bundle and creates an explicit workspace.
+
+## Local Claude Code and Codex plugins
+
+**The current branch is a development candidate.** The `v1.0.0` tag and npm release
+must exist before using these release commands. Maintainers qualify development
+bundles with the reviewed local engine archive instead.
+
+The plugin is `kiln-engine` in the Instrukt Labs marketplace `instruktlabs`. Its
+cache contains setup guidance and an installer, while the pinned engine and asset
+workspaces stay in persistent directories outside that cache. Installing the plugin
+does not start a second global Kiln MCP server.
+
+For Claude Code:
+
+```sh
+claude plugin marketplace add instruktlabs/kiln#v1.0.0 --sparse .claude-plugin plugins/kiln-engine
+claude plugin install kiln-engine@instruktlabs
+```
+
+For Codex:
+
+```sh
+codex plugin marketplace add instruktlabs/kiln --ref v1.0.0 --sparse .agents/plugins --sparse plugins/kiln-engine
+codex plugin add kiln-engine@instruktlabs
+```
+
+Ask your agent to set up a Kiln asset workspace. The setup skill installs the exact
+package version in `runtime.json` through npm, with optional dependencies included
+and lifecycle scripts disabled. Node.js and npm are required; an engine checkout,
+Bun and a separate model API key are not. An existing working workspace can be used
+as-is. Otherwise choose an empty directory and follow its generated `START.md` to
+open a new authoring session. Accept the host's project/MCP trust prompts, then
+verify `kiln_discover({capabilities:true})` on `kiln_workspace` and an actual render.
+
+The workspace owns its author/refine/QA skills and MCP configuration. The plugin
+registers only setup, avoiding duplicate authoring skills and servers. It does not
+redirect saved assets or rewrite an existing workspace when its cached version
+changes. For an intended engine update, use the new plugin's helper with `--check`
+and `--upgrade`, following its bundled `references/plugin-install.md`; customized
+managed files require explicit conflict resolution. Select the desired release tag
+when changing the marketplace source. Removing the plugin leaves the persistent
+runtime and authored assets in place.
+
+An older `kiln@kiln` installation can expose a separate global `kiln` server.
+Disable or uninstall that old plugin in the relevant host before using the new
+workspace workflow, after recording any custom store paths. Do not delete its
+source store. See [the v1 migration notes](migration.md#local-plugin-transition).
## Verify a distribution as a contributor
@@ -388,19 +461,30 @@ in a temporary directory, tests CSG and UV WASM, CPU images, MCP discovery, refe
editing, persistence across restart, and exact source export. It retains a JSON
receipt and artifacts at the printed path. Normal unit tests do not run npm installs.
+The maintained local plugin is generated with
+`node scripts/package-local-plugin.mjs FRESH_OUTPUT_DIRECTORY`.
+Review the generated files before copying them into `plugins/kiln-engine`, then run
+`node scripts/package-local-plugin.mjs plugins/kiln-engine --check`.
+The unit suite checks those bytes, including the version pin and complete setup
+reference. The package smoke checks that the installed npm archive contains both
+catalogs and every file named by the plugin's hash inventory. Validate the plugin
+itself with `claude plugin validate plugins/kiln-engine --strict`, in addition to
+the marketplace manifest. A local-path Claude installation loads in place; use a
+Git-backed marketplace to qualify a copied cache installation.
+
To test an existing package instead of packing the checkout, run
`node scripts/smoke-package.mjs --tarball /absolute/candidate.tgz`. For Linux, run
`node scripts/smoke-package-linux.mjs /absolute/candidate.tgz /absolute/receipt.json`
-with Docker running. See the [recorded Linux package check](evaluation/platform-matrix.md)
+with Docker running. See the [recorded Linux package check](https://github.com/instruktlabs/kiln/blob/main/docs/evaluation/platform-matrix.md)
for the pinned image, exact candidate hash, coverage, and limitations.
CI builds one tarball on Linux, then runs the same npm package smoke natively on
-`macos-15` (ARM64) and `macos-15-intel` (x64), with Node 22.23.2 and npm 12.0.2.
+`macos-15` (ARM64) and `macos-15-intel` (x64), with Node 22.23.3 and npm 12.2.0.
The Mac jobs install no contributor dependencies and do not set up Bun. Their
retained receipts include the tarball hash, native architecture and completed
checks. These versioned runner labels follow [GitHub's runner catalog](https://docs.github.com/en/actions/reference/runners/github-hosted-runners);
GitHub maintains the underlying images, so the labels are not immutable OS images.
-Both architectures passed all 16 package checks in [CI run 33996715717](https://github.com/matthew-kissinger/kiln/actions/runs/33996715717). The retained receipts are linked in the platform matrix.
+Both architectures passed all 16 package checks in [CI run 33996715717](https://github.com/instruktlabs/kiln/actions/runs/33996715717). The retained receipts are linked in the platform matrix.
CI also runs Linux package jobs at Node 20.15.0, 22.2.0 and 24.20.0 using each
distribution's npm. The release build retains its pinned maintainer toolchain.
@@ -413,7 +497,7 @@ and none of these jobs qualifies physical AMD, Intel or Apple GPU behavior.
## Embed the tools
```ts
-import { createKilnProgramToolRegistry } from '@kiln/engine/tools';
+import { createKilnProgramToolRegistry } from '@instruktlabs/kiln/tools';
const tools = createKilnProgramToolRegistry();
```
diff --git a/docs/material-library.md b/docs/material-library.md
index 42ec40c4..819e735c 100644
--- a/docs/material-library.md
+++ b/docs/material-library.md
@@ -84,9 +84,9 @@ recording meters does not silently change geometry or UVs.
```ts
import { FileMaterialLibrary, createMaterialLibraryPayload,
- decodeMaterialLibraryPayload } from '@kiln/engine/material-library/node';
-import { createMaterialPresetDraft } from '@kiln/engine/material-presets';
-import { createMaterialRecordV1 } from '@kiln/engine/material-library/node';
+ decodeMaterialLibraryPayload } from '@instruktlabs/kiln/material-library/node';
+import { createMaterialPresetDraft } from '@instruktlabs/kiln/material-presets';
+import { createMaterialRecordV1 } from '@instruktlabs/kiln/material-library/node';
const library = new FileMaterialLibrary('/workspace/.kiln/materials');
const record = await createMaterialRecordV1(createMaterialPresetDraft('wood-grain', {
diff --git a/docs/migration.md b/docs/migration.md
index 1db153e9..f829b4ed 100644
--- a/docs/migration.md
+++ b/docs/migration.md
@@ -4,11 +4,59 @@ Existing inline-code transport and the legacy capture format remain supported. T
Discovery and authoring-helper changes below require explicit migration; retired
names have no callable compatibility aliases.
-## Unreleased changes planned for 0.11
+## Unreleased changes planned for 1.0
-These changes describe the local alignment candidate, not the downloadable 0.10.0
+These changes describe the 1.0 release candidate, not the downloadable 0.10.0
release. Use the documentation and package from the same release when upgrading.
+### Package and SDK identity
+
+The npm package becomes `@instruktlabs/kiln`. The previous `@kiln/engine` name was
+used by downloaded private-package tarballs; this change does not publish an alias
+under that old namespace. The current `1.0.0-rc.1` checkout is still unpublished.
+
+Update application imports to `@instruktlabs/kiln` and its documented subpaths.
+Exports now provide compiled ESM and TypeScript declarations, so Node consumers no
+longer need a source loader. The root is a library entrypoint, not the CLI. Run
+`kiln` for CLI commands, `kiln-init` for workspace setup, and `kiln-mcp` for stdio MCP.
+CommonJS and unlisted internal file paths are not public v1 APIs.
+
+Keep the previous installation available while testing the new package in a separate
+installation directory. Stop active harness sessions, run the new installation's
+`kiln-init EXISTING_WORKSPACE --check`, then use `--upgrade` after resolving reported
+customizations. Upgrade refreshes managed runtime paths and skills; it preserves
+saved assets, source revisions and user-authored instruction changes, refusing
+conflicts instead of overwriting them. Keep original engine versions for historical
+artifact replay; a new build does not retroactively qualify an old asset.
+
+Experimental implicit modeling and the opt-in community exporter retain their
+labels and limitations. The shared tool registry, Discovery metadata and dedicated
+documentation remain authoritative for those boundaries.
+
+### Local plugin transition
+
+The v1 local plugin is `kiln-engine@instruktlabs`. Its small cached bundle registers
+setup only; the generated workspace owns its `kiln_workspace` MCP server and
+authoring skills. It installs an exact engine version in persistent storage outside
+the plugin cache. The [installation guide](install.md#local-claude-code-and-codex-plugins)
+documents the release commands and current development status.
+
+If you installed the earlier `kiln@kiln` plugin, record its custom source/asset store
+paths before disabling or uninstalling it through the host. That global `kiln`
+server is a different installation from a managed workspace; do not leave both
+active and silently choose one. Removing the plugin is not a request to delete
+saved source, engine installations or exported assets. Add the new marketplace and
+plugin explicitly. A checkout used for engine development can retain its own
+project MCP configuration; authoring takes place in a separate workspace.
+
+Installing or updating the new plugin leaves existing managed workspaces unchanged.
+Reopen a current workspace normally, or intentionally run its new plugin helper's
+`--check` and `--upgrade` flow. Resolve modified managed files before upgrading and
+restart the harness. Plugin-cache cleanup cannot invalidate the workspace's engine
+path, because the runtime is stored separately.
+
+### Engine behavior
+
- **Full optimization.** `optimize: 'full'` replaces flatten/join with rigid-group
merging. The rigid-merge pass keeps every node's name, parent and transform, but an
ordinary named mesh can become empty or hold its group's merged geometry. The
@@ -332,8 +380,8 @@ identity and lineage history before retaining source. It reports
Older assets without a current receipt require explicit migration before restore
or revision; download and inspection of their saved records remain available.
-Hosts import the current contract/store from `@kiln/engine/requirements` and the
-explicit legacy converter from `@kiln/engine/requirements/migration`. CLI `render`,
+Hosts import the current contract/store from `@instruktlabs/kiln/requirements` and the
+explicit legacy converter from `@instruktlabs/kiln/requirements/migration`. CLI `render`,
`generate`, `save`, and `asset --restore` accept
`--requirements <host-binding.json>`. The file contains a complete current binding
returned by the host store, not source-authored metadata, a bare category or an
@@ -357,9 +405,9 @@ Tool arguments and source metadata cannot select or replace the host binding.
## Review explicit legacy data conversion
-Library callers of `@kiln/engine/qa` now use `collectRequirementsSceneEvidence`
+Library callers of `@instruktlabs/kiln/qa` now use `collectRequirementsSceneEvidence`
and `runRequirementsSceneQa` with a context from `resolveRequirementsContext`
-(`@kiln/engine/requirements`). Pass the collected evidence to the runner and
+(`@instruktlabs/kiln/requirements`). Pass the collected evidence to the runner and
use `appendRequirementsFinalQa` for exported-artifact checks. Scene-only QA is
not final-GLB acceptance. Reports carry schema version 2 and the policy identity.
@@ -385,7 +433,7 @@ and exit 2 means invalid command arguments. Inputs must be regular UTF-8 JSON fi
no larger than 1 MiB. No renderer, model, asset-store write or source execution occurs.
The manifest API is `migrateAssetManifestV1ToRequirements` from
-`@kiln/engine/requirements/migration`; the existing intent API is
+`@instruktlabs/kiln/requirements/migration`; the existing intent API is
`migrateAssetIntentV1ToRequirements`. A manifest proposal keeps the old revision and
file hashes, carries non-policy build options as review data, and requires a rebuild.
It is a versioned migration proposal, **not a new saved manifest**. Old QA, preview
@@ -475,7 +523,7 @@ remain separate mechanisms.
## Use the native program-reference loop
-The public `@kiln/engine/tools` export no longer includes
+The public `@instruktlabs/kiln/tools` export no longer includes
`createKilnToolRegistry` or `kilnToolRegistry`. Those factories recreated the
retired four-tool workflow. Use `createKilnProgramToolRegistry` for a host-managed
workflow, or `createKilnNativeToolRegistry` with native completion. Both use
@@ -497,12 +545,12 @@ module and thinking A/B runner are retired. Use runtime-cost metrics from the
reviewed artifact and request explicit refinement before selecting its final
revision. Do not re-execute source just to retrieve a post-completion grade.
-The category-driven `@kiln/engine/prompt` subpath, `getSystemPrompt`,
+The category-driven `@instruktlabs/kiln/prompt` subpath, `getSystemPrompt`,
`buildUserPrompt` and their full/trimmed/current/unified prompt variants are
removed. They advertised retired tools and injected category-specific generation
rules. There is no fallback or alias. Use `runKilnAgent` for Kiln's native
bootstrap, or build a custom harness over the current registry and Discovery.
-`@kiln/engine/prompt-api` remains a pure catalog text formatter; it does not
+`@instruktlabs/kiln/prompt-api` remains a pure catalog text formatter; it does not
configure an agent or generate the maintained skills. The old `kiln-glb` skill
drift checks and absent `kiln:gen-skill` command are retired; use `check:skills`
for the maintained `skills/` tree.
@@ -550,7 +598,7 @@ evidence. Other live routes and cold installed-package qualification remain
separate. See [native workflow and support limits](runtime.md#optional-native-strands-workflow).
The package version moves with every change that ships, so the version you are moving to
-is whatever the [latest release](https://github.com/matthew-kissinger/kiln/releases/latest)
+is whatever the [latest release](https://github.com/instruktlabs/kiln/releases/latest)
says; see [CHANGELOG.md](../CHANGELOG.md) for what changed between any two.
## Retain the source once
@@ -586,7 +634,7 @@ The GPU service now preserves HDR values until tone mapping and conversion to
sRGB. Earlier previews could clip highlights despite reporting full-material
rendering. Regenerate comparison images with the updated service; its capture
identity invalidates older cached cells. The legacy beauty-image route also works
-again. [Measured display correction](evaluation/results/gpu-display-output.md).
+again. [Measured display correction](https://github.com/instruktlabs/kiln/blob/main/docs/evaluation/results/gpu-display-output.md).
## Replace removed authoring helpers
@@ -698,8 +746,8 @@ project's `kiln_workspace` server to avoid selecting an older global plugin.
`implicitSurface` is experimental and bounded. General bevel, shell and remeshing
are not stable helpers in this release. Their trials and adoption decisions are
-documented in [geometry experiments](experiments/geometry-frontier.md) and the
-[additional acceptance cases](experiments/geometry-acceptance.md). Ordinary
+documented in [geometry experiments](https://github.com/instruktlabs/kiln/blob/main/docs/experiments/geometry-frontier.md) and the
+[additional acceptance cases](https://github.com/instruktlabs/kiln/blob/main/docs/experiments/geometry-acceptance.md). Ordinary
JavaScript functions remain the supported way to reuse parameterized parts.
## Assembly roots and physical roof frames
diff --git a/docs/plans/2026-10-05-v1-publication-plan.md b/docs/plans/2026-10-05-v1-publication-plan.md
new file mode 100644
index 00000000..0fdbd407
--- /dev/null
+++ b/docs/plans/2026-10-05-v1-publication-plan.md
@@ -0,0 +1,1433 @@
+# Kiln Engine 1.0 publication plan
+
+Research dates: 5-6 October 2026. Repository audited at
+`cf4abe6c7b142da56d005751e21d0f9c57a9dd21`.
+Plan updated: 6 October 2026, including release sequencing, ownership, hosting economics and decision handling.
+
+Status: documented v1 plan, with owner decisions recorded in section 9 and remaining
+choices proposed for review. This document records research and planned work;
+the document itself does not authorize a repository transfer, account creation, paid deployment,
+package publication or directory submission. No engine implementation or package
+publication was performed during this audit. The owner separately authorized the
+private Sites probe on 6 October; its local and hosted results are recorded below.
+Later on 6 October the owner explicitly authorized doing the GitHub transfer and
+npm onboarding immediately. The native transfer to `instruktlabs/kiln` completed;
+community/history preservation passed comparison and the local origin was updated.
+The owner-approved exact Bun action was added to the inherited Actions allowlist;
+a Linux CI job rerun passed under the new ownership. See the
+[setup receipt](../reviews/2026-10-06-publisher-setup.md). npm personal
+account creation and email verification are complete, and the free `instruktlabs`
+organization is registered with `matthew-kissinger` as owner. Two security keys,
+write-action 2FA and organization-wide 2FA enforcement are verified. The owner also
+explicitly authorized Workers Paid if needed; the signed-in dashboard confirms
+Workers Paid and R2 Paid are already active, so no purchase was needed. These setup
+actions do not activate the full implementation goal or publish a package.
+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
+
+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
+affordable authenticated hosted MCP service for ChatGPT/Codex; and submit complete,
+tested candidates to the OpenAI and Anthropic plugin directories. Publish under
+Instrukt Labs as `@instruktlabs/kiln` under the secured npm organization; preserve
+existing workspaces and contributor history,
+and keep outside issue/PR triage out of this cycle. Develop integrations alongside
+package readiness, publish the package when its own gates pass, and track vendor
+approval separately from the work the maintainer can complete.
+
+Include publisher onboarding and release automation in the goal: establish the npm
+account/organization, configure trusted publishing, and verify the resulting release
+path. The agent carries technical preparation and routine setup through completion;
+the owner handles private authentication, identity verification and the concrete
+publication approvals still required. Sequence these handoffs when actionable and
+continue independent implementation while awaiting them. The owner requested this
+division of work on 6 October; adding it to the goal statement does not start execution.
+
+The owner selected `@instruktlabs/kiln` and an early GitHub transfer on 6 October,
+with preservation of stars and open PRs as an explicit condition. The goal statement
+describes the intended development-cycle outcome; this documentation update does
+not itself perform implementation, a transfer or external release actions.
+
+The owner requested a ready-to-start overnight execution goal on 6 October. Its
+copyable text is in [the execution goal](2026-10-06-v1-execution-goal.md). Perform the
+remaining transfer closeout and npm onboarding first while the owner can observe and respond.
+Surface account handoffs in both the visible browser and chat, with decisions
+sequenced through the question tool. This is a requested execution order and target,
+not evidence that the full plan can finish in one night; see section 7. The goal has
+not been activated by this documentation request.
+
+### Confirmed direction and proposed choices
+
+The owner has confirmed the 1.0 release target, Instrukt Labs organization/LLC
+ownership, exclusion of incoming community issue/PR work before publication, and
+permission for the bounded private Sites probe. The owner selected the npm name
+`@instruktlabs/kiln` and an early GitHub move with community history preserved. The
+owner has also invited decisions to be surfaced now or through questions while work
+proceeds. On 6 October the owner clarified that **$20/month is an initial target,
+not a hard ceiling**: optimize cost and allow deliberate growth, avoiding sustained
+hundreds of dollars without funding. The owner has Cloudflare and ChatGPT Pro and
+is open to sponsorships/credits. The owner also selected retention of saved assets until
+deleted within a storage quota, with unsaved work expiring after seven days. The
+owner selected an all-Cloudflare production stack on 6 October, permits a bounded
+Sites probe, and wants another provider considered only for a demonstrated cost,
+performance, capacity or compatibility reason. Exact quotas and production
+qualification remain open. The owner selected `kiln.instruktlabs.com` for the
+hosted service and its MCP/support/privacy pages on 6 October. Record
+explicit answers in section 9 rather than treating a
+recommendation or an unanswered question as acceptance.
+After reviewing the concrete inventory and MCP exposure on 6 October, the owner
+accepted retaining existing experimental functionality, making its labels and
+limitations consistently visible, documenting stable APIs separately, and keeping
+the alternative exporter explicitly selected. Any change to feature availability
+or defaults still needs its own evidence and review.
+
+## 1. Recommended release
+
+Publish **Kiln Engine**, maintained by **Instrukt Labs**, as **`@instruktlabs/kiln`**
+under the now-registered npm organization. Keep the `kiln` CLI and the product name.
+Use one versioned engine package, thin integration packages, and a hosted service
+running the same qualified engine artifact. Do not split the engine into a new
+multi-package architecture merely to publish it.
+
+The cycle should deliver:
+
+1. A public npm `1.0.0` with a defined JavaScript/TypeScript SDK, CLI, workspace setup,
+ local MCP server, maintained skills and migration instructions.
+2. Working local plugins for Claude Code and Codex, installable without cloning or
+ building the engine repository.
+3. A small hosted Kiln service supporting a public OpenAI plugin for ChatGPT and
+ Codex, with authentication, isolated evaluation, persistent private artifacts,
+ reliable downloads and bounded operating cost.
+4. Submitted OpenAI and Anthropic directory candidates, each with reproducible
+ installation and end-to-end evidence. Directory acceptance is an external
+ milestone; do not promise approval within the development cycle.
+
+Retain the CPU rasterizer. Qualify the existing software Vulkan path for material
+previews before considering rented GPUs or a new software renderer. Keep optional
+Strands/provider execution out of the hosted baseline: the user's agent authors the
+source and Kiln evaluates it, so normal MCP operation does not require Kiln-funded
+model inference.
+
+The owner explicitly excluded outside issues and PRs from this pre-v1 scope. Existing
+contributions should remain intact and receive a separate triage cycle. New packs,
+Troy features, whole-game performance work and a commercial Studio application are
+also outside this publication cycle.
+
+## 2. Publisher, package name and repository ownership
+
+### Initial read-only namespace findings, before registration
+
+Public registry and profile checks were read-only. A missing package or scope is a
+point-in-time signal, not a reservation or a guarantee that registration will succeed.
+
+| Name | Observed result | Recommendation |
+| --- | --- | --- |
+| `kiln` | Published package, latest `0.0.1`, belonging to another maintainer | Unavailable |
+| `@kiln/engine` | Package missing; `kiln` npm scope exists; owner confirms it is someone else's | Blocked by scope ownership |
+| `@instruktlabs/kiln` | Package 404; npm organization page says `Scope not found` | First choice |
+| `@instruktlabs/kiln-engine` | Package 404; same scope result | More explicit fallback within the chosen scope |
+| `@instruktlabs/engine` | Package 404; same scope result | Too generic for an organization with multiple products |
+| `@kilnstudio/engine` | Package 404; npm scope page says `Scope not found` | Viable alternative, but requires another brand namespace |
+| `kiln-engine` | Package 404 | Unscoped fallback; less useful for organization governance |
+| `@kiln3d/engine` | Package missing, but `kiln3d` account exists | Avoid: closely adjacent naming collision |
+
+The existing [Kiln3D npm package](https://www.npmjs.com/package/kiln3d) describes a
+Kiln MCP server for AI-assisted 3D printing, with a
+[separate repository](https://github.com/codeofaxel/Kiln). This makes the publisher
+qualification useful: **Kiln Engine by Instrukt Labs**, with a clear description of
+procedural 3D asset authoring. npm checks do not establish trademark clearance.
+
+The verified GitHub organization is [instruktlabs](https://github.com/instruktlabs),
+display name **Instrukt Labs**, with one public repository,
+[matter-field](https://github.com/instruktlabs/matter-field). The owner states that
+Instrukt Labs is also the LLC name. Use the exact legal entity details during vendor
+verification, subject to the owner's confirmation of the account information.
+
+### npm ownership is independent of GitHub ownership
+
+GitHub organization ownership does not reserve the same npm scope. Create an npm
+organization separately and give the release workflow publishing access. Public npm
+organizations are free. `@instruktlabs/kiln` can be published from the existing
+`matthew-kissinger/kiln` repository; the npm scope and GitHub owner do not need to
+match. Configure trusted publishing for the repository that actually runs the workflow.
+See [npm organizations](https://docs.npmjs.com/organizations/),
+[organization creation](https://docs.npmjs.com/creating-an-organization/) and
+[trusted publishing](https://docs.npmjs.com/trusted-publishers/).
+
+Owner-selected community destination: **`instruktlabs/kiln`**. Transfer early in the
+cycle, before creating final publishing trust and directory bindings, subject to the
+owner's condition that stars, open PRs and existing community history are preserved.
+A transfer preserves issues, PRs, stars and Git history and redirects repository URLs.
+It does not require reviewing or merging incoming PRs. GitHub Pages URLs are a
+separate concern. See [GitHub's transfer documentation](https://docs.github.com/en/repositories/creating-and-managing-repositories/transferring-a-repository).
+
+Personal portfolio visibility is compatible with organization ownership. GitHub
+allows a public repository to be pinned on a personal profile when the user owns it
+or has contributed within the preceding year. The owner's recent Kiln contributions
+qualify; verify the personal pin after transfer and optionally feature the same repo
+on the organization profile. Keep the original history and attribution. See
+[GitHub's profile reference](https://docs.github.com/en/account-and-profile/reference/profile-reference).
+
+### Transfer verification, checked 6 October 2026
+
+GitHub's current transfer documentation confirms preservation of stars, watchers,
+issues, PRs, wiki, commit contributions and fork relationships. Existing collaborators,
+webhooks, secrets and deploy keys remain associated. Caveats to check:
+
+- Issue assignees outside the destination organization are cleared.
+- Destination organization permissions and policies apply.
+- Repository/Git URLs redirect; GitHub Pages URLs do not.
+- Reusing the old repository path removes its redirects.
+- Private repositories moving to a Free account can lose plan-dependent features;
+ Kiln is currently public.
+
+Source: [GitHub repository transfer documentation](https://docs.github.com/en/repositories/creating-and-managing-repositories/transferring-a-repository).
+
+The read-only GitHub API check found repository ID `1278326592`, public and not a
+fork, with **233 stars, 18 forks, two subscribers, three open PRs (#140, #141, #142)
+and one open issue (#134)**. The PRs have no assignees; issue #134 is assigned to
+`matthew-kissinger`. GitHub Pages is not enabled. The destination organization lists
+only `matter-field`, so no `kiln` name conflict was observed. These are planning
+observations, not the final transfer baseline; refresh them immediately before the
+move and verify organization membership for any issue assignees.
+
+### Transfer acceptance
+
+The transfer work item must inventory and verify: required checks/rules, Actions
+permissions, deployment integration installations, source URLs, badges, local remotes,
+release links, Pages/custom-domain behavior, npm provenance bindings and plugin
+repository references. Do not recreate a repository at the old path and break the
+redirect. If the transfer is deferred, proceed with npm publication from the current
+repository; it is not a package blocker.
+
+Use GitHub's native repository transfer for the existing repository. Before the move,
+record its immutable repository ID, star/watch/fork counts, release/tag inventory,
+and a paginated inventory of open issues and PRs, including numbers, titles, authors,
+states, assignees and PR branch references. Identify affected issue assignments before
+the move and surface any owner decision needed to preserve them; do not silently
+invite collaborators or change membership. After the move, verify the same repository ID,
+preserved history/releases, every open issue/PR and its discussion, repository URL
+redirects, and the personal profile pin. Compare community counts and reconcile any
+concurrent activity; unexplained loss blocks transfer closeout. Do not close, merge,
+recreate or triage outside PRs as part of this work. If transfer prerequisites cannot
+preserve the existing repository, surface that before proceeding. A copied/new repo
+does not satisfy this condition.
+
+### Transfer executed on 6 October 2026
+
+The owner explicitly requested immediate transfer and npm setup. GitHub's native
+transfer API moved the existing repository to `instruktlabs/kiln`. Repository ID
+`1278326592` and node ID `R_kgDOTDG3QA` are unchanged. The complete comparison retained
+233 stargazer identities, two watchers, 18 fork identities, all 144 issue/PR records
+(143 PRs, including the three open contributions), eight issue comments, open-PR
+reviews, five releases/assets and tags, the main SHA, protected checks, collaborator
+access, environment configuration and the personal pinned repository. Issue #134's
+assignment remains intact. No contributor work was closed, merged or rewritten.
+
+The old repository, issue #134, PR #140 and v0.10.0 release URLs redirect to the new
+owner; Git access through the old URL still resolves the same refs. The local
+`origin` now points to `https://github.com/instruktlabs/kiln.git`. The destination
+was shown in the browser. Initial stargazer/watcher API propagation returned 404;
+the subsequent complete snapshot succeeded with no errors and exact identity matches.
+
+Evidence is stored outside the distributable engine checkout at
+`C:/Users/Mattm/X/kiln-dogfood/publisher-setup-2026-10-06/`: `before.json`, `after.json`
+and `comparison.json`. Repository content references and plugin publishing bindings
+remain part of the implementation cycle; old URLs currently redirect.
+
+One organization-policy difference was resolved with explicit owner approval: Instrukt Labs
+requires full SHA pins and allows only GitHub-owned Actions. Existing Kiln workflows
+also use `oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6`. A proposed
+allowlist payload now permits only that existing version, retaining SHA enforcement
+and other restrictions. The owner approved the organization-wide entry; the effective
+repository policy was verified. The existing Linux CI job rerun passed under the new
+ownership; its result is recorded in the setup receipt.
+
+Use npm teams and protected release access for maintainers. Keep MIT licensing and
+existing contributor attribution. Organization ownership is not permission to
+retroactively reassign contributors' copyright. Add a short maintenance policy and a
+security reporting route, without introducing a CLA or governance bureaucracy as a
+release prerequisite.
+
+## 3. Repository readiness: what exists and what blocks publication
+
+The repository already has substantial release infrastructure. This is principally a
+distribution and hosted-product cycle, not an engine rewrite.
+
+| Surface | Current evidence | Required v1 disposition |
+| --- | --- | --- |
+| Release baseline | GitHub `v0.10.0` has a built tarball, checksums and platform receipts | Publish npm separately; incorporate main-only breaking changes into v1 migration notes |
+| Current CI | [Run 37409744200](https://github.com/matthew-kissinger/kiln/actions/runs/37409744200) passed on the audited SHA | Rerun against the exact renamed/versioned candidate |
+| Package identity | `@kiln/engine`, `private: true`, version `0.10.0` | Adopt owned name, public metadata/access and unique RC/final versions |
+| CLI and MCP | Compiled Node bundles; lazy MCP engine loading; portable package tests | Preserve these strengths; add an explicit `kiln-mcp` executable |
+| SDK | 55 export entries all target TypeScript; root export is `src/cli.ts` | Define the supported SDK and emit runnable ESM plus declarations |
+| Tarball | Dry run: 829 files, 9,362,192 bytes compressed, 26,535,869 unpacked | Reduce historical documentation and verify the shipped allowlist |
+| Docs payload | 440 files, 8,102,226 bytes under `docs/` | Ship consumer documentation and skill references; keep historical records on GitHub |
+| Plugin setup | Claude, Codex and root manifests exist | Generate current host-specific packages from maintained skills and shared tool definitions |
+| OpenAI ZIP | Packaging script emits `apps: './.app.json'` and a private connector binding | Replace for public submission; current public rules reject this format |
+| ChatGPT UI/download | Interactive card previously worked; native GLB/ZIP attachments explicitly unverified | Prove actual HTTPS downloads and target-host behavior |
+| Hosting | Local stdio, tunnel documentation and isolated evaluator building blocks | Implement public HTTP host, auth, tenancy, persistence and operational limits |
+| Rendering | CPU fallback and installed software Vulkan CI probe | Qualify software rendering as an explicit production mode |
+| Notices/support | MIT, contributing guide and dependency notices exist; notices reflect older dependency pins | Refresh exact artifact inventory and add security/support/privacy material |
+
+Audit checks performed:
+
+- `npm pack --dry-run --json --ignore-scripts`: inspected package contents; did not publish.
+- `node scripts/test-plugin-package.mjs`: passed the current packaging contract.
+- `node scripts/check-skills.mjs`: passed for six skills and the two registered setup copies.
+- `claude plugin validate . --strict`: passed the marketplace check.
+- `claude plugin validate .claude-plugin/plugin.json --strict`: failed on the warning
+ that root `CLAUDE.md` is not loaded as plugin context. A passing marketplace check
+ does not establish plugin readiness.
+- Plain Node 24 import of `@kiln/engine/discovery` failed with `ERR_MODULE_NOT_FOUND`
+ on the extensionless `src/discovery/catalog` import. Current documentation requires
+ a TS-aware loader/bundler; ordinary Node SDK support is not established.
+- Inspected the completed CI platform jobs, including installed software Vulkan.
+ The full local test suite was not rerun for this research-only document.
+
+The current shell has Node 24.20.0/npm 11.19.0; repository maintainer pins are Node
+22.23.3/npm 12.2.0/Bun 1.4.2. Release gates must use the pins. Consumer support is a
+separate decision: Node 20 is now EOL, while 22 and 24 are LTS in the
+[current Node schedule](https://nodejs.org/en/about/previous-releases). Recommend
+supporting maintained 22/24 lines for v1, with the tested minimum declared in
+`src/runtime-support.mjs` and `engines.node`. Do not impose Bun or the publishing npm
+version on consumers.
+
+## 4. npm and SDK work
+
+### Package contract
+
+Keep a single `@instruktlabs/kiln` engine package for v1. Classify every current export
+as stable, explicitly experimental, or internal before freezing semver. Start the
+stable contract from documented consumer use: authoring primitives/helpers, rendering,
+validation, discovery and the APIs needed by CLI/MCP hosts. Do not promise all 55
+subpaths indefinitely without reviewing their dependencies and callers.
+
+Emit compiled ESM with valid relative extensions and `.d.ts` declarations. Give root
+imports a deliberate library entry without CLI execution. Preserve documented source
+workflows through an explicit migration path. Separate Node-only entrypoints from
+portable ones and qualify any browser claims. In particular, avoid pulling
+`src/views/renderer-id.ts` and its module-load filesystem access into portable imports.
+CommonJS support is not required without an actual consumer need.
+
+#### SDK decision evidence, checked 6 October
+
+The 55 current export entries in [package.json](../../package.json) point to
+TypeScript source, with the root pointing at the CLI. The maintained
+[architecture reference](../architecture.md) documents tools, the optional agent,
+discovery, requirements, rendering/views, geometry, immutable stores, caches,
+contracts, composition, QA and arena APIs. This is an existing consumer surface;
+optional agent/arena/composition modules are not automatically experimental.
+
+The architecture reference explicitly labels `/implicit` experimental, and the
+Discovery catalog already carries stable/experimental/deprecated metadata for
+individual helpers and recipes. Recommend preserving established documented
+features, carrying existing experimental labels and limitations into the package,
+and reviewing all exported contracts before freezing v1. Do not relabel established
+APIs merely to avoid supporting them. If that review exposes a consequential removal
+or behavior change, present the specific callers and migration before adopting it.
+On 6 October the owner accepted the specific experimental-feature policy after
+reviewing the inventory and actual MCP exposure below: retain existing functionality,
+make labels/limitations visible, document stable APIs separately, preserve explicit
+exporter selection, and review availability/default changes individually. State the
+stability promise in consumer documentation. Experimental labeling does not waive
+installation, export resolution, resource bounds or truthful fidelity checks.
+
+#### What is currently experimental and how users encounter it
+
+Follow-up inspection on 6 October used checkout
+`65ce2f815a70ca3bdf8ad4fa1f8bf52d5fd08581`. The current Discovery catalog contains
+137 entries: **one experimental operation and 16 experimental recipes**, alongside
+120 stable entries. These labels do not classify the whole engine or MCP server as
+experimental, and recipe labels do not downgrade the stable helpers they use.
+
+| Existing item | Meaning and limitations | Current exposure |
+| --- | --- | --- |
+| `implicitSurface` | Samples a mathematical field into mesh geometry; resolution-dependent, no UVs, no guarantee of CAD accuracy or thin-feature preservation; host execution limits still required | Exported from `/implicit` and re-exported by `/primitives`; present in normal authoring globals used by `kiln_render`; no separate experimental opt-in |
+| 16 construction/rig recipes | Teaching examples and modeling guidance with specific limitations, not complete anatomy, physics, contact, navigation or manufacturing solutions | Returned by the ordinary `kiln_discover` catalog/search/detail routes and the `/discovery` package entrypoint; recipes are not separate MCP tools |
+| Alternative Three.js `GLTFExporter` backend | Export conversion candidate with native dependency, texture-transform and downstream qualification limits | Included but explicitly selected by host `KILN_GLTF_EXPORTER=three` or library `gltfExporter: 'three'`; default remains the established exporter |
+
+The 16 recipe IDs are seven rig guides (`rig-biped-v1`, `rig-quadruped-v1`,
+`rig-avian-v1`, `rig-serpentine-v1`, `rig-multi-limb-v1`, `rig-wheeled-v1`,
+`rig-custom-v1`) and nine construction guides (`joined-frame-v1`,
+`editable-assembly-v1`, `surface-detail-v1`, `foliage-cutout-v1`,
+`directional-sweep-v1`, `structural-bays-v1`, `open-tiered-seating-v1`,
+`steerable-wheel-v1`, `branched-articulation-v1`). Prefix each with `recipe:` for
+exact Discovery lookup. For example, a rig recipe provides semantic joint guidance,
+not skinning or a gait solver; its label is about the recipe's scope/readiness.
+
+Confirmed model-facing routes:
+
+```text
+kiln_discover({ capabilities: true })
+kiln_discover({ ids: ["implicitSurface"] })
+kiln_discover({ ids: ["recipe:surface-detail-v1"] })
+```
+
+Capabilities report `geometry.implicitSurfaces: 'experimental'` and whether the
+experimental exporter is selected. Exact helper/recipe details include
+`stability: 'experimental'` and limitations. `implicitSurface` also stamps an
+`EXPERIMENTAL_IMPLICIT_SURFACE` geometry warning that enters export warnings;
+compact render replies may bound the warning list.
+
+**Exposure gap to fix during implementation:** the Discovery service retains
+`stability` in structured search results, but its compact search text omits that
+field. MCP's Discovery adapter sends the text representation, so an experimental
+recipe can appear in normal search without its experimental label until the agent
+fetches exact details. The helper's own summary says experimental; most recipe
+summaries do not. There is no general `includeExperimental` switch or stability
+filter in the current Discovery input schema. Adding a new input flag would require
+the normal schema/compatibility review, not an incidental packaging change.
+
+A read-only probe against the actual Node stdio MCP bundle confirmed 17 tools with
+no separate experimental tool; capabilities and exact details show the labels, while
+`query: 'surface detail', kind: 'recipe'` did not show the label. The response had
+text content and no `structuredContent`. The MCP/engine build identity matched the
+current source identity (`sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295`).
+Receipt: `C:/Users/Mattm/X/kiln-dogfood/experimental-mcp-probe-2026-10-06/discovery-receipt.json`.
+This probe did not render an asset, invoke models or change runtime code.
+
+Release work should make existing stability labels visible in compact Discovery
+results, document the different meanings above, and preserve explicit exporter
+selection. Review any proposal to hide helpers, remove recipes or change defaults
+separately. An experimental label alone is not an execution restriction or a reason
+to remove a working feature.
+
+Evidence: [helper contract](../../src/discovery/helper-contracts.ts),
+[recipe catalog](../../src/discovery/recipes.ts),
+[Discovery presentation](../../src/discovery/service.ts),
+[MCP formatting](../../src/mcp-engine.ts),
+[capabilities](../../src/tools/discovery.ts),
+[implicit implementation](../../src/implicit.ts), and
+[exporter documentation](../community-exporter.md).
+
+Add `repository`, `homepage`, `bugs`, public publishing configuration and typed export
+metadata. Keep consumer installation free of engine-build and provider-login scripts.
+Do not assume optional native dependencies are present. A CPU install and an install
+with optional dependencies omitted must produce useful behavior and diagnostics.
+
+Rename all identity-sensitive boundaries, not just `package.json`:
+
+- `src/runtime-identity.ts` and `src/views/renderer-id.ts` check the old name.
+- Package smoke tests, software renderer CI and workspace discovery use old paths.
+- Skills, setup copies, generated workspace instructions, manifests and examples
+ must describe the same installation.
+- Existing workspaces must retain user edits and stored asset revisions during managed
+ upgrade. Recognize old local installations only where needed for explicit migration.
+
+Keep `kiln`, `kiln-init` and a new `kiln-mcp` executable in the package. The latter
+allows a thin local plugin to launch an exact npm release without calculating a
+`node_modules` path. An illustrative release launcher is:
+
+```text
+npx --yes --package @instruktlabs/[email protected] kiln-mcp
+```
+
+This is a proposed command, not available today. Validate argument handling and startup
+on Windows, macOS and Linux, including a cold npm cache and paths with spaces.
+
+### Artifact and publication discipline
+
+Allowlist consumer docs, skills and their referenced resources. Do not remove source
+needed by supported authoring workflows just to reduce a size number. Keep historical
+plans, reviews and model traces out of the installable/plugin context. Check licenses
+and notices against the exact resolved native/WASM dependencies; the existing notices
+predate current `webgpu`, `sharp`, `canvas` and `manifold` pins. Container images require
+their own dependency inventory because they also contain OS libraries.
+
+Build the candidate once, record its SHA-256 and test that tarball in clean consumers.
+Use GitHub-hosted OIDC trusted publishing with a protected release workflow and explicit
+public access. Avoid long-lived publish tokens. npm's
+[staged publishing](https://docs.npmjs.com/staged-publishing/) provides a useful final
+human review step; first-time staging also creates a public placeholder, so it is an
+external publication action, not a dry run. Bootstrap a new package deliberately, then
+configure the package's trusted publisher. The repository's npm 12.2.0 pin supports
+the current staged and trusted-publishing tooling.
+
+### Publisher account and credential setup, checked 6 October
+
+The owner needs an individual npm account with a verified email, then a separate
+`instruktlabs` npm organization administered by that account. Reuse an existing
+personal account if available. Select the free public-package organization plan;
+private-package billing is unnecessary for this release. GitHub organization
+ownership does not create the npm organization. The separate free npm organization
+was registered successfully on 6 October, with the owner verified in npm's member list.
+See [account creation](https://docs.npmjs.com/creating-a-new-npm-user-account/) and
+[organization creation](https://docs.npmjs.com/creating-an-organization/).
+
+Setup began on 6 October at the owner's request. No local npm session was present.
+The owner created personal account `matthew-kissinger` and confirmed email verification
+using the requested business alias, `[email protected]`. The agent then created
+the free `instruktlabs` organization and verified that account as its sole owner.
+Two registered security keys and write-action 2FA are verified, and organization
+enforcement is enabled. The owner-requested local recovery backup is encrypted with
+Windows DPAPI, verified, and its plaintext staging file removed. It is tied to this
+Windows account; local npm CLI login remains unconfigured until needed for publishing.
+The alias must reliably receive verification/recovery mail; npm's signup page notes
+that the publishing email may appear in package metadata. `instruktlabs` is now the
+registered organization rather than the personal account name. No package was published.
+
+Enable npm two-factor authentication, preferably with a passkey/security key, and
+save recovery codes in the owner's password manager. Require 2FA for organization
+members. Contributors use individual accounts and receive only necessary package
+access; do not share an organization password. See
+[npm 2FA setup](https://docs.npmjs.com/configuring-two-factor-authentication/) and
+[organization 2FA](https://docs.npmjs.com/requiring-two-factor-authentication-in-your-organization/).
+
+| Credential or identity | Planned location and use |
+| --- | --- |
+| npm account password/passkey and recovery codes | Owner's password manager/security device; entered through npm's normal account flow |
+| Local CLI login | `npm login` opens web authentication and manages credentials in the user configuration; this machine reports `C:\Users\Mattm\.npmrc`. Its contents were not read |
+| Routine release authorization | GitHub-hosted Actions obtains short-lived OIDC identity; no persistent `NPM_TOKEN` in GitHub or Cloudflare |
+| Hosted engine | Installs the public versioned package; needs no npm publishing credential |
+
+Keep credentials out of the repository, project `.npmrc`, `.env` files, package
+tarball and chat. The npm-managed user configuration is outside this checkout.
+See [npm login](https://docs.npmjs.com/cli/v12/commands/npm-login/).
+
+After the repository transfer and first-package bootstrap, bind npm trust to
+`instruktlabs/kiln`, the actual release workflow filename and a protected release
+environment. Proposed names are `release.yml` and `npm-release`; these are not
+configured yet. Use stage-only publishing permission with an owner 2FA approval,
+and disable token publishing after the trusted route is verified. This is the
+recommended release design, not an account change already performed. See
+[trusted publishers](https://docs.npmjs.com/trusted-publishers/).
+
+For the first package, an authenticated staging operation establishes a public
+`0.0.0-stage` placeholder. It is therefore an authorized external step, not a
+namespace-availability check. Configure OIDC once package settings exist, then stage
+the qualified release through that workflow and verify provenance. Inspect/download
+the staged archive before approving publication with 2FA. Do not assume a manually
+staged bootstrap has workflow provenance. See
+[staged publishing](https://docs.npmjs.com/staged-publishing/).
+
+npm hosts the release archive and downloads; Cloudflare runs the optional hosted
+service. After release, SDK consumers install `@instruktlabs/kiln`, while local
+CLI/MCP execution runs on their own machine. Account setup can happen before engine
+implementation; publication still requires the package gates below. The current
+`private: true` package is deliberately not publishable yet. No account, organization,
+credential or package was created during the initial research-only stage. The owner
+subsequently authorized account/org onboarding; its actual status is recorded above.
+
+### Agent execution and owner handoffs
+
+The owner wants the agent to handle publisher setup and release work as far as the
+available tools and authenticated sessions allow. Account onboarding belongs in the
+implementation goal; do not leave it as an unexplained prerequisite for the owner.
+
+| Work | Agent responsibility | Owner participation |
+| --- | --- | --- |
+| Personal npm account | Check whether an existing account can be reused; prepare/open the signup or login flow and resume setup afterward | Supply the account identity, enter private login details, complete email verification or any CAPTCHA |
+| 2FA and recovery | Navigate to setup, explain the choices and verify enabled status without collecting secrets | Enroll the passkey/security key or other supported factor and store recovery codes privately |
+| npm organization and access | Create/configure `instruktlabs` through the available authenticated interface within the authorized setup scope; verify ownership and package access | Resolve unavailable names, missing legal/account information or authentication challenges if they arise |
+| Package and release automation | Fix package contents/exports, build and test the exact archive, prepare GitHub Actions, configure publishing trust and verify provenance | No routine technical work; respond only to consequential choices or account reauthentication |
+| First package and public release | Prepare the reviewed bootstrap, staged release and final registry verification; carry out authorized actions | Approve the concrete publication when needed and complete npm's human 2FA approval |
+| Hosting and directory accounts | Prepare Cloudflare configuration and submission materials, and operate through connected accounts | Complete required identity, billing, terms or authentication steps when the service requires the account holder |
+
+Never ask the owner to paste passwords, one-time codes, recovery codes or tokens into
+chat. Pause at a protected account step and let the owner complete it in the service's
+own interface, then resume. If a setup page is inaccessible to automation, provide
+the exact minimal manual steps rather than promising full unattended completion.
+Existing authorization persists; do not ask again merely because a new implementation
+step begins. Prepare release candidates before seeking any missing final approval,
+as required by this repository's publication rule in `AGENTS.md`.
+
+Use `1.0.0-rc.N` on a prerelease tag, then build and separately qualify `1.0.0` because
+the version is part of runtime identity. Publish the exact final tested bytes. Verify
+registry integrity, provenance, tags, fresh install, CLI/MCP flow and release checksums.
+Use a new patch/deprecation for recovery; do not plan to overwrite a published version.
+
+## 5. Plugin distribution and public submission
+
+### OpenAI: one public plugin for ChatGPT and Codex
+
+Current OpenAI documentation describes a shared plugin architecture and directory.
+Prefer the portable root `plugin.json` schema with OpenAI-specific metadata in
+`extensions.com.openai`, plus maintained skills and MCP configuration. Local Codex
+distribution can remain a separate variant. See
+[packaging](https://developers.openai.com/plugins/build/plugins).
+
+For public submission, use a stable HTTPS Streamable HTTP MCP endpoint. A private
+Secure MCP Tunnel does not meet the public endpoint requirement; local-only support
+requires discussion with OpenAI. See
+[endpoint deployment](https://developers.openai.com/plugins/build/mcp-server#deploy-the-endpoint).
+
+Keep three independent properties explicit in implementation and public copy:
+
+| Property | Private Sites trial | Intended public OpenAI service |
+| --- | --- | --- |
+| Network reachability | Internet-addressable HTTPS with access controls | Stable public HTTPS MCP endpoint |
+| Authorization | Owner-only access; managed MCP connection still unverified | Authenticated users, private per-user assets and authorized downloads |
+| Plugin distribution | Owner's private plugin | Public directory candidate, then public listing only after approval and publication |
+
+A public MCP endpoint does not imply anonymous tool execution or public user data.
+The engine evaluator and rendering services can remain behind the public MCP host.
+Sites publication, successful OAuth connection, working tool calls and directory
+eligibility are separate evidence. Do not call the Sites trial a qualified public
+hosting solution until the missing evidence is obtained.
+
+Prepare a new public ZIP rather than reusing the current private-connector bundle.
+The current [submission flow](https://developers.openai.com/plugins/deploy/submission)
+requires a verified publisher with submission permission, domain verification, and
+the MCP server in the initial submission. It supports one connected MCP server per
+plugin. `apps`/`.app.json` and lifecycle hooks are not accepted in that ZIP. Prepare
+five positive and three negative cases, a demo video, release notes and reviewer
+access that works immediately. Review approval and the subsequent publish action are
+separate steps.
+
+Audit the hosted tool surface against the
+[plugin guidelines](https://developers.openai.com/plugins/plugin-guidelines): explicit
+read-only/destructive/open-world annotations, minimal data, and visible model-callable
+operations. Kiln's mixed `action` tools and opaque payloads deserve specific review.
+Do not duplicate definitions in a hosted adapter. If operation-specific hosted tools
+are required, derive their schemas/dispatch from the registry and keep a versioned
+mapping with parity tests. The local 17-tool contract and its schema/cache budgets
+remain stable unless a deliberate versioned change is adopted. Geometry catalog
+discovery is useful functionality; it is not permission to hide executable operations.
+
+Implement [OAuth 2.1 and resource authorization](https://developers.openai.com/plugins/build/auth)
+for private user artifacts, with audience validation and the required metadata.
+Publish accurate privacy, support and retention information under the publisher's
+controlled domain. Demonstrate creation, revision, preview and downloaded artifact
+identity on the real ChatGPT and Codex surfaces. Native chat attachments remain
+unclaimed until tested; signed HTTPS file delivery is the baseline.
+
+### Anthropic: directory submission and marketplace distribution
+
+Build a small Claude plugin directory with maintained skills, valid metadata and an
+exact-version local MCP launcher. Make it available through an Instrukt Labs-owned
+marketplace so installation does not depend on directory approval.
+
+The current [Claude Code publishing documentation](https://code.claude.com/docs/en/plugins/publish)
+routes public directory submissions through
+[claude.ai/directory/manage](https://claude.ai/directory/manage), using a paid Claude
+account and a GitHub source. Directory installs reach Claude Code through account
+sync. The curated **`claude-plugins-official` marketplace does not accept submissions
+through that portal**; an official-marketplace listing is a separate partner route.
+Do not promise it as the outcome of an ordinary directory submission.
+
+The [submission workflow](https://claude.com/docs/plugins/submit) supports a repository
+subdirectory. Choose the final source location before submitting; source/path cannot
+simply be changed afterward. The repository must be public before the listing goes
+live. This is another reason to resolve an optional GitHub transfer early.
+
+The [pre-submission checklist](https://claude.com/docs/plugins/pre-submission-checklist)
+requires exact package pins rather than `@latest`. Large trees, binary files and
+registry launchers can require reviewer inspection. In particular, trees over 512
+files or non-image files over 256 KiB can be held for review. These are review holds,
+not a blanket ban. Avoid submitting the full engine repository as the plugin folder.
+
+Claude's [dependency loading rules](https://code.claude.com/docs/en/plugins/loading#nodejs-package-dependencies)
+also matter: supported lockfiles and `--ignore-scripts` installs are used, Bun locks
+need Bun, and npm `overrides` can cause the dependency install step to be skipped.
+The current root package is not automatically a turnkey plugin installation. Start
+with an inspectable pinned launcher and disclose its first-use download; prove it
+in clean cached installs. A dedicated npm-lockfile wrapper is an alternative if
+cold-start or review evidence favors it.
+
+Local MCP works in Claude Code but is not a remote chat backend. Keep the supported
+surfaces explicit using the [platform support table](https://claude.com/docs/plugins/platform-support).
+Claude chat/remote connector submission can reuse the hosted service later, but is
+not an extra mandatory launch channel for this Claude Code request.
+
+### One workspace contract
+
+Resolve the current mismatch between plugin MCP name `kiln` and generated authoring
+workspace name `kiln_workspace`. Select one active local authoring server and prove
+that installing a plugin beside an existing workspace does not expose duplicate
+servers or change tool choice. Never store authored assets in a disposable plugin
+cache or expose engine examples as authoring context. Keep workspace paths, revisions
+and custom instructions through plugin updates. Hooks are unnecessary for v1.
+
+Use a stable plugin slug such as `kiln-engine`, display name **Kiln Engine**, publisher
+**Instrukt Labs**. Confirm directory-name uniqueness during preflight. An integration
+published by the project is first-party Kiln software; a directory listing does not
+mean OpenAI or Anthropic maintains or endorses the engine.
+
+## 6. Rendering and hosting decision
+
+### Three different render paths
+
+| Path | What it establishes | v1 role |
+| --- | --- | --- |
+| Existing CPU rasterizer | Deterministic geometry feedback; not truthful textured/PBR material evidence | Default universal fallback and offline QA workflow |
+| Three WebGPU through Dawn plus Mesa software Vulkan | Material-aware rendering without physical GPU hardware | First hosted PBR candidate, pending production qualification |
+| Actual local/hosted GPU | Hardware-accelerated material views | Preserve local support; rent only if measured demand justifies it |
+
+Software rendering is not a new research project from zero. CI already installs Mesa,
+selects a software Vulkan ICD and renders textured/metallic test content through the
+installed package. `scripts/smoke-renderer.mjs` explicitly passes `allowSoftware: true`.
+Production `render-service/src/gpu.mjs` currently rejects software adapters by default.
+The green CI probe proves functionality, not hosted latency, visual equivalence or
+production acceptance.
+
+Add an explicit host render mode and truthful backend/fidelity identity. Preserve the
+hardware-default guard. Include backend/build/dependency/capture identity in cache
+compatibility. Benchmark existing CPU, software Vulkan and one qualified hardware
+reference using the same retained inputs: matte geometry, textures, metalness, alpha,
+animation and a bounded complex assembly. Measure cold/warm latency, p50/p95, peak RSS,
+timeouts, concurrency and CPU-seconds per complete authoring workflow, not only a tiny
+single-frame fixture.
+
+Keep `captureViewsViaPort` as the sole deadline/fallback owner, propagate cancellation,
+and preserve the short in-loop versus longer final-sheet deadlines. Slow software
+PBR may be suitable for final review even when CPU fallback is needed in-loop. Never
+label a CPU geometry image as material evidence or feed pixels into image-free QA.
+Browser GLB display can use the visitor's GPU, but does not itself produce the
+server-side images the authoring agent needs.
+
+### Hosting comparison
+
+| Option | Fit for Kiln | Decision |
+| --- | --- | --- |
+| Existing static site/CDN and R2 | Documentation, gallery and downloadable files; visitor-side GLB display | Retain; hosting a website does not host engine execution |
+| ChatGPT Sites | Hosted frontend, storage, identity and a private MCP integration | Continue a bounded optional probe for concrete integration/hosting value; full-engine suitability remains unqualified |
+| Cloudflare Workers only | Auth, request routing, quotas and metadata | Existing Node/native/subprocess runtime cannot be deployed unchanged |
+| Cloudflare Workers + Containers + R2 | Public MCP edge plus portable Linux evaluation/render compute | Owner-selected production stack; runtime qualification remains open |
+| Google Cloud Run | Potential alternative Linux container host | Exception only if evidence shows a material advantage or Cloudflare cannot meet a required capability; not a parallel default workstream |
+| Small Linux VM | Predictable server control and easier OS-level isolation configuration | Fallback if managed containers cannot satisfy evaluator requirements; owner operates patching/backups |
+| Hosted physical GPU | Useful if qualified software rendering is too slow | Defer until measurements show it is necessary |
+
+### Owner-selected provider direction
+
+On 6 October the owner selected **an all-Cloudflare stack**, with Sites exploration allowed
+when it can add useful capabilities. Do not treat Cloud Run as an equally preferred
+destination or automatically spend the cycle comparing providers. Start production
+qualification on Cloudflare and build on the existing operational footprint.
+
+A proposal to use Cloud Run or another provider must identify a concrete reason:
+
+- A required native dependency, isolation boundary, software-rendering route or
+ workload cannot run acceptably on Cloudflare after a bounded investigation.
+- Measured total operating cost rises beyond the initial target at the required
+ usage, and an alternative has a defensible cost or operational advantage.
+- Matched tests show a material advantage in cold/warm latency, throughput, queueing
+ under load or memory efficiency that matters to the intended user flow.
+
+Compare the same qualified engine, asset fixtures, rendering fidelity and resource
+limits. Include startup/idle cost, storage, network and operational burden in a cost
+proposal. A headline free tier or an unmeasured performance claim does not justify
+switching. Surface the evidence and recommendation before changing this direction.
+
+Keep the Sites probe bounded to the unresolved managed MCP connection, distribution
+eligibility and any concrete convenience it can provide alongside the engine host.
+Only expand it if results support a useful role; it does not block Cloudflare or
+package work. Neither provider preference nor the operating target establishes that
+an actual production deployment has passed qualification.
+
+Sites is in public beta with plan-specific usage limits, not a published unlimited
+hosting commitment. Its supported web runtime and storage are documented in
+[Sites](https://learn.chatgpt.com/docs/sites). The installed Sites capability supports
+Worker-based server code, D1/R2 and platform-managed MCP authentication/private plugin
+creation. That does not establish public-directory approval or arbitrary Node/GPU
+execution. This repo requires native dependencies, subprocesses and isolated source
+evaluation. Even without GPU rendering, a Worker alone is not a drop-in host:
+[`node:child_process` is a compatibility stub](https://developers.cloudflare.com/workers/runtime-apis/nodejs/).
+Use Sites only if its convenience justifies an additional frontend while the engine
+runs elsewhere. Do not tie the cross-vendor production service to private Sites
+identity headers without an explicit adapter and verified authorization boundary.
+
+The more specific, newly updated
+[Sites plugin-hosting article](https://help.openai.com/en/articles/20001547-hosting-a-plugin-with-chatgpt-sites)
+confirms MCP hosting and describes availability across plans, subject to rollout and
+workspace permissions. It also states that personal/Pro users cannot currently share
+their Site-hosted plugin directly with other users; Business/Enterprise sharing is
+within the workspace and requires access to both the Site and plugin. A public Site
+does not make its plugin public. The general Sites page and this newer feature page
+describe availability differently, so verify entitlement in the target account.
+Neither establishes that a Sites-managed private plugin can be promoted into a public
+directory listing. This is a distribution uncertainty separate from compute support.
+
+Cloudflare's current [Sandboxes](https://developers.cloudflare.com/sandbox/) offering
+adds a relevant deployment option: Linux container microVMs for untrusted execution,
+with network admission controlled outside the sandbox. Its
+[security model](https://developers.cloudflare.com/sandbox/concepts/security/)
+requires one trust boundary per sandbox; processes inside the same sandbox share
+access. Use per-user or per-job instances, or a separately qualified inner isolation
+boundary. Keep credentials and other tenants' artifacts outside. The container
+scheduling policy remains beta. Dynamic Workers are another sandbox type but do not
+remove this engine's native dependency requirements.
+
+Cloud Run also now offers [sandbox execution in preview](https://docs.cloud.google.com/run/docs/configuring/services/sandboxes).
+It shares the parent instance's CPU/memory and has a provider-specific launcher.
+Evaluate it as an alternative isolation implementation, not proof that Kiln's existing
+`bwrap` readiness probes work there unchanged. Prefer a portable image and explicit
+host adapter over embedding either provider in deterministic engine paths.
+
+### Probes completed during this research
+
+Disposable source and receipts are in
+`C:/Users/Mattm/X/kiln-dogfood/v1-hosting-probe-2026-10-05/`, outside the engine repo.
+
+| Probe | Result | What it establishes |
+| --- | --- | --- |
+| Sites account API | `list_sites` succeeded; zero owned Sites before the trial | Control API reachable; not a numerical quota/billing entitlement check |
+| Current local Workers runtime | Wrangler 4.147.0, compatibility date 2026-10-05, loopback only | Tests use the current available runtime, not the older globally installed binary |
+| HTTP MCP and real Kiln discovery | Six assertions passed: health, runtime probe, initialize, tool discovery, real catalog query, unknown-method error | Portable discovery can run in a Worker with an HTTP MCP facade |
+| Node subprocess | `ERR_METHOD_NOT_IMPLEMENTED` for `child_process.spawnSync` | Existing subprocess evaluator cannot execute in this Worker runtime |
+| WebGPU API | `navigator.gpu` absent | No WebGPU route exposed by this tested local runtime |
+| Full MCP-engine Worker dry-run build | Failed resolving the native Skia `.node` dependency | Current engine bundle is not directly Worker-deployable; this was a local build, not an upload |
+| Linux software rendering | Downloaded and inspected the audited CI run's receipt and PNGs; Mesa llvmpipe, software=true, passed | Existing material-aware CPU implementation produces textured images |
+| Local Linux container execution | Docker CLI exists but Linux daemon is not running | No local Docker/provider isolation result was obtained |
+| Private Sites deployment | Succeeded with `has_mcp: true`; automatically provisioned the named private plugin | Actual MCP-capable Sites hosting and plugin provisioning are available to this account |
+| Sites access boundary | Anonymous `/health`: 401; private service-authorized `/health`: 200 with exact probe identity | Owner-private deployment access verified |
+| Sites MCP authorization | `/mcp`: 401 with OAuth protected-resource metadata challenge; service token did not grant MCP access | Managed MCP OAuth is a distinct authorization boundary |
+| Managed plugin installation | Private plugin appeared under Created by you; browser detail page failed with `cloudflare_challenge` | No successful user OAuth connection or model tool call claimed |
+
+The software-renderer fixture produced three two-view 128px captures. Recorded total
+times were 1208.7 ms, 379.9 ms and 64.7 ms in execution order. Initialization is outside
+these measurements; different backdrops, warmup and shader caching make them unsuitable
+for throughput extrapolation. They are functional evidence only. The initial globally
+installed Wrangler 4.84.1 rejected the October compatibility date; a pinned 4.147.0 was
+used without changing the global installation.
+
+After owner approval, a separate dependency-free, read-only probe with four genuine
+catalog contracts was published at
+[Kiln private MCP hosting probe](https://kiln-private-mcp-probe-oct2026.mkvision.chatgpt.site).
+It executes no source, renders no images, uses no storage and contains no credentials
+or user assets. Local handler checks passed. The source commit is
+`a9db829cc89342cd68b1e2a4b62fa4dd6d57d0c0`; archive SHA-256 is
+`78bfa145ba40dc5ada9c32fc272997ca1d84ee0deeb202ca479ca045f86abcb8`.
+The deployment is owner-only, with one allowed user and no workspace groups.
+
+The platform returned a private plugin ID after provisioning completed. Its install
+page was reached through the normal Plugins > Personal flow; the browser then reported
+`Failed to load plugin cloudflare_challenge`. Installation and user OAuth were not
+confirmed. The native installation suggestion remains available to the owner. Do not
+route around the MCP OAuth requirement using service access or broaden Site sharing.
+The full model-to-tool connection, account quotas, realistic cold starts and public
+directory eligibility remain unverified. No paid Cloudflare or Google deployment was
+performed. The private Site remains deployed for continued testing.
+
+Sites packaging on this Windows host needed two process-local adjustments: select
+the installed Git Bash instead of the unavailable WSL Bash, and set GNU tar's
+`TAR_OPTIONS=--force-local` so `C:/...` is not interpreted as a remote archive path.
+The standard source helper then pushed and packaged successfully; no global shell
+configuration or plugin source was changed. Receipts contain identifiers and status,
+not source-write credentials or service-access tokens.
+
+### Hosting economics and implementation, updated 6 October
+
+The owner clarified that $20/month is a starting target, not a hard cap; growth
+beyond it is acceptable when justified. Avoid sustained hundreds of dollars without
+revenue, sponsorship or an explicit funding decision. See the accompanying
+[hosting economics and implementation report](2026-10-06-hosting-economics.md) for
+current prices, the exact calculation, scenarios, alternatives and qualification.
+
+The owner-selected stack is **entirely Cloudflare**: Workers for HTTPS MCP/OAuth and
+the static viewer, D1 for metadata, R2 for source/GLBs/previews, and Durable Objects
+coordinating Linux Containers for native evaluation and CPU/software rendering.
+Workers alone and Sites alone cannot host the current native engine. Software
+Vulkan does not require a hardware GPU, but the actual Container's dependencies,
+isolation, renderer output, memory and latency still require qualification. Preserve
+the host-injected renderer boundary and keep the portable engine provider-neutral.
+
+With the report's explicit assumptions, 1,000 occasional monthly authors cost about
+$17/month; 1,000 frequent authors cost about $257/month. At the occasional workload,
+increasing aggregate startup/idle time from one to fifteen minutes per authoring
+session raises the model to about $82/month. These are usage scenarios, not measured
+Kiln capacity or guaranteed bills. Do not equate connected users with running machines.
+
+The owner's existing ChatGPT Pro subscription is relevant to incremental Sites cost,
+but no numerical Pro hosting allowance or overage price schedule was verified. The
+live probe's settings expose Add custom domain; `kiln.instruktlabs.com` is a supported
+domain shape, subject to DNS/TLS and MCP OAuth qualification. No domain was attached.
+Sites would still need external Linux compute, so a hybrid does not eliminate the
+major cost. Public plugin distribution remains a separate open qualification.
+
+The official `cf` CLI is the preferred tool to evaluate for the new hosting project.
+Pinned `[email protected]` passed local Windows version and offline command-search
+checks. It is beta; retain Wrangler for current scripts/gaps and review any migration
+with dry-run, especially Containers and DO migrations. No global install, login or
+deployment was performed. Details and current official sources are in the report.
+
+Prepare optional GitHub Sponsors and Cloudflare credit-program proposals alongside
+implementation. Do not count unawarded credits or promised donations as funding.
+Before sustained higher spending, compare a fixed-price Linux compute host using
+matched measurements; keep the domain, MCP identity and storage portable.
+
+Cloud Run request-based billing includes 180,000 vCPU-seconds, 360,000 GiB-seconds and
+two million requests monthly in the documented free tier. Sparse compatible workloads
+may cost less there, excluding storage, builds, networking and other services. See
+[Cloud Run pricing](https://cloud.google.com/run/pricing). Choose from actual RSS,
+startup and isolation results; neither provider has been deployment-tested in this
+audit. A budget alert is not a hard cap. Enforce application admission limits, bounded
+concurrency, per-user quotas and an operator expensive-work cutoff. Set operating
+thresholds from measured costs and owner funding preferences, not an assumed $20 cap.
+
+### Minimal hosted architecture
+
+```mermaid
+flowchart LR
+ A[ChatGPT and Codex public plugin] --> B[HTTPS MCP and OAuth]
+ B --> C[Admission and user-scoped artifact service]
+ C --> D[Isolated Linux engine evaluator]
+ D --> E[CPU geometry views]
+ D --> F[Optional software Vulkan material views]
+ C --> G[Private object storage and metadata]
+ G --> H[Authorized preview and download links]
+ I[Claude Code and local Codex plugin] --> J[Exact npm engine in user workspace]
+```
+
+Start with one region, one qualified Linux image, bounded parallel jobs and durable
+object storage. Keep authentication, tenant authorization and storage outside the
+untrusted source evaluator. Every read, revision reference, render cache lookup and
+download must respect user ownership. Never assume an opaque `programRef` is an
+authorization credential. Preserve source, engine identity and exact revision bytes.
+
+The existing `src/evaluator/isolation.ts` readiness probes are a useful launch gate:
+namespace separation, no new privileges, empty capabilities, restricted filesystem,
+sanitized environment and denied network/metadata access. Run them on the actual
+provider. A process timeout, Node permission setting or generic container alone does
+not prove these invariants. If a provider cannot run the isolation boundary, change
+the host or adopt a separately reviewed isolation design; do not weaken it to pass.
+
+Validate uploads before parsing, restrict external fetches, bound native memory and
+CPU in addition to the JS heap, kill timed-out work, and exclude provider credentials
+from evaluator processes. Add artifact retention/deletion, token-free logs, minimal
+operational telemetry and a rollback path. For jobs exceeding host deadlines, use
+explicit job/status operations or a bounded failure; do not return success before a
+reviewed artifact exists. The public service is a real user-data product, even if free.
+
+The owner-selected retention policy is: keep saved source files and GLBs until the
+user deletes them, within a storage quota; expire unsaved work after seven days.
+Define the expiry clock and communicate it in the interface and privacy information.
+Cleanup must preserve files referenced by saved revisions, including their required
+material resources. Download-link expiry is separate from artifact deletion. Choose
+per-user and total storage/admission limits from measured sizes and the initial
+$20/month target with an explicit growth policy; do not promise unlimited users.
+
+### Authentication architecture review, 6 October
+
+The owner selected **Google and GitHub for hosted v1; email sign-in can follow**.
+Access stays free within quotas. The package, local tools and local plugins need
+no Kiln account. Correct implementation, clear branding and end-user security are
+explicit launch requirements. This decision supersedes the earlier GitHub-only
+choice. The present implementation still supports GitHub alone; this section
+records the target architecture and remaining work, not deployed acceptance.
+
+#### Recommended boundaries
+
+Keep the existing MCP authorization server on Cloudflare, backed by the maintained
+`@cloudflare/workers-oauth-provider` library. Add provider adapters around one
+Kiln-owned account identity; do not use a Google or GitHub id as the storage owner.
+Use a maintained standards client such as `oauth4webapi` for Google OIDC validation,
+not hand-written JWT decoding or signature checks. Its documented runtime support
+includes Workers, it implements OAuth/OIDC validation, and it has no dependencies.
+Exact library adoption still requires a pinned installation and workerd proof.
+[Cloudflare authorization options](https://developers.cloudflare.com/agents/model-context-protocol/protocol/authorization/),
+[oauth4webapi](https://github.com/panva/oauth4webapi).
+
+```mermaid
+flowchart LR
+ U[User chooses Google or GitHub] --> I[Verified provider identity]
+ I --> A[Permanent Kiln account ID]
+ A --> C[Consent for a particular MCP client]
+ C --> O[Kiln OAuth token for kiln.instruktlabs.com/mcp]
+ O --> T[Account-owned assets and quotas]
+```
+
+The diagram separates roles, not browser ordering. Unregistered/dynamic clients
+must receive Kiln consent before an upstream provider redirect, as the existing
+library's browser-bound consent helpers require. A logged-in browser session is
+not an MCP access token. Google/GitHub tokens never authorize `/mcp`, never become
+asset ownership selectors and never enter native evaluation. The gateway issues
+its own resource-bound tokens. [MCP security requirements](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/security-considerations).
+
+Define a small provider-neutral account interface: resolve verified identity,
+start/finish explicit linking, revoke a connection, disable/delete account and
+check access state. Store accounts and unique `(issuer, subject)` identity bindings
+in a dedicated SQL authority. A small D1 database is the preferred initial fit
+for this shared identity index; tenant asset data stays in Durable Object SQLite
+and R2. This is a demonstrated shared-metadata need, not a second asset catalogue.
+Use transactional batches, unique constraints and primary-backed security reads;
+do not derive security guarantees from eventual KV reads or arbitrary read replicas.
+Prove concurrent registration/linking and rollback against the actual schema.
+[D1 database API](https://developers.cloudflare.com/d1/worker-api/d1-database/),
+[read consistency](https://developers.cloudflare.com/d1/best-practices/read-replication/).
+
+Generate one immutable Kiln account ID independent of email and provider. Explicitly
+linking another verified identity retains that ID and its assets/quotas. Bind link
+intent to a recent authenticated Kiln session and one-time server-side transaction;
+require control of the new provider too. Refuse linking an identity already owned
+by another account. Do not silently merge existing libraries. Do not let unlinking
+remove the last usable sign-in method. Revoke affected sessions/grants on sensitive
+account changes. Recovery in v1 uses a previously linked provider or that provider's
+own recovery; support cannot reassign assets merely because an email matches.
+
+Google identities use its validated immutable `sub` with canonical issuer. GitHub
+uses the immutable numeric user id from its authenticated API. Email is optional
+contact/display data, not an ownership key or automatic link signal. Start Google
+with `openid profile` unless a concrete product need requires verified email; do
+not request Gmail, Drive or Calendar. Keep GitHub's empty additional scope set.
+Provider-specific callback paths and server-bound provider/purpose state prevent
+cross-provider mix-up. Validate issuer, audience, expiry, nonce, PKCE, state and
+signatures through the selected client library.
+[Google OIDC](https://developers.google.com/identity/openid-connect/openid-connect),
+[GitHub scopes](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps).
+
+This is provider-agnostic and MCP-client-agnostic at the interfaces. Deployment
+still intentionally uses Cloudflare. Adding another provider must not change
+asset ownership, the npm SDK or the public MCP resource URL. Exportable identity
+bindings and SQL migrations preserve a future hosting/library migration path.
+
+#### Current standards and concrete checks
+
+Checked the MCP 2026-07-28 authorization profile, current OpenAI plugin auth docs,
+Claude Code docs, installed library documentation/source and public provider metadata.
+Registry checks report Cloudflare OAuth provider **1.2.1** (already installed,
+published 28 September), Better Auth **1.7.7**, oauth4webapi **3.8.8** and jose
+**6.2.12**. These are observations, not permission to float release dependencies.
+
+CIMD is preferred for current clients; retain bounded DCR only for compatibility.
+Keep RFC 9728 protected-resource discovery, RFC 8414 issuer discovery, S256 PKCE,
+resource/audience binding and RFC 9207 issuer identification. OpenAI supports CIMD
+public exchange (`none`) or signed exchange (`private_key_jwt`); current Cloudflare
+1.2.1 implements only the public option and negotiates it from the offered set.
+It must reject a signed-only client. Do not advertise or claim signed-client
+authentication. Claude Code also documents CIMD and preconfigured-client fallback.
+[OpenAI authentication](https://developers.openai.com/plugins/build/auth),
+[Claude Code MCP](https://code.claude.com/docs/en/mcp),
+[Cloudflare provider behavior](https://github.com/cloudflare/workers-oauth-provider/blob/main/docs/authorization-server.md).
+
+Read-only live metadata probes confirmed Google's issuer/endpoints and S256 support,
+and ChatGPT's current CIMD offer of both methods with a legacy signed preference.
+Two new workerd checks exercise that negotiation, missing PKCE rejection and
+signed-only refusal. All 19 focused authentication checks pass. This is a simulated
+client with real production gateway/library code, not a live OpenAI connection.
+`npm audit --omit=dev` reported zero known production dependency advisories; that
+does not establish the absence of design or deployment vulnerabilities.
+
+Keep upstream sign-in scopes separate from scopes exposed to MCP clients. The
+current gateway advertises `kiln:use` and `offline_access`, not OIDC user identity
+scopes. OpenAI's optional enterprise domain restrictions require issuer OIDC
+discovery and verified-email UserInfo; Kiln does not implement that feature today.
+Do not advertise `openid`/`email` downstream without actually implementing it.
+
+#### Alternatives considered
+
+| Option | Finding and v1 disposition |
+| --- | --- |
+| Cloudflare OAuth provider plus narrow identity adapters | Retain. Current supported MCP server library, own-domain consent and no separate identity SaaS subscription. Kiln still owns account lifecycle, SQL correctness, UI and deployed qualification; using a library does not remove those obligations. |
+| Better Auth on Cloudflare D1 | Viable broader application-auth framework. Supports social providers, sessions and explicit linking; disable implicit email linking if adopted. Its current user model requires email, including when a provider omits it. Avoid fabricated recovery addresses or silently expanding GitHub permissions solely to fit that model. Reconsider with the email/passkey milestone rather than replacing the working MCP issuer just for two sign-in buttons. |
+| Better Auth MCP/OAuth stack | Current docs use `@better-auth/mcp`, `@better-auth/cimd` and the OAuth provider/JWT machinery. It is a real alternative, not a deprecated path. Do not install a second MCP issuer alongside the Cloudflare issuer. A replacement needs full client, key rotation and storage qualification. |
+| WorkOS AuthKit | Managed sign-in reduces owned lifecycle work. Published user management allowance is up to one million MAU, but a hosted custom domain is listed at $99/month. That branded hosted option exceeds the initial hosting target and introduces another identity service; not the default. Custom UI has a different integration tradeoff. |
+| Cloudflare Access | Useful for operator/admin access. Standard Cloudflare One Access users consume seats; do not make a public community service depend on an assumed unlimited seat allowance. No Access plan change is required for the selected architecture. |
+
+Sources: [Better Auth account linking](https://better-auth.com/docs/concepts/users-accounts),
+[email requirement](https://better-auth.com/docs/concepts/oauth#handling-providers-without-email),
+[D1 support](https://better-auth.com/docs/concepts/database),
+[current MCP plugin](https://better-auth.com/docs/plugins/mcp),
+[WorkOS pricing](https://workos.com/pricing),
+[Cloudflare seat accounting](https://developers.cloudflare.com/cloudflare-one/team-and-resources/users/seat-management/).
+
+#### Remaining security and user-flow gates
+
+The current gateway follows the upstream library's consent/PKCE pattern, strips
+credentials before private dispatch and tests tenant separation. It lacks Google,
+an internal account registry, account settings/linking/deletion, production public
+endpoint quotas and the branded end-user flow. The current bare consent form is
+an implementation fixture, not the approved launch presentation.
+
+The provider documents a same-browser concurrent replay window because KV cannot
+atomically consume a consent/upstream handle. KV also propagates changes across
+locations asynchronously. Add an authoritative, transactional guard for one-time
+application login/link intents and strong account-disable/deletion checks on the
+protected path; qualify grant revocation and refresh behavior separately. A guard
+around login does not automatically fix every token-endpoint race. Do not claim
+instant global revocation from the local test. If the supported library integration
+cannot meet the required guarantees, compare a SQL-backed issuer before public
+launch; do not patch private library internals or weaken isolation checks.
+[Provider limitation](https://github.com/cloudflare/workers-oauth-provider/blob/main/docs/upstream-sign-in.md),
+[KV consistency](https://developers.cloudflare.com/kv/api/read-key-value-pairs/).
+
+Implement and qualify in this order:
+
+1. Freeze the provider-neutral account contract and identity uniqueness/deletion
+ rules; test primary SQL concurrency before changing tenant routing.
+2. Add Google through the maintained OIDC client, preserving GitHub behavior and
+ binding callback purpose/provider. Negative fixtures must cover issuer, audience,
+ signature, expiry, nonce, state, replay and provider-swap failures.
+3. Add explicit linking, connection revocation and account deletion with recent
+ reauthentication, atomic consumption and protection against deleting the last
+ login. Prove linked providers reach one unchanged library and quota.
+4. Finish a mobile-usable Kiln / Instrukt Labs sign-in and consent experience with
+ exact requesting-client identity, free-access explanation, privacy/support,
+ denial/retry states and account controls. Keep secrets out of pages and logs.
+5. Configure separate test/production provider clients with exact callbacks and
+ minimal scopes. Complete Google's brand verification for the displayed public
+ app name/logo. Surface owner login/verification steps when required.
+6. Run deployed two-user and two-provider flows in the actual target MCP clients,
+ including sign-out versus disconnect, account deletion, refresh/expiry, outage,
+ cross-region revocation and public-endpoint admission/cost tests. Capture separate
+ receipts; no model calls are needed for protocol qualification.
+
+[Google production branding](https://developers.google.com/identity/protocols/oauth2/production-readiness/brand-verification).
+Email is not a v1 requirement. Cloudflare Email Service currently offers outbound
+transactional sending in beta on Workers Paid, including sign-in links, so a future
+email route need not introduce another hosting vendor. Verify account access,
+deliverability, costs, abuse controls and recovery semantics before enabling it.
+[Cloudflare Email Service](https://developers.cloudflare.com/email-service/).
+
+No provider app, secret, SQL resource or production authentication change was
+created during this review. This hosted work does not block the independently
+qualified npm 1.0 publication.
+
+## 7. Development-cycle sequence and acceptance
+
+### Opening sequence while the owner is available
+
+1. Refresh the checkout, repository identity, current instructions and open decisions.
+ Read `README.md` before package changes. Preserve unrelated work and establish an
+ execution checklist with evidence paths. Do not rerun the entire research phase.
+2. Prioritize the native GitHub transfer from `matthew-kissinger/kiln` to
+ `instruktlabs/kiln`. This transfer has now completed: read its receipt and close
+ only remaining operational checks; never repeat it. For any still-unperformed
+ transfer step, open the existing repository/transfer page visibly and report
+ the fresh baseline in chat before the action. Use the section 2 preservation
+ preflight, including fork relationships, history, releases and issue assignments;
+ do not substitute a new repository, mirror or archive. At kickoff, use the owner's
+ explicit transfer authorization in the adopted goal, with human authentication or
+ recipient acceptance only where actually required.
+3. Immediately verify the immutable repository ID, stars/watchers/forks, all open
+ issue/PR identities and discussions, history/releases, redirects, permissions,
+ integrations and personal pin. Open the destination repository visibly and report
+ a before/after table in chat. Reconcile concurrent community changes. An unexplained
+ discrepancy blocks migration closeout and must be surfaced while the owner is
+ present. Keep old URLs working; do not recreate the old repository path. Update
+ remotes and project references without changing or triaging outside contributions.
+4. Start npm onboarding immediately afterward, or while an external transfer/account
+ step is pending. Reuse/create the personal account, secure the free `instruktlabs`
+ organization if available, and resolve email/2FA/recovery steps. Open each required
+ account page in the visible browser and state the exact human action in chat.
+ Credentials stay in the service's own interface/password manager. Account setup
+ is early; public package bootstrap waits for a reviewed candidate and authorization.
+5. Surface any remaining scope decision and any concrete account, paid-trial or
+ publication authorization needed for the next work before the owner leaves when
+ feasible. Use the asynchronous question tool for non-secret decisions. Existing
+ answers remain settled. Do not invent approval because the owner is absent.
+6. Continue package implementation, Cloudflare qualification, integrations and release
+ preparation independently while a human step is pending. Do not delay all useful
+ work on one account form, and do not silently substitute a different provider or
+ npm namespace. No additional user-owned task or scheduled automation is implied.
+
+### Overnight target and completion accounting
+
+The owner wants sustained overnight execution of the entire plan, starting with the
+supervised opening sequence. This target does not replace the planning estimate below
+or waive functional, isolation, release or installed-consumer checks. Complete all
+authorized work that can be completed; persist through ordinary failures and keep a
+durable milestone/evidence log. Do not declare the entire goal complete at sunrise,
+at the end of a turn, or merely because implementation is finished.
+
+Report npm publication, local plugin distribution, hosted production verification and
+each directory submission independently, with exact versions, hashes, URLs or
+submission receipts. Vendor review/acceptance is external and remains explicitly
+pending after a successful submission. If a required human action, provider limitation
+or failed qualification prevents an outcome, identify the exact remaining step and
+continue independent work; the unfinished outcome remains part of the goal. Surface
+a measured schedule/scope problem rather than silently reducing the plan.
+
+Planning estimate: **20-30 focused engineering days**, approximately four to six weeks
+for one maintainer, with external reviews outside that estimate. This is an estimate,
+not a deadline or a claim that provider isolation has already been solved. Re-estimate
+after the package and hosting spikes. Parallel workstreams are possible without
+changing the dependency order.
+
+| Milestone | Work | Exit evidence |
+| --- | --- | --- |
+| A. Identity and v1 contract, 1-2 days | Secure the chosen npm scope; preflight and perform the planned GitHub transfer; define supported SDK and consumer Node policy; align roadmap | Owned npm scope, preserved repository/community state, written API/migration contract |
+| B. Package candidate, 4-6 days | Rename identities; ESM/types; executable launcher; doc allowlist; notices; isolated clean installation and workspace upgrade | Exact RC tarball works as SDK/CLI/MCP on supported OS/Node matrix; no Bun for consumers |
+| C. Hosting/render spike, 2-3 days | Qualify Linux isolation/native dependencies/software Vulkan on Cloudflare first; investigate an alternative only for a demonstrated blocker or material advantage | Cloudflare qualification or evidence-backed exception proposal; renderer fidelity/latency/RSS receipt, explicit budget assumptions |
+| D. Hosted service, 5-8 days | HTTP MCP, OAuth, tenancy, persistence, downloads, quotas, cancellation, retention and rollback | Two-user isolation tests; source-evaluation readiness; real authenticated asset lifecycle; spend controls |
+| E. Plugin candidates, 2-4 days | Lightweight local Claude/Codex wrappers; public OpenAI ZIP; synchronized skills; directory metadata | Strict validation and clean installs; no duplicate server or plugin-cache asset storage |
+| F. Independent release gates, 3-5 days | Qualify and publish the exact package; verify local plugins and hosted journeys as each becomes ready; submit complete candidates | Separately recorded npm, local distribution, hosted service and directory submission receipts |
+
+These ranges overlap and sum to a broader envelope; do not treat the low end of every
+row as a committed schedule. Stage C starts early because unsupported isolation or
+slow software rendering could change the hosted design. Documentation and submission
+assets can progress while service work is underway. Store approval is not needed to
+make the npm package and owned marketplace available.
+
+### Parallel preparation, separate release decisions
+
+Owner decision, 6 October: free hosted v1 uses Google and GitHub sign-in for private
+saved assets and personal quotas; email can follow. The package and local plugins
+require no Kiln account. Request basic identity only, without repository or
+Gmail/Drive/Calendar permissions. The architecture review above defines the account boundary.
+The launch must present clear Kiln / Instrukt Labs branding, verified domain,
+privacy/support links and understandable consent, and qualify real sign-in,
+disconnect, deletion, expired credentials and cross-user denial. This is an access
+and ownership mechanism, not paid billing. Local authentication fixtures alone do
+not satisfy the owner's requirement for a secure, professional deployed flow.
+
+1. Establish the selected package name and repository destination early. Inventory
+ API changes and prepare portable builds while registration and transfer preflight
+ are underway.
+2. Make milestone B the package critical path. Start milestone C alongside it, and
+ prepare local plugin launchers and submission materials during B. Early plugin
+ testing should expose installation/API problems before the package is frozen.
+3. Build local plugin candidates against the exact RC. Build the hosted adapter
+ after provider isolation and rendering have passed C, using the same versioned
+ engine artifact rather than a separate fork.
+4. Release npm 1.0 when its package gates and required approval are complete. Local
+ owned distribution can follow as soon as its installed-package flow passes.
+ Neither step waits for a hosted launch or vendor directory approval.
+5. Launch the hosted candidate and submit each complete plugin when its own real
+ user flow passes. Anthropic's local plugin submission need not wait for the remote
+ OpenAI service. Keep both submissions in the cycle's target scope.
+6. If hosted qualification or submission work threatens that scope, surface the
+ evidence, remaining work and revised estimate. Do not silently defer it, and do
+ not mark the whole cycle complete when only npm publication is finished.
+
+The parallelism here is a work sequence, not authorization to start other agents,
+paid infrastructure or additional user-owned chats.
+
+### Required qualification
+
+Run the repository's full gates on the exact candidate with pinned maintainer tools:
+
+```text
+bun install --frozen-lockfile
+bun run check:toolchain
+bun run check:skills
+bun run typecheck
+bun run lint
+bun run test
+bun run test:render-service
+bun run test:coverage
+```
+
+After runtime changes, rebuild bundles using `node scripts/build-runtime.mjs all`;
+use `bun run build:runtime` when viewer assets also changed. `bun run build` alone
+does not rebuild bundles. Apply strict test-first work to behavior changes and retain
+the current coverage and MCP size budgets. Keep ordinary CI CPU-only and offline;
+the installed software renderer remains an explicit separate job.
+
+Add consumer evidence that the existing CI does not substitute for:
+
+- Plain Node ESM import and TypeScript type-check from the packed package; every
+ stable public export resolves, and library import does not launch the CLI.
+- Fresh npm install and npm-exec startup on Windows, Linux and both macOS architectures;
+ test the minimum supported Node and maintained LTS versions.
+- CPU operation without optional GPU dependencies; explicit native dependency errors;
+ software renderer correctness and deadline degradation where enabled.
+- Fresh workspace and managed upgrade with custom instructions, collections and saved
+ revisions retained; project membership stays opt-in.
+- Installed Claude Code and Codex plugin: create, inspect, edit, render, save, present
+ and export a small asset from a separate workspace, with exact revision receipts.
+- Hosted flow on real ChatGPT/Codex: connect, authorize, create, revise, material review
+ where supported, download GLB/editable source, reconnect and retrieve saved work.
+ Exercise the required mobile/reviewer paths and a usable text/download fallback.
+- Negative cases: malformed source, timeout/cancellation, quota rejection, forbidden
+ cross-user references, unavailable renderer, expired downloads and invalid tokens.
+- Import a produced GLB into the documented target viewer/importer. Existing scene
+ benchmarks do not prove a newly packaged SDK or chat download route.
+
+Live model qualification requires an explicit bounded budget when implementation
+reaches that point. Do not inherit earlier cycles' model-spend permissions.
+
+## 8. Release and submission runbook
+
+1. Secure the chosen npm scope and verify the planned repository transfer. Prepare publisher verification,
+ recovery access and npm organization permissions without exposing credentials.
+2. Freeze the public API, plugin identifiers and v1 migration notes. Record the full
+ optimizer's changed semantic-node behavior and replay old unversioned assets with
+ their original engine, or create explicit new revisions.
+3. Build and qualify an RC from a clean source revision. Publish an authorized RC under
+ the prerelease tag; demonstrate fresh consumers and plugin installs.
+4. Produce and qualify the final `1.0.0` artifact. Present digest, checks, migration
+ notes and exact public changes for release approval. Do not substitute a rebuilt
+ artifact after approval.
+5. Publish npm and GitHub release artifacts; verify registry integrity/provenance and
+ a fresh installed user flow. Keep package publication, source release and website
+ deployment as separately recorded results.
+6. Publish owned marketplace metadata pinned to the final release. Test installed
+ cached copies, not only repository-relative development paths.
+7. Independently deploy the approved hosted candidate. Verify `/mcp`, authentication,
+ data separation, health/build identity, quotas, real artifact downloads and rollback
+ readiness. This is not a prerequisite for steps 5-6 or the local Anthropic submission.
+8. Submit the complete OpenAI plugin ZIP and Anthropic plugin source through their
+ current portals. Record candidate versions, source commit, endpoints, evidence,
+ submission receipts and review status. Contact a vendor partner about curated
+ local/official-marketplace routes only if the owner separately authorizes outreach.
+9. Address review feedback, publish approved listings and rerun the real install flow.
+ Record approval/publication as pending if vendor review extends beyond the cycle.
+
+The controllable cycle endpoint is **npm 1.0 published, hosted service and owned plugin
+distribution operational, both public directory submissions made with evidence**.
+The broader launch endpoint includes approved public listings. Never mark the latter
+complete on a successful ZIP validation or form submission alone.
+
+## 9. Decision queue and owner collaboration
+
+### Confirmed constraints
+
+The release target is 1.0; community issue/PR triage remains outside the pre-v1 scope.
+The owner owns the Instrukt Labs GitHub organization and states that it is the LLC
+name. On 6 October the owner chose `@instruktlabs/kiln` and an early transfer to the
+organization, conditional on preserving stars, open PRs and existing community
+history. The private Sites trial was separately authorized. These choices do not
+need to be asked again. npm scope registration and the transfer have not been
+performed at the initial planning stage. The owner subsequently authorized immediate
+setup: the native GitHub transfer is complete with preservation verified, the Actions
+allowlist fix is applied with a passing Linux CI rerun, and the npm account/free organization
+are created with 2FA enforcement verified. The owner initially selected up to $20/month and then clarified on
+6 October that it is a starting target, not a hard ceiling. Growth is acceptable;
+avoid sustained hundreds of dollars without funding. The owner already has Cloudflare
+and ChatGPT Pro, is willing to pay for justified hosting, and is interested in
+sponsorships/credits. Concrete paid deployments and production publication remain
+separate actions; this clarification does not authorize an unspecified purchase.
+The owner selected saved-asset retention until deletion within a quota, with unsaved
+work expiring after seven days, on 6 October. This policy is settled; exact storage
+quotas remain open. The public service domain is `kiln.instruktlabs.com`, selected
+on 6 October; domain control and configuration still require verification.
+After the experimental inventory and actual MCP/package exposure were explained,
+the owner accepted the section 4 recommendation on 6 October: retain existing
+functionality, make labels/limitations visible, document stable APIs separately,
+preserve explicit exporter selection, and review availability/default changes
+individually. This policy is settled.
+The owner selected an all-Cloudflare production stack on 6 October. A bounded Sites probe may
+continue; Cloud Run requires a concrete cost, performance, capacity or capability
+reason before proposing a change. This provider decision is settled, while actual runtime
+qualification remains implementation work.
+The owner subsequently selected free hosted access within quotas with optional
+sponsorship and no subscription billing in v1. They accept justified usage overages
+and are open to a paid Cloudflare developer plan when the concrete costs make sense.
+This settles D8 and reinforces that $20 is a target, not a guaranteed billing cap.
+
+### Decision register
+
+| ID | Decision and recommendation | When to surface | Current status |
+| --- | --- | --- | --- |
+| D1 | Product Kiln Engine; publisher Instrukt Labs; npm `@instruktlabs/kiln` | Before package identity changes or npm publication | Scope secured on 6 October: free `instruktlabs` npm organization owned by `matthew-kissinger`; package unpublished |
+| D2 | Transfer to `instruktlabs/kiln` early and preserve personal pin | Before final publishing trust and directory source bindings | Native transfer completed 6 October; community/history/pin preservation verified; exact Bun action allowlisted with owner approval; Linux CI rerun passed |
+| D3 | Preserve established documented SDK features, emit ESM/types, retain and consistently label existing experimental features; maintained Node 22/24 with tested minimum | Before freezing v1 API contracts | Owner accepted the concrete inventory/exposure recommendation on 6 October; fix the compact MCP label gap and preserve explicit exporter selection; specific consequential compatibility changes still require evidence |
+| D4 | All-Cloudflare stack, CPU fallback plus qualified software Vulkan; bounded Sites probe; alternative host only with a demonstrated reason | Qualify the selected stack during implementation; surface exceptions with evidence | Owner adopted the all-Cloudflare stack on 6 October; actual deployment/isolation/performance/cost qualification remains open |
+| D5 | Optimize near $20/month initially, allow deliberate growth, avoid sustained unfunded hundreds; use admission controls and cost visibility | Establish measured operating thresholds before paid deployment or broader access | Owner clarified on 6 October that $20 is not a hard cap; existing Cloudflare and Pro; interested in sponsorships/credits; exact paid trial remains to be prepared |
+| D6 | Private user artifacts, clear retention/deletion, controlled support/privacy domain | Before persistence policy and OAuth identity are fixed | Owner selected saved assets retained until deleted within a quota, unsaved work expires after 7 days, and `kiln.instruktlabs.com` on 6 October; exact quotas and publisher account details still open |
+| D7 | Public OpenAI plugin plus Anthropic directory; local owned distribution available independently | Before exact artifacts are submitted/published | Requested outcome; final candidates and applicable approvals still required |
+| 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 |
+
+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
+from the GitHub display name. No approval is required merely to inspect code, compare
+options or prepare a reviewable proposal within the authorized work.
+
+### Remaining question sequence
+
+The owner requested the remaining decisions be sequenced on 6 October. Ask in this
+order, retaining the IDs above so answers remain traceable:
+
+1. **D5: funding preference, answered and clarified.** $20/month is the initial target,
+ not a hard ceiling. The owner will consider growth and sponsorship/credits but
+ wants to avoid sustained unfunded hundreds. Do not ask the hard-cap question again.
+ Bring measured forecasts and concrete funding choices when relevant.
+2. **D6: hosted artifact retention and access, answered.** On 6 October the owner
+ selected retention of saved source files and GLBs until deletion within a storage
+ quota, with unsaved work expiring after seven days. Do not ask this policy again.
+ Keep artifacts private by default. Exact quotas require measured artifact sizes
+ and must fit the measured operating/funding plan, including global capacity limits.
+3. **D6: public domain answered; publisher accounts at setup.** The owner selected
+ `kiln.instruktlabs.com` on 6 October for the hosted service, MCP endpoint and
+ support/privacy pages. Do not ask the domain preference again.
+ Verify domain control and resolve publisher details before OAuth and submission configuration.
+ Ask only for missing non-secret information; use normal account connection flows
+ for authentication.
+4. **D3: experimental scope clarified and accepted.** On 6 October the owner accepted
+ the section 4 recommendation after reviewing the operation, 16 recipes, exporter
+ backend and actual MCP exposure. Keep existing functionality, show labels/limits
+ consistently, document stable APIs separately and retain explicit exporter
+ selection. Do not ask this broad policy again.
+ Present concrete callers/migration evidence for any consequential compatibility
+ change. Do not require the owner to design build tooling or resolve routine
+ technical details.
+5. **D8: hosted access and billing scope, answered.** The owner selected free
+ hosted access within usage/storage quotas and global capacity limits, with no
+ subscriptions or payment integration in v1. The free npm/MIT distribution is
+ already part of the release; this question concerns only the hosted service.
+ Answered on 6 October. Sponsorship can fund access without building subscriptions into
+ v1. This concerns charging users, not the owner's Cloudflare bill. A free service
+ still needs authentication and expenditure controls. Resolve it before hosted
+ signup is fixed; exact quotas need measurement, but the business-model choice is settled.
+6. **D4: Cloudflare direction settled; qualification during implementation.** Test
+ Cloudflare first and keep the Sites probe bounded. Bring measured isolation,
+ preview fidelity, cold/warm latency, memory, load and cost results. Propose Cloud
+ Run only for a concrete blocker or material advantage. Prepare
+ a bounded paid-trial proposal first if needed; a monthly planning answer alone
+ does not authorize an unspecified deployment. Do not repeat the choice between
+ providers before the evidence can distinguish them.
+7. **D7: release and submission actions, against completed candidates.** Present the exact qualified artifacts,
+ destinations, verification results and unresolved limitations. Honor existing
+ authorization and seek only missing action approvals. npm, hosted launch and
+ directory submissions have separate readiness checks.
+
+No additional general preference question is needed to start independent implementation
+after the owner initiates the goal. D8 is settled; implement free access without billing.
+Host qualification, exact quotas, publisher setup and consequential compatibility
+changes can be resolved while work proceeds when their evidence is ready. D1, D2,
+D4's all-Cloudflare decision, D5, experimental-feature policy, retention policy and domain preference are settled and
+must not be asked again. Later owner questions should concern measured host tradeoffs, exact quotas,
+missing publisher setup details or concrete release candidates, not another round
+of general preferences. Surface an unexpected scope, cost or compatibility decision
+at the point it matters instead of waiting for its position in this queue.
+
+### How questions should be handled during execution
+
+The owner explicitly permits decisions to be surfaced now, sequenced through the
+question tool, or asked while work is underway. Use that permission to keep the work
+moving without requiring every decision at the start:
+
+- Ask the next one or two relevant questions using the asynchronous question tool.
+ Give a concrete recommendation, succinct alternatives and the practical tradeoff.
+- For account setup or authentication, also open the relevant page in the visible
+ browser and post the exact handoff in chat. The question tool is for non-secret
+ answers; passwords, verification codes and recovery material stay in the service's
+ own interface. Resume after the owner completes the step. This browser-and-chat
+ handoff was explicitly requested for the opening transfer/npm work on 6 October.
+- Continue independent work while awaiting an answer. For optional preferences,
+ distinguish a stated planning assumption from an adopted owner decision. Silence
+ never grants approval for publication, account changes or spend.
+- Resolve routine reversible implementation details autonomously within the approved
+ scope. Surface changes to product scope, compatibility, public identity, data
+ retention, cost or release timing before they become expensive to undo.
+- Record the owner's answer, date and resulting plan change in this decision queue;
+ preserve existing authorization and do not ask the same question again.
+- Before an action that still requires approval, finish the authorized preparation
+ and present the exact artifact, destination, cost or change being approved. Follow
+ [AGENTS.md](../../AGENTS.md#safety), including its instruction: "Do not commit, push,
+ force-push, create remotes/releases, or publish packages without explicit user
+ approval." Recheck the conversation first so existing approval is honored.
+- Keep package publication, local distribution, hosted readiness, submissions and
+ directory acceptance separately reported. Surface a scope/schedule decision if a
+ remaining milestone cannot meet the current plan; do not silently remove it.
+
+## 10. Evidence anchors and freshness
+
+Repository evidence: `package.json`; `src/runtime-support.mjs`;
+`src/runtime-identity.ts`; `src/views/renderer-id.ts`; `src/views/port.ts`;
+`src/evaluator/isolation.ts`; `src/tools/registry.ts`; `src/mcp-server.ts`;
+`scripts/build-runtime.mjs`; `scripts/create-workspace.mjs`;
+`scripts/package-plugin.mjs`; `scripts/test-plugin-package.mjs`;
+`scripts/smoke-package.mjs`; `scripts/smoke-renderer.mjs`;
+`.github/workflows/ci.yml`; the three plugin manifests; `docs/install.md`;
+`docs/chatgpt.md`; `docs/runtime.md`; `THIRD_PARTY_NOTICES.md`; `CONTRIBUTING.md`;
+`CHANGELOG.md`; `ROADMAP.md`; `docs/backlog.md`.
+
+Public namespace checks used npm registry metadata and visible npm scope pages.
+The initial GitHub organization/release/CI checks used read-only API calls. No
+credentials were printed. The research-stage cloud write was the separately
+authorized owner-private Sites trial and its managed source repository.
+The owner subsequently authorized immediate setup: the engine repository was
+natively transferred, the exact Bun action was allowlisted with separate owner
+approval, an existing CI job was rerun, and the free npm organization was registered.
+See [the setup receipt](../reviews/2026-10-06-publisher-setup.md) for current outcomes.
+No package was published or third-party message sent. Cloudflare Workers Paid and
+R2 Paid were verified active in the account; no purchase or upgrade was performed.
+Pricing and submission rules were checked against the
+official sources linked above; recheck them at implementation and submission because
+these platforms are changing rapidly.
diff --git a/docs/plans/2026-10-06-hosting-economics.md b/docs/plans/2026-10-06-hosting-economics.md
new file mode 100644
index 00000000..51749cfd
--- /dev/null
+++ b/docs/plans/2026-10-06-hosting-economics.md
@@ -0,0 +1,421 @@
+# Kiln 1.0 hosting economics
+
+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.
+No paid Cloudflare deployment, DNS change, sponsorship application or account upgrade
+was performed. The existing, separately authorized private Sites probe remains active.
+
+## Owner direction
+
+The owner clarified that **$20/month is an initial target, not a hard ceiling**.
+Choose an efficient host and allow deliberate growth. Avoid drifting into hundreds
+of dollars of recurring costs without revenue, sponsorship or an explicit funding
+decision. The owner already has Cloudflare and ChatGPT Pro. On 6 October the owner
+adopted the all-Cloudflare production stack described below; actual runtime and cost
+qualification remain implementation work. Sites may complement it if verified benefits justify
+the extra integration. No automatic move to Google Cloud Run is planned.
+
+The owner subsequently confirmed free hosted access within quotas with optional
+sponsorship and no end-user subscription billing in v1. They accept justified usage
+overages and are open to a suitable paid Cloudflare plan. Use Workers Paid
+(currently a $5/month account subscription with included allowances), plus metered
+Containers/storage and other overages. This is separate from a domain's Pro/Business
+plan. The signed-in dashboard now confirms Workers Paid and R2 Paid are already
+active, renewing 20 October 2026; no purchase or upgrade was needed. The observed
+cycle has $0.00 in usage charges beyond included allowances, excluding the base
+subscription. Existing applications share those allowances. Keep the $5 base in
+the standalone service scenarios below, but do not count another $5 subscription
+as an incremental Kiln charge on this same account. Prepare the bounded compute
+trial estimate before deployment. Sources and rates are below.
+
+## What actually costs money
+
+### Recommended implementation: all Cloudflare
+
+```mermaid
+flowchart TD
+ Client[ChatGPT / Codex / Claude MCP client] --> Edge[Workers: HTTPS MCP, OAuth, discovery, admission]
+ Browser[Kiln website and viewer] --> Edge
+ Edge --> Meta[Tenant Durable Objects + SQLite: ownership, revisions, quotas]
+ Meta --> Files[R2: private source, GLBs, previews]
+ Meta --> Scheduler[Durable Objects: bounded execution and lifecycle]
+ Scheduler --> Compute[Cloudflare Linux Container: Node + native engine dependencies]
+ Compute --> CPU[Existing CPU rasterizer]
+ Compute --> Software[Qualified Mesa software Vulkan + Dawn renderer]
+ Compute --> Edge
+```
+
+The whole diagram can reside under Cloudflare. **Containers are the native compute
+service; Workers and Sites are not substitutes for it.** Cloudflare documents Linux
+images, native tools and child processes as a [Container use case](https://developers.cloudflare.com/sandbox/concepts/).
+Bake the exact Node bundle and native libraries into a pinned Linux image; install
+nothing from user input at job time. Serve the web viewer with Workers static assets.
+
+Implementation refinement: tenant ownership and quota transactions now use the
+tenant Durable Object's own SQLite database. This keeps the authoritative record
+with the tenant routing boundary; it does not need a second D1 copy of those records.
+D1 remains optional for a demonstrated shared-metadata need, not a resource to
+provision merely because it appeared in the initial diagram.
+
+Native execution does not require hardware GPU rendering. CPU geometry previews
+already exist in Kiln. Textured/material previews would use the repo's existing
+software Vulkan path, which runs graphics code on the CPU. Current Container types
+list CPU, RAM and disk, with no GPU configuration in the verified documentation.
+Therefore this plan assumes CPU-only Cloudflare compute, not Workers AI GPUs usable
+as a Vulkan device. If hardware rendering becomes necessary, retain `PbrRenderPort`
+and attach a separately priced, qualified GPU service only for view production.
+
+Use an isolated Container sandbox per trust boundary, with a short bounded lifetime.
+Do not share one unrestricted Linux process/filesystem across tenants. Cloudflare's
+[sandbox security guidance](https://developers.cloudflare.com/sandbox/concepts/security/)
+explicitly says processes inside a sandbox share access and that a Linux username is
+not an isolation boundary. Keep OAuth tokens, R2 credentials and other users' files
+in the trusted Worker. Apply outbound network restrictions outside the sandbox.
+The Worker remains authoritative for ownership, quotas and permitted output handling.
+
+The critical spike is whether Kiln's current `setpriv`/`bwrap`/namespace restrictions
+work inside the actual Container. Native binary support alone does not prove this.
+If they do not, qualify an explicit per-job sandbox adapter; do not silently weaken
+the current evaluator. Test filesystem escape, network denial, CPU/native-memory
+limits, cancellation and tenant separation along with rendering. Treat Container
+outputs as untrusted inputs at the host boundary. A successful local Docker run or
+existing software-renderer CI job is insufficient to accept hosted isolation.
+
+Start with `standard-2` as a conservative test fixture, then measure a custom
+one-vCPU/3-GiB configuration if RSS and image size permit. Current
+[custom instance constraints](https://developers.cloudflare.com/containers/platform/limits/)
+allow sizing within documented CPU/memory/disk limits. The tables below retain
+6 GiB for a reproducible conservative comparison; they do not claim optimized sizing.
+
+### When another compute host could be better
+
+| Candidate | Why consider it | Price evidence and limitation |
+| --- | --- | --- |
+| Cloudflare Workers + Containers + R2 | Preferred first candidate for intermittent work, integrated operations and scale-to-zero | Usage scenarios below; native isolation/software rendering still need provider tests |
+| Cloudflare edge/storage + a Linux VM | Predictable compute bill if usage keeps a machine busy, or if Container isolation is incompatible | DigitalOcean Basic 8 GiB/4 shared vCPU is $48/month; CPU-Optimized 8 GiB/4 dedicated vCPU is $84/month, before the edge/storage and extras |
+| Hetzner Linux VM + Cloudflare edge/storage | Lower fixed-cost candidate when regional latency and capacity are acceptable | June 2026 official schedule lists EU CX33 at $9.99/month and CPX32 at $41.99, excluding IPv4/tax; instance capacity/availability must be checked, not inferred from a stale low-price advertisement |
+| Sites Pro + external Container/VM | Managed frontend/identity convenience | Cannot remove native compute cost; Pro hosting allowance and public-plugin route remain insufficiently quantified |
+
+Sources: [DigitalOcean pricing](https://www.digitalocean.com/pricing/droplets),
+[Hetzner current price-adjustment schedule](https://docs.hetzner.com/general/infrastructure-and-availability/price-adjustment/),
+[Hetzner cost-optimized specifications](https://www.hetzner.com/cloud/cost-optimized/).
+Both cited Hetzner models have 8 GB memory; the public product pages returned
+unavailable markers during this read, so checkout capacity is unverified. Do not
+select a launch dependency on that basis. A shared vCPU is not equivalent to dedicated
+capacity, and an 8-GB VM does not prove four simultaneous 6-GiB Kiln jobs will fit.
+
+For perspective, one DigitalOcean Basic VM plus the modeled Cloudflare base and
+100 GB R2 is about $54.35/month before backups/tax. It does not guarantee the same
+throughput, isolation or availability as an elastic fleet. A VM requires patching,
+process supervision, isolation, backups and recovery. Compare measured completed
+work per dollar, not nominal vCPU counts. Cloud Run remains an evidence-backed
+exception candidate rather than an automatic next step.
+
+The recommendation is to qualify the all-Cloudflare stack first. Revisit a fixed VM
+when measurements show steady utilization or roughly $50-$100/month of compute.
+Keep the Linux job interface portable so replacing compute does not require moving
+the domain, OAuth service, stored assets, npm package or plugin identity.
+
+An installed MCP connection is not a dedicated Kiln machine. Keep discovery,
+authentication, artifact listings and downloads at the edge; admit isolated engine
+jobs only when a tool needs evaluation, export or rendering. Persist assets outside
+the compute instance and stop compute between work when practical.
+
+This model assumes the user's ChatGPT/Claude session writes source and calls tools.
+Kiln does not invoke a maintainer-funded model. If a hosted native agent loop, image
+generation or texture API is added, price that separately. The owner's Pro plan must
+not be treated as pooled model credits for public users.
+
+Current Cloudflare rates used in the calculations:
+
+| Component | Included monthly amount | Overage assumption |
+| --- | --- | --- |
+| Workers Paid | $5 account subscription; 10M requests; 30M CPU-ms | $0.30/M requests; $0.02/M CPU-ms |
+| Container CPU | 22,500 vCPU-seconds | $0.000020/vCPU-second |
+| Container memory | 90,000 GiB-seconds | $0.0000025/GiB-second |
+| Container disk | 720,000 GB-seconds | $0.00000007/GB-second |
+| R2 Standard | 10 GB-month; 1M writes/Class A; 10M reads/Class B | $0.015/GB-month; $4.50/M Class A; $0.36/M Class B |
+| Durable Objects compute | 1M requests; 400,000 GB-seconds | $0.15/M requests; $12.50/M GB-seconds |
+| Durable Objects SQLite | 25B rows read; 50M rows written; 5 GB-month | $0.001/M rows read; $1/M rows written; $0.20/GB-month |
+
+Sources: [Workers](https://developers.cloudflare.com/workers/platform/pricing/),
+[Containers](https://developers.cloudflare.com/containers/platform/pricing/),
+[R2](https://developers.cloudflare.com/r2/pricing/),
+[Durable Objects](https://developers.cloudflare.com/durable-objects/platform/pricing/).
+Containers charge allocated memory/disk while awake and actual CPU usage; sleep
+stops container compute billing. R2 internet egress is free, but container egress has
+its own allowance. DO duration and R2 operations have billing-unit rounding, included
+below. All allowances are account-level assumptions, not newly granted per project.
+
+The modeled instance is `standard-2`: one vCPU, 6 GiB RAM, 12 GB disk. This is a sizing
+assumption carried from the hosting research, not evidence that Kiln needs 6 GiB or
+that a smaller instance works. A lower-memory qualified instance could cost less.
+Workers Paid is separate from a domain's Pro/Business zone plan; do not purchase a
+zone upgrade without a feature that requires it.
+
+## Usage scenarios
+
+One session means an asset-authoring visit, potentially containing repeated edits
+and reviews. A compute job means one evaluation/render/export invocation, not one
+finished asset. Failures, retries and revisions count as work too.
+
+| Assumption per monthly active user | Occasional author | Frequent author |
+| --- | --- | --- |
+| Authoring sessions/month | 4 | 20 |
+| Compute jobs/session | 10 | 20 |
+| Compute jobs/month | 40 | 400 |
+| CPU and busy wall time/job | 5 seconds each | 15 seconds each |
+| Extra awake time/session, including startup and idle gaps | 60 seconds | 60 seconds |
+| Extra CPU/session for startup | 2 vCPU-seconds | 2 vCPU-seconds |
+| Average retained source/GLB/preview storage | 100 MB | 100 MB |
+
+These inputs are hypotheses for sensitivity analysis. The 60-second overhead is the
+total extra awake time across the session, not a promised cold-start time or a
+five-minute timeout on each tool call. It requires checkpointing and sensible sleep
+behavior; retaining a container throughout model thinking can cost substantially more.
+The 100 MB storage assumption is neither an adopted quota nor a measured asset size.
+
+| Monthly active users | Occasional jobs/month | Occasional modeled USD/month | Frequent jobs/month | Frequent modeled USD/month |
+| ---: | ---: | ---: | ---: | ---: |
+| 100 | 4,000 | $5.44 | 40,000 | $27.76 |
+| 500 | 20,000 | $10.44 | 200,000 | $134.80 |
+| 1,000 | 40,000 | $16.75 | 400,000 | $257.47 |
+| 5,000 | 200,000 | $67.27 | 2,000,000 | $1,311.56 |
+
+These columns are two workload scenarios, not confidence bounds. A real population
+will mix light and heavy users; a small group of intensive users can dominate usage.
+For example, 1,000 users at the occasional workload, with 10% upgraded to the frequent
+workload, produces approximately $40/month under the same assumptions.
+
+The table includes the $5 subscription, compute, storage and the modeled request,
+log and network overages. It assumes otherwise unused included allowances, compact
+metadata within included D1/DO SQL allowances, downloads served from R2, and no
+paid identity provider. It excludes tax, existing domain renewal, the already-owned
+Pro subscription, engineering/support, backup copies and unmodeled abuse/retries.
+Allow operational headroom rather than spending to the calculated cent. Do not count
+the full account allowances again if other projects already consume them.
+
+At 1,000 occasional users, the calculation breaks down to $5 subscription, $3.71
+CPU, $6.38 memory, $0.32 disk and $1.35 R2 storage. Other modeled usage remains within
+its included amounts. This suggests an initial community deployment can plausibly
+live near the $20 target, **if the actual job and idle measurements match**.
+
+## Idle time, storage and concurrency change the answer
+
+For the same 1,000 occasional users and 40,000 jobs:
+
+| Total extra awake time per session | Modeled monthly cost |
+| --- | ---: |
+| 0 seconds, optimistic lower-overhead case | $12.95 |
+| 60 seconds | $16.75 |
+| 5 minutes | $31.96 |
+| 15 minutes | $82.48 |
+
+An otherwise idle `standard-2` instance kept awake for all 720 hours of a 30-day month
+costs about $45.78 including the base subscription and provisioned memory/disk,
+before storage or background CPU. Fully occupying its CPU raises that to about
+$97.17. Therefore, do not buy an always-warm machine implicitly through idle policy.
+The existing local renderer's five-minute lifecycle is not automatically the right
+hosted policy. Never shorten it by changing the shared engine contract globally;
+implement and qualify the host's lifecycle separately.
+
+Storage depends on all retained accounts, including inactive users. R2 Standard at
+100 GB-month is $1.35; at 1,000 GB-month it is $14.85. Saved assets remain until deleted
+within quotas, so storage can accumulate across months. Unsaved work expires after
+seven days. The table assumes a bounded total stock, not unlimited history.
+
+Do not assign a container or permanently active DO to every connected user. Current
+Cloudflare [MCP handler APIs](https://developers.cloudflare.com/agents/model-context-protocol/apis/handler-api/)
+support stateless request handling. Qualify it against the required clients, keeping
+user state in durable storage and respecting transport compatibility. Container
+coordination can still use DOs without making every MCP connection a running server.
+
+Monthly affordability is not burst capacity. The occasional 1,000-user scenario has
+about 122 aggregate container-hours/month; the frequent case has 2,000 hours, already
+requiring more than two continuously utilized instances on average. Peaks require
+more instances or a queue. A single serial five-second job slot serves at most twelve
+jobs/minute before overhead. Admission/concurrency limits must deliver an honest
+busy/retry result; price and test bursts separately from monthly totals.
+
+## Reproducible calculation
+
+Let `U` be active users; `S` sessions/user; `J` jobs/session; `c` CPU seconds/job;
+`w` busy seconds/job; `h` extra awake seconds/session; `i` startup CPU/session.
+
+```text
+jobs = U*S*J
+cpuSeconds = jobs*c + U*S*i
+awakeSeconds = jobs*w + U*S*h
+container = max(0,cpuSeconds-22500)*0.000020
+ + max(0,6*awakeSeconds-90000)*0.0000025
+ + max(0,12*awakeSeconds-720000)*0.00000007
+```
+
+Sum awake seconds across instances; overlapping jobs cannot be counted as parallel
+single-vCPU throughput for free. The table assumes serial execution within each
+instance. The DO estimate conservatively budgets active time equal to instance
+awake time at 0.128 GB per DO, then subtracts 400,000 GB-s and rounds any remainder
+up to million-GB-s billing blocks. Extra active session/admission DO time must be
+added if the architecture introduces it.
+
+Additional explicit assumptions in the reproducible model:
+
+- Worker requests: five/job, twenty/session, twenty/user; five CPU-ms/request.
+- DO requests: two/job, one/session, one/user, rounded in excess-million blocks.
+- R2: four Class A operations/job and ten Class B operations/job; average storage
+ `0.1*U` GB-month, rounded per published billing units. Add inactive users separately.
+- Container egress: 1 MB/job in North America/Europe; subtract 1,000 GB/month, then
+ $0.025/GB. Downloads come from R2; do not regenerate/re-serve GLBs from compute.
+- Logs: five events/job plus one/Worker request. The current included 20M events and
+ $0.60/M excess are used; reprice for the announced 1 December 2026 pricing change.
+- D1/DO SQL: assume indexed compact metadata below included storage/read/write
+ allowances. Polling and full-table scans must be measured before relying on this.
+
+## Sites with the owner's existing Pro subscription
+
+The [current Sites documentation](https://learn.chatgpt.com/docs/sites) confirms Pro
+availability, custom domains/subdomains, D1/R2, sign-in and plan-specific limits.
+It does **not** publish a numerical Pro allowance for requests/CPU or an overage
+price table. Hitting a limit can restrict storage or continued public hosting.
+Do not translate Pro's model rate-limit multipliers into hosting capacity, and do not
+interpret “no fixed” R2 storage limit as unlimited included usage.
+
+Read-only account checks on 6 October confirmed the existing probe is active,
+owner-private and MCP-ready, with no custom domains attached. Its settings UI exposes
+**Add custom domain**, so custom-domain configuration is available to this account.
+`kiln.instruktlabs.com` is therefore a supported type of target, subject to DNS and
+TLS verification. No domain was attached and no DNS records changed. Site settings
+did not expose a numerical hosting quota or cost estimate. The account's Usage view
+showed model/Work/Codex usage categories, not a Sites hosting meter; those balances
+were not used as hosting capacity. Pro was also visible in the account menu.
+
+Treat already-paid Pro as a sunk subscription in the incremental comparison. Sites
+might add no separate hosting charge within its allowance, but that is a conditional
+scenario, not a verified unlimited-price promise. A complete Sites cost forecast
+remains unavailable until account-specific limits and paid expansion terms are visible.
+
+Sites remains a Worker runtime, so current Kiln native modules, subprocess isolation
+and software Vulkan still require external Linux compute. A Sites + Cloudflare
+Containers hybrid retains the Cloudflare paid compute subscription and most of the
+costs above. At the occasional scenario's scale, the Cloudflare gateway already fits
+inside its included requests, so replacing it with Sites produces no modeled gateway
+savings. Sites could still offer valuable managed identity or UI convenience.
+
+Public Site access, public MCP authorization and public plugin-directory distribution
+remain separate qualifications. The earlier managed-plugin install was not completed.
+For a custom domain, test OAuth discovery, issuer/resource matching, redirects and
+client reconnection on the actual hostname, rather than assuming the existing
+`chatgpt.site` OAuth resource changes automatically.
+
+## Sponsorship and credits
+
+1. **GitHub Sponsors under Instrukt Labs** is the most direct recurring hosting-fund
+ option. [GitHub supports organizations receiving sponsorships](https://docs.github.com/en/sponsors/receiving-sponsorships-through-github-sponsors/about-github-sponsors-for-open-source-contributors).
+ Personal-account sponsorships carry no GitHub fee; organization sponsorships have
+ different fees. Illustratively, ten $5 monthly individual sponsors fund $50 gross,
+ enough to make modest growth easier to support. Revenue is zero in the base model
+ until actually committed; do not promise paid service entitlements for donations.
+2. **Cloudflare for Startups** currently advertises a $10,000 entry tier for
+ bootstrapped/self-funded companies, with one-year credits and eligibility review.
+ [The current page](https://www.cloudflare.com/startups/) also has potentially
+ conflicting general “funded within the last 12 months” wording. Verify eligibility,
+ legal entity facts and explicit Containers coverage before counting credits.
+ Instrukt Labs may be a candidate, not an established accepted applicant. Credits
+ expire and overages can be billed. Evaluate steady-state economics without them.
+3. **Project Alexandria**, which the old OSS sponsorship link now redirects to,
+ offers annual OSS credits. It requires a recognized OSS license and operation
+ solely on a non-profit basis. The LLC/open-source combination does not establish
+ that condition; obtain provider clarification before treating this as suitable.
+ [Current program terms](https://www.cloudflare.com/lp/project-alexandria/).
+
+Research and prepare an application packet during the cycle, but do not make grants
+a release dependency. Include the public repo, license, verified usage, monthly cost
+model, requested products and benefit to users. No applications or outreach sent.
+
+## Recommendation and qualification gate
+
+Proceed with Cloudflare Workers + bounded Linux Containers + R2 as the preferred
+candidate. Preserve portable compute and keep Sites as a bounded integration option.
+There is currently no evidence that Sites removes the expensive part of this workload.
+
+Proposed operating policy, to set after measurements: begin near $20, notify/review
+when the run rate approaches $30-$50, and require a funding/capacity decision before
+planning sustained $100+ months. These thresholds are recommendations, not owner-set
+caps or authorization for spend. Track gross infrastructure cost, confirmed recurring
+sponsorship, credits and out-of-pocket cost separately. Avoid building subscription
+billing into v1 solely because future growth might need funding.
+
+[Cloudflare budget alerts](https://developers.cloudflare.com/billing/manage/budget-alerts/)
+are informational and do not stop billing. Add a global admission budget, per-user
+limits, bounded job time/memory, maximum instances, idle shutdown, storage quotas,
+log controls and an operator compute-stop control. A rejected request or retained
+storage can still cost money; this is expenditure control, not a guaranteed invoice cap.
+
+The hosted spike must replace assumptions with measurements of representative CPU
+and material-preview jobs: CPU-seconds, RSS, cold startup, aggregate awake time,
+cancel/retry rates, output sizes, storage operations and peak queue latency. Reconcile
+those with the provider's metering and the account's already-used allowances. Recompute
+both usage profiles, a mixed population, and burst behavior before opening access.
+
+## CLI choice and local probe
+
+Use the official [Cloudflare CLI, `cf`](https://developers.cloudflare.com/cf/), pinned
+in the new hosting project if qualification succeeds. It is currently beta. On this
+Windows machine, `[email protected] --version` and the offline command search for
+container applications passed from an isolated scratch install. The initial `npx`
+attempt failed because a cache package file was missing; a project-local install
+with lifecycle scripts disabled succeeded. No login, deployment or global install
+was performed.
+
+Keep Wrangler for existing deployment scripts and beta gaps. The
+[migration guide](https://developers.cloudflare.com/cf/wrangler/migrate/) requires
+manual attention for Containers and DO migrations; preview changes with dry-run.
+Do not run automatic project setup/migration over the existing website during this
+research. `cf` has separate authentication, requires Node 22.18+ for configuration,
+and does not make current Wrangler configuration interchangeable automatically.
+
+Scratch CLI receipt location:
+`C:/Users/Mattm/X/kiln-dogfood/cf-cli-probe-2026-10-06/`.
+
+## OAuth storage addition during implementation
+
+The hosted OAuth gateway uses a dedicated Workers KV namespace for the maintained
+Cloudflare OAuth library. This stays within the selected provider; user sources
+and assets retain their separate storage boundary. It does not require another
+subscription beyond the existing Workers Paid plan.
+
+Rechecked [KV pricing](https://developers.cloudflare.com/kv/platform/pricing/)
+on 6 October: Paid includes 10 million key reads per month, one million each of
+writes, deletes and list requests, and 1 GB stored. Overage is $0.50 per million
+reads, $5 per million writes/deletes/list requests, and $0.50 per GB-month.
+Account-wide existing usage consumes those same allowances. Failed lookups are
+billable reads, so anonymous token/registration abuse still needs admission controls.
+
+At modest initial use, authentication can fit within the included allowance; this
+is a planning inference, not measured usage. The live qualification must count
+operations across sign-in, MCP requests, refresh, revocation and expired-record
+cleanup and include them in the complete bill. The prototype keeps access tokens
+to 15 minutes and refresh grants to 30 days, with library-managed record expiry.
+Production KV propagation and account-wide usage remain unqualified.
+
+## Tenant-storage implementation costs
+
+The separate tenant Worker adds SQLite ownership/quota records, R2 object writes,
+downloads and bounded retention/reconciliation alarms. The SQLite rates above were
+rechecked on 6 October against [Cloudflare pricing](https://developers.cloudflare.com/durable-objects/platform/pricing/).
+Indexes and deletes count toward writes; setting an alarm also counts as a write.
+This is SQLite-backed Durable Object pricing, not legacy DO key-value pricing.
+
+Daily reconciliation costs persist for a tenant after ordinary artifact deletion.
+For 1,000 retained tenants with at most 100 R2 objects each, one daily listing per
+tenant is about 30,000 monthly Class A calls and 30,000 alarm invocations, before
+uploads, deletion retries, larger prefixes and other operations. The R2 list portion
+alone is $0.135 at marginal overage rates before provider rounding, or consumes
+included allowance when available. This is arithmetic, not measured provider usage.
+Account deletion must finish cleanup and retire alarms to end that recurring work.
+
+The byte quota includes file bytes and serialized saved metadata, but is not a
+physical SQLite/R2 invoice ceiling. Measure database/index overhead, transaction
+row counts, orphan recovery and DO duration with realistic retained inventories.
+Native job costs still dominate the earlier scenarios; these new storage operations
+must be included before treating any scenario as a launch forecast.
diff --git a/docs/plans/2026-10-06-v1-execution-goal.md b/docs/plans/2026-10-06-v1-execution-goal.md
new file mode 100644
index 00000000..895775d6
--- /dev/null
+++ b/docs/plans/2026-10-06-v1-execution-goal.md
@@ -0,0 +1,92 @@
+# 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.
+
+## 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.
diff --git a/docs/programs.md b/docs/programs.md
index 200ed863..768d2f50 100644
--- a/docs/programs.md
+++ b/docs/programs.md
@@ -87,7 +87,7 @@ and set `diffTruncated`; use source reads for the rest.
## Library use
-`createKilnProgramToolRegistry(context)` is exported from `@kiln/engine/tools` and returns the
+`createKilnProgramToolRegistry(context)` is exported from `@instruktlabs/kiln/tools` and returns the
same twelve definitions used by MCP. Inject `context.programStore`, with asynchronous
`put(code)` and `get(programRef)` methods, to share revisions between instances. Without
it, one registry instance keeps an in-memory store bounded to 64 MiB. Keep that instance
diff --git a/docs/projects-and-live-review.md b/docs/projects-and-live-review.md
index cd3376a9..220a20d7 100644
--- a/docs/projects-and-live-review.md
+++ b/docs/projects-and-live-review.md
@@ -1,6 +1,6 @@
# Projects and Live Review
-The packaged local dashboard adds shared project configuration, a material library and observation history to standalone authoring. The CLI, the stdio MCP tools `kiln_project`, `kiln_material` and `kiln_review`, and the dashboard read and write the same records. Each MCP tool takes one flat object whose `action` names the operation; the server reports the fields that action needs, and `kiln_discover({ ids: ["shape:project-draft"] })` and the other `shape:` entries return the full nested record schemas. The [foundation checkpoint](plans/2026-09-26-project-foundation.md) records how this was qualified and what production acceptance remains.
+The packaged local dashboard adds shared project configuration, a material library and observation history to standalone authoring. The CLI, the stdio MCP tools `kiln_project`, `kiln_material` and `kiln_review`, and the dashboard read and write the same records. Each MCP tool takes one flat object whose `action` names the operation; the server reports the fields that action needs, and `kiln_discover({ ids: ["shape:project-draft"] })` and the other `shape:` entries return the full nested record schemas. The [foundation checkpoint](https://github.com/instruktlabs/kiln/blob/main/docs/plans/2026-09-26-project-foundation.md) records how this was qualified and what production acceptance remains.
## One workspace across interfaces
@@ -87,8 +87,8 @@ The MCP `kiln_project` export action returns an exact revision resource URI for
## GPU connection and performance qualification
-Local development uses the shared renderer on this machine. Remote rendering is an explicit endpoint selection through `--render-port` where supported, or `KILN_RENDER_PORT_URL`; an explicit endpoint never triggers local service replacement. A URL whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) is the local service and takes the local route. CLI/MCP use the host connection resolver. Embedded callers inject a render port. Do not construct an unauthenticated raw transport after merely discovering a local service. See the [GPU integration review](plans/2026-09-26-gpu-service-integration.md) for the reproduced authentication failure, remaining credential-policy ambiguity and proposed unified connection contract.
+Local development uses the shared renderer on this machine. Remote rendering is an explicit endpoint selection through `--render-port` where supported, or `KILN_RENDER_PORT_URL`; an explicit endpoint never triggers local service replacement. A URL whose origin is exactly the shared local socket (`http://127.0.0.1:8000` by default) is the local service and takes the local route. CLI/MCP use the host connection resolver. Embedded callers inject a render port. Do not construct an unauthenticated raw transport after merely discovering a local service. See the [GPU integration review](https://github.com/instruktlabs/kiln/blob/main/docs/plans/2026-09-26-gpu-service-integration.md) for the reproduced authentication failure, remaining credential-policy ambiguity and proposed unified connection contract.
Use `--render gpu` for required GPU image qualification. `auto` can use the CPU for untextured nonmetallic scenes or degrade when a GPU view is unavailable, with explicit fidelity metadata; `cpu` is an offline diagnostic mode. The interactive viewport and recorded image are different render paths. GPU output is appearance evidence, not structural QA authority.
-The dashboard's Measure control records a bounded browser sample: load to first render submission, frame intervals, draw/geometry/texture counts, viewport, DPR and available adapter identity. Frame intervals are not GPU execution times; texture counts are not memory bytes. The [controlled foundation review](reviews/2026-09-26-foundation-performance.md) records exact technical fixtures, actual panel dimensions, installed identities and ambient workload separately from earlier busy-machine observations. A future pack's real proving scene needs its own measurements before accepting a game performance budget. Record exact artifacts, browser/backend, adapter/driver, canvas size/DPR, thermal/power conditions, concurrent workload, cold/warm repetitions and any profiler overhead.
+The dashboard's Measure control records a bounded browser sample: load to first render submission, frame intervals, draw/geometry/texture counts, viewport, DPR and available adapter identity. Frame intervals are not GPU execution times; texture counts are not memory bytes. The [controlled foundation review](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-26-foundation-performance.md) records exact technical fixtures, actual panel dimensions, installed identities and ambient workload separately from earlier busy-machine observations. A future pack's real proving scene needs its own measurements before accepting a game performance budget. Record exact artifacts, browser/backend, adapter/driver, canvas size/DPR, thermal/power conditions, concurrent workload, cold/warm repetitions and any profiler overhead.
diff --git a/docs/releasing.md b/docs/releasing.md
new file mode 100644
index 00000000..5d1c45c1
--- /dev/null
+++ b/docs/releasing.md
@@ -0,0 +1,128 @@
+# Publishing Kiln 1.0
+
+This is the maintainer runbook for `@instruktlabs/kiln`. The release workflow is
+prepared; it has not published a package. 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.
+
+## Qualify the candidate
+
+1. Complete the release contract, consumer documentation, notices and changelog.
+ Align `package.json`, engine metadata and plugin manifests to `1.0.0-rc.N` or
+ `1.0.0`, then rebuild the runtime. A version change creates a new candidate.
+2. Review the changes and obtain authorization to merge. After merging, wait for
+ **every** job in `.github/workflows/ci.yml` to pass on that exact main commit.
+ PR receipts are useful during development but cannot authorize a release.
+3. Download `node-package-candidate` from that run and record the archive SHA-256.
+ Do not repack it. CI installs this same archive on Windows, macOS arm64/x64 and
+ the Linux Node matrix, checks consumer declarations and executes software Vulkan.
+4. Dispatch **Prepare npm release** from main, with the CI run ID, reviewed digest
+ and mode **verify**. The workflow checks repository identity, commit, job results,
+ archive contents and every required receipt. Development versions, missing or
+ expired artifacts, digest drift and skipped checks fail. This mode has no npm
+ publishing access. Download its `npm-release-review` artifact for review.
+
+The dispatch commit must equal the CI commit. If main moves before dispatch,
+qualify its new candidate instead. Qualification artifacts expire; if necessary,
+rerun CI and review its newly produced archive and digest. Never substitute a local
+rebuild. The [preparation script](../scripts/prepare-npm-release.mjs) and its tests
+define the required matrix; update them together with any intentional CI change.
+
+## Establish publishing access
+
+Reuse the existing `instruktlabs` npm organization and the owner's verified
+`matthew-kissinger` account. Passwords and security-key challenges belong in npm's
+browser flow. Keep recovery material outside the repository and logs. A local npm
+login is needed for owner review/promotion; CI will use short-lived OIDC credentials.
+
+Configure GitHub environment **npm-release** with the sole required reviewer
+`matthew-kissinger`, administrator bypass disabled, and deployments restricted to
+protected branches. Keep owner self-review available: this repository's owner may
+both dispatch and approve a release. The workflow itself restricts execution to
+main. Verify these settings before dispatching mode **stage**; the script refuses
+an unprotected environment rather than accepting an implicit environment creation.
+
+This GitHub environment was created and read back on 6 October 2026 with the
+settings above; see the execution record. Recheck it before staging. npm trusted
+publishing is not configured yet, and creating the environment published nothing.
+
+First-time npm staging creates a public `0.0.0-stage` placeholder. It therefore
+requires explicit authorization against the reviewed candidate. The staged code
+stays private until promotion. Do not stage a dummy package to reserve the name.
+Source: [npm staged publishing](https://docs.npmjs.com/staged-publishing/).
+
+If npm still requires an existing package before adding its trusted publisher,
+bootstrap using the **qualified RC archive** and the owner's local login:
+
+```sh
+npm stage publish /absolute/path/to/instruktlabs-kiln-1.0.0-rc.N.tgz --ignore-scripts --access public --provenance=false --tag next --registry=https://registry.npmjs.org --json
+```
+
+This is an external write, not a dry run. Retain its `stageId`; do not approve this
+bootstrap stage. The explicit provenance override is only for local bootstrap,
+which cannot issue a GitHub build attestation. npm 12.2.0 gives explicit CLI flags
+precedence over `publishConfig`. After configuring trust, reject the bootstrap by
+stage ID with owner 2FA before CI stages the same version. Do not overwrite a stage
+or reuse a published version. If npm provides a supported package-free trust setup
+at execution time, prefer that and record the actual path used.
+
+In npm's package settings, bind a GitHub trusted publisher to:
+
+| Field | Value |
+| --- | --- |
+| Owner | `instruktlabs` |
+| Repository | `kiln` |
+| Workflow filename | `release.yml` |
+| Environment | `npm-release` |
+| Permission | `npm stage publish` only |
+
+Leave direct publishing and dist-tag management disabled. Require package 2FA and
+disallow token publishing; do not add an `NPM_TOKEN` secret. Configure trust shortly
+before use because unvalidated configurations expire after 48 hours. Verify the
+first successful OIDC stage rather than treating saved settings as proof.
+Sources: [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/),
+[trust configuration expiry](https://github.blog/changelog/2026-10-02-unvalidated-npm-trusted-publishing-configurations-now-expire/).
+
+## Stage and promote
+
+Dispatch the same reviewed candidate with mode **stage**. Review the verification
+artifact, then approve the GitHub environment. The second job downloads and checks
+the original CI artifacts again before staging the exact tarball. It does not
+install package dependencies, rebuild the package, or execute its lifecycle scripts.
+RC versions use `next`; `1.0.0` uses `latest`. The job retains `npm-stage.json` and the
+full candidate evidence in `npm-staged-candidate`.
+
+On a logged-in maintainer machine, use the returned **stage ID**:
+
+```sh
+npm stage view STAGE_ID --json
+npm stage download STAGE_ID --json
+```
+
+Compare the downloaded archive's SHA-256 with `review.json` and inspect package,
+version, tag, contents and provenance. If a staging command times out, inspect the
+stage list before retrying; a missing response does not prove nothing was staged.
+Reject an incorrect stage. Only after owner approval and its browser 2FA:
+
+```sh
+npm stage approve STAGE_ID
+```
+
+The workflow never approves stages. npm makes this an owner action, and staged
+tags cannot be changed in place. Source: [npm stage CLI](https://docs.npmjs.com/cli/v12/commands/npm-stage/).
+
+## Verify publication and recover
+
+Read the public registry metadata and independently fetch the published archive;
+compare its digest with the approved candidate. Run clean registry installs on the
+supported platform matrix and exercise SDK, CLI, MCP, workspace setup/upgrade and
+local plugin flows. Verify the public provenance statement's repository, workflow
+and commit. Retain registry URL, version/tag, digest, run IDs, installed receipts
+and the owner's approval. Create the approved GitHub release/tag with matching
+notes and archive identity only after these checks.
+
+Publication failure does not authorize a rebuild under an existing version. Before
+promotion, reject and replace an incorrect stage. After publication, stop rollout
+and prepare a newly versioned correction; consider deprecation or tag changes only
+with explicit approval. Do not assume npm unpublish is available or an appropriate
+rollback. Hosted rollback and vendor review remain independently tracked.
diff --git a/docs/reviews/2026-10-06-publisher-setup.md b/docs/reviews/2026-10-06-publisher-setup.md
new file mode 100644
index 00000000..2161b2d7
--- /dev/null
+++ b/docs/reviews/2026-10-06-publisher-setup.md
@@ -0,0 +1,121 @@
+# Kiln publisher setup, 6 October 2026
+
+The owner explicitly requested the repository transfer and npm setup before starting
+the full v1 implementation goal. No engine changes, package publication or hosting
+purchase were performed by these setup actions.
+
+## Native GitHub transfer
+
+Destination: [instruktlabs/kiln](https://github.com/instruktlabs/kiln).
+GitHub's native transfer operation moved the existing repository; it was not copied
+or recreated. The local `origin` URL was updated to the destination.
+
+| Property | Before | After |
+| --- | --- | --- |
+| Repository ID | `1278326592` | Same |
+| GraphQL node ID | `R_kgDOTDG3QA` | Same |
+| Stars | 233 | 233, same stargazer identities |
+| Watchers | 2 | 2, same identities |
+| Forks | 18 | 18, same repository identities |
+| Open PRs | #140, #141, #142 | Same IDs, authors, bodies, states, head/base refs and reviews |
+| Open issue | #134 | Same ID, body, state and owner assignment |
+| All issue/PR records | 144, including 143 PRs | Exact projected record comparison passed |
+| Issue comments | 8 | Same IDs and contents |
+| Tags and releases | 5 of each | Same refs, release IDs, metadata and assets |
+| Main SHA | `65ce2f815a70ca3bdf8ad4fa1f8bf52d5fd08581` | Same |
+| Main protection | Eight required checks, strict updates, admin enforcement and other existing settings | Preserved |
+| Personal profile pin | Kiln pinned | Same pinned node, now `instruktlabs/kiln` |
+
+Old repository, issue #134, PR #140 and v0.10.0 release URLs were tested and redirect
+to the organization URLs. Git access through the old URL returns the same HEAD,
+main and tag refs. Pages was disabled before and after. No outside contribution was
+triaged, closed, merged or rewritten. Existing collaborators, environments, hook,
+deploy-key and secret-name inventories match; no secret values were read.
+
+Initial post-transfer stargazer/watcher reads returned temporary 404s. A subsequent
+complete snapshot passed without API errors and matched every captured identity.
+
+## Actions policy compatibility
+
+The destination organization requires full commit-SHA pins and permits selected
+Actions. It initially allowed only GitHub-owned Actions, excluding Kiln's existing
+Bun setup action. The owner explicitly approved adding only
+`oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6` (upstream v2.2.0).
+
+That exact allowlist entry is now applied and effective for Kiln. Mandatory SHA
+pins, GitHub-owned actions and the other organization restrictions remain in place.
+The stricter inherited policy explains the only settings difference in the
+before/after audit. This was an organization-wide setting, disclosed to the owner.
+
+The existing Linux `typecheck · lint · test` job from
+[CI run 37410749192](https://github.com/instruktlabs/kiln/actions/runs/37410749192)
+was rerun under the new ownership to verify operational continuity. Attempt 2 and
+the new Linux job `112124711993` passed on the unchanged SHA. This reran the Linux
+job, including toolchain setup, tests/coverage and exporter qualification; the other
+previously successful platform jobs were not represented as newly executed.
+
+## npm handoff
+
+The local CLI had no authenticated npm account. The owner asked to use
+`[email protected]`, an alias to their personal inbox. The signup form was
+prepared with that business email and suggested personal username
+`matthew-kissinger`; the organization will be `instruktlabs` separately.
+
+The owner completed account creation and confirmed email verification. The agent
+created the free public-package organization `instruktlabs`; npm displayed its success
+message and the member list verified `matthew-kissinger` as the sole owner. The scope
+is secured. No invitation or paid npm subscription was created.
+
+The owner enrolled two security keys, reporting one on the PC and one on the phone.
+The npm key list confirms two registrations and 2FA required for write actions.
+Organization-wide 2FA enforcement is enabled; npm confirms one enabled member, no
+disabled members and no removals. No package has been published. Configure package
+publishing trust when an authorized reviewed bootstrap exists.
+
+At the owner's explicit request, a one-use, loopback-only helper was prepared to save
+the recovery codes using Windows DPAPI CurrentUser and restrictive Windows file
+permissions. The browser tools' virtual clipboard was empty. The local form failed,
+and Notepad could not open the prepared restricted paths. The owner saved the codes
+manually and supplied the exact file path in OneDrive Documents. The helper then
+encrypted that file and verified both the in-memory and persisted round trips.
+The encrypted file exists at
+`%LOCALAPPDATA%/Instrukt Labs/Kiln/Secrets/npm-recovery-20261006-055937-d35c8c23.dpapi`.
+The staging plaintext was removed and its absence verified. OneDrive recovery or
+synced copies were not inspected or purged. This backup requires the original
+Windows account's DPAPI keys; it is not an independent disaster-recovery copy.
+No code contents were printed or added to the repository. Browser account setup
+is complete; local npm CLI login remains unconfigured until publishing requires it.
+
+Automatic approval review blocked an earlier cleanup command for the two empty
+helper staging files and synthetic test backup, reporting only "blocked by policy."
+Those harmless helper artifacts remain. The separately verified owner plaintext
+file was subsequently removed successfully.
+
+## Cloudflare subscription
+
+The owner explicitly authorized Workers Paid at its current $5/month subscription
+price if not already active. After the owner signed in, the Subscriptions dashboard
+confirmed **Workers Paid: Active** and **R2 Paid: Active**, both renewing on
+20 October 2026. No purchase or account upgrade was needed or performed.
+
+The Billable usage dashboard showed $0.00 in usage charges for the current cycle,
+with all observed usage within included tier limits. This excludes the subscription
+base charge and is not a forecast for Kiln's future workload. Allowances are shared
+with the account's existing applications. An auto-created $10 budget alert already
+exists with one recipient; it was inspected without changes. This is a notification,
+not a hard spending cap. Native Container
+qualification, Kiln-specific resources and deployment remain implementation work.
+This developer subscription is separate from a domain Pro/Business plan.
+
+## Evidence and remaining work
+
+Full local snapshots and scripts:
+`C:/Users/Mattm/X/kiln-dogfood/publisher-setup-2026-10-06/`.
+This is a scratch evidence directory, not the engine checkout or release workspace.
+All release planning documents and future engine changes belong in `kiln-oss`.
+Key receipts: `before.json`, `after.json`, `comparison.json`,
+`actions-policy-final.json`. These are outside the installable engine checkout.
+
+Repository content links, metadata and final plugin/npm trust bindings will be
+updated during the v1 implementation cycle; old GitHub URLs currently redirect.
+This record does not prove native Cloudflare execution or npm release qualification.
diff --git a/docs/reviews/2026-10-06-v1-execution.md b/docs/reviews/2026-10-06-v1-execution.md
new file mode 100644
index 00000000..8e46c574
--- /dev/null
+++ b/docs/reviews/2026-10-06-v1-execution.md
@@ -0,0 +1,1153 @@
+# Kiln 1.0 execution record
+
+Started 6 October 2026 by the owner's active goal. Working checkout:
+`C:/Users/Mattm/X/kiln-oss`, branch `codex/v1-publication`, initial source
+`65ce2f815a70ca3bdf8ad4fa1f8bf52d5fd08581`.
+
+The [publication plan](../plans/2026-10-05-v1-publication-plan.md) defines scope;
+[hosting economics](../plans/2026-10-06-hosting-economics.md) records assumptions.
+This record tracks evidence, not release acceptance by implication. Community
+contributions remain outside this cycle. No package or production service is
+published yet.
+
+## Deliverables and evidence
+
+| ID | Requirement | State and required proof |
+| --- | --- | --- |
+| P0 | Preserve publisher/repository setup | Complete in [publisher setup receipt](2026-10-06-publisher-setup.md); current checkout remote verified `instruktlabs/kiln` |
+| P1 | Public API, stability and migrations | In progress: all 55 public entrypoints classified in the SDK guide, experimental/re-export and deprecated-alias boundaries explicit, Discovery labels visible; final release freeze and target-version upgrade proof remain open |
+| P2 | Compiled ESM SDK and declarations | In progress: corrected 53-entry core qualification includes dependency-free arena; all 55 imports/declarations pass in fresh optional-peer installations at current and declared-minimum versions; final-version and platform evidence remain open |
+| P3 | Package identity, contents, executables and notices | In progress: unpublished `@instruktlabs/[email protected]`, aligned engine/plugin identities, MCP launcher, consumer doc allowlist and dependency notices; fresh RC archive checks pass locally, final release audit remains open |
+| P4 | Clean installs and workspace upgrades | In progress: RC package passed all platform CI jobs; official 0.10.0-to-RC upgrades pass for Claude/Codex workspaces with conflict refusal, reapplied customizations and byte-exact old assets; final-version harness checks remain open |
+| P5 | Release automation and npm publication | In progress: manual exact-archive workflow and owner runbook; GitHub npm-release environment created with sole owner review, no admin bypass and protected branches; live npm trust, staging approval, registry provenance and fresh registry install remain open |
+| H1 | Native Cloudflare qualification | In progress: Linux image built, Trixie software renderer passes six textured views; Docker namespace probe fails closed, Bubblewrap launch-argument defect corrected; real Cloudflare isolation/execution, RSS, startup and measured cost remain pending |
+| H2 | Authenticated MCP and tenant boundary | In progress: Google and GitHub selected with one Kiln account; existing GitHub-only OAuth and native HTTP pass local two-user, storage and reconnect checks; provider-neutral account storage, Google/linking, branded real sign-in, container dispatch and evaluator isolation remain open |
+| H3 | Artifact lifecycle | In progress: tenant SQLite/R2 bytes, ProgramStore and native AssetLibrary, atomic quotas/revision pins, material closures, authenticated downloads, deletion and seven-day unsaved retention pass local workerd and actual-engine checks; standalone MaterialLibrary, native dispatch, browser tickets, account deletion and deployed lifecycle proof remain open |
+| H4 | Capacity and operations | In progress: local native request admission, body/response/deadline bounds and cancellation pass; global operational quotas, process cleanup, load/cost measurements, alerts, deployed health/build identity and rollback remain open |
+| H5 | Production deployment | Pending: approved deployment at `kiln.instruktlabs.com`; live authenticated create/edit/render/save/download/reconnect flow |
+| L1 | Local Claude Code and Codex plugins | In progress: both remote Git catalogs and real versioned caches qualified; actual development-to-RC plugin updates preserve pinned workspaces until explicit runtime upgrade, saved assets remain byte-exact and native clients discover one server; final registry/tag distribution and final-version upgrade remain open |
+| L2 | Public OpenAI plugin | Pending: compliant ZIP, verified publisher/domain, working MCP, privacy/support pages, review cases/video/account, submission receipt |
+| L3 | Anthropic directory | Pending: owned marketplace publication, final source path, account eligibility, reviewer materials and submission receipt |
+| V1 | Exact candidate verification | In progress: development builds have pinned local and CI evidence; final RC/version archive and target-host flows remain open |
+| V2 | Release documentation and receipts | Pending: changelog/migrations/install/support/security/privacy/runbook; exact commits, hashes, versions, URLs and separate vendor-review state |
+
+## Execution notes
+
+- Created `codex/v1-publication` from the current main checkout without altering
+ the four existing untracked planning/setup documents.
+- Confirmed Bun 1.4.2 is installed. Default shell Node/npm differ from maintainer
+ pins; use the installed Node 22.23.3 environment for release gates.
+- First implementation target is the SDK build and installed-consumer contract.
+ Current exports point at TypeScript and the package root is the CLI, so a plain
+ Node consumer cannot use the promised library without a source loader.
+
+### Compiled SDK foundation
+
+The development package now emits ESM and declarations for all 55 public entrypoints.
+The root is a library entry, and compiled modules resolve explicit Node paths.
+Worker and viewer resource lookup support the compiled layout. Core tool types no
+longer pull optional Strands declarations into ordinary host consumers. The
+[SDK reference](../sdk.md) records the intended contract and its limits.
+
+Verified locally with Bun 1.4.2, Node 22.23.3 and npm 12.2.0:
+
+- Unit suite: 3,191 passed, two platform skips, no failures (404 files).
+- Toolchain, skill alignment, typechecking and lint passed.
+- Render service: 78 tests passed, no failures.
+- Fresh npm tarball installation: 20 checks passed, including all 52 core SDK
+ imports and TypeScript declarations without optional agent peers; real SDK
+ subprocess rendering; CLI/MCP source edits, persistence and exact exports;
+ native/WASM helpers, CPU PNG and textured community export.
+- All 55 SDK imports also passed with optional peers installed in the development
+ checkout. This does not replace clean optional-workflow qualification.
+- Coverage initially counted both `src/` and its generated `lib/` copy. Excluding
+ the generated copy restores the existing source measurement without lowering
+ thresholds: functions 95.20% (minimum 94.00%), lines 92.52% (minimum 92.10%).
+ The corrected full coverage run had one Windows `EPERM` during an atomic asset
+ directory rename in `packaged-save-provenance.test.ts`; its focused rerun passed
+ all nine tests. Record this as a full-run failure followed by a passing focused
+ rerun, not an entirely green coverage run. CI remains required.
+
+Local development tarball SHA-256:
+`48b633bd9ca6ad3399548d711ec8a06aee6f992e98c3606711a48c3eddbbc23d`.
+Receipt: `.cache/v1-package-smoke-types.log`. This archive still uses the previous
+private `@kiln/[email protected]` identity; it is not a release candidate or npm
+publication. The package identity change is a separate tracked step.
+
+CI now checks installed consumer declarations against the exact tarball distributed
+to its Windows, Linux and macOS jobs. Full cross-platform qualification remains open.
+The foundation was committed as `ea56ccdf10052a869b64280f64de1267a0261da8`
+and pushed to the approved branch. [Draft PR #145](https://github.com/instruktlabs/kiln/pull/145)
+started [CI run 37425306532](https://github.com/instruktlabs/kiln/actions/runs/37425306532).
+That run completed with the portable package build, Linux consumer matrix, Windows
+package installation, render-service tests and software Vulkan checks passing.
+The separate website workflow also passed. Two defects prevented an all-green run:
+
+- macOS ARM64/x64 package assertions compared the `/var` temporary-directory alias
+ with Node's canonical `/private/var` module URL. The smoke check now canonicalizes
+ its temporary root; the Windows package rerun passes with that correction.
+- Both engine-check jobs rejected the enlarged agent guide: 12,441 bytes exceeded
+ the 12,288-byte repository budget. Condensing its wording preserves the instructions
+ at 12,235 bytes; the focused repository-contract tests pass.
+
+Both fixes passed in the next commit's CI run, recorded below. Passing adjacent jobs
+in the original failed run did not qualify them.
+At that foundation commit, the isolated evaluator still located source TypeScript
+workers. The correction and its separate qualification are recorded below.
+
+### Public package identity and installed commands
+
+The next slice adopts `@instruktlabs/kiln` with the explicitly unpublished version
+`1.0.0-dev.0`. Package, engine and plugin versions stay aligned. Public repository,
+support and publish metadata point at Instrukt Labs; maintained SDK examples and
+runtime identity checks use the new scope. Historical planning/release records keep
+their original names and versions.
+
+The archive's documentation now uses a 21-file consumer allowlist instead of the
+whole research/planning tree. The new `kiln-mcp` executable points to the existing
+thin Node MCP entry. Package smoke checks exercise that command through npm, and
+inspect the installed documentation even when CI supplies a prepacked archive.
+Receipt verification now requires the chosen package name and SDK/documentation/
+MCP-command checks. Negative fixtures first demonstrated the old verifier accepting
+missing evidence; the updated focused suite passes.
+
+The Windows dependency-notice inventory was refreshed against installed manifests
+and native-library metadata. This does not qualify the native binary inventory on
+other platforms. Thirty links from consumer documents to excluded repository files
+now point to GitHub source pages. The installed-document check first rejected the
+previous archive for a broken link, then passed after rebuilding it.
+
+Pinned local results for this slice:
+
+- Toolchain, skill alignment, typechecking and lint pass.
+- Fresh npm installation: all 22 checks pass, including 52 core SDK imports and
+ declarations, subprocess rendering, installed document links, all three npm
+ executables, source edits and persistence. Receipt verification accepts its
+ package name/version, runtime and archive digest.
+- Archive inventory: 922 files, 21 consumer documents, no planning/review/evaluation
+ records or test files. Receipt: `.cache/v1-namespace-package-final.log`.
+- Final development archive SHA-256:
+ `ff8a1863ab54e6875092a4a5dc9319b429b4496beb90dd5140cb1cbcb93818fd`.
+- Full offline coverage run: 3,195 pass, two platform skips, one failure in 404 files.
+ The same Windows `EPERM` at the immutable asset-revision directory rename
+ recurred in `packaged-save-provenance.test.ts`. This is now a reproducible release
+ concern, not closed by the prior focused rerun. A bounded atomic-save correction
+ and another full gate are required.
+- The separately checked LCOV thresholds still pass at 95.20% functions and 92.52%
+ lines. This does not make the failed full run green.
+
+Committed as `c7c578ee5bde6928ee78a1a70eeff23782ace458` and pushed to the approved
+branch. [CI run 37427644449](https://github.com/instruktlabs/kiln/actions/runs/37427644449)
+completed successfully, including Linux/Windows engine checks, every package
+platform job, both macOS architectures and software Vulkan. Downloaded platform and producer receipts all match
+the same CI tarball SHA-256:
+`68795af7d2641dd2723d99a3d937ef45dcbe24c299344f990644879dcc561047`.
+The producer reports 22 checks including consumer types; each downstream platform
+reports 21 checks because it does not install the TypeScript qualification toolchain.
+These receipts qualify this commit, not the following runtime corrections.
+
+### Atomic saves and compiled isolated workers
+
+Focused regressions first demonstrated both defects: transient Windows rename
+denials aborted saves, and the SDK build omitted workers reached only through URLs.
+The save path now retries Windows `EPERM`/`EACCES`/`EBUSY` only when the destination
+is absent, with a total delay budget of 770 ms. Existing destinations and other
+errors return to the existing immutable-import handling. The operation remains an
+atomic rename; it never deletes or copies over a destination. All 24 focused atomic,
+asset-library and packaged-save tests pass.
+
+The SDK build now includes the evaluator, readiness and transport worker entryfiles.
+Source, installed SDK and executable-bundle paths resolve their corresponding
+workers; installed JavaScript uses Node directly without `tsx`. Existing namespace,
+environment, filesystem/network and resource-limit controls remain mandatory.
+Package tests execute a trusted fixture through the actual installed compiled
+worker; this does not run or qualify the OS isolation boundary.
+
+Typecheck/lint and all 23 fresh-install checks pass, including consumer types and
+the compiled worker. Receipt: `.cache/v1-runtime-fixes-package.log`.
+Development tarball SHA-256:
+`f0511c21b1e1857a9a22a039a78b0da88253880e8043eab3cdaa5f0ecfbad0ec`.
+The corrected full offline coverage run passes: 3,210 tests, two platform skips,
+zero failures in 406 files; functions 95.20% and lines 92.52%, above the unchanged
+94.00%/92.10% thresholds. The previously failing packaged-save case passes in the
+full run. Receipt: `.cache/v1-runtime-fixes-coverage.log`.
+Committed and pushed as `ee7ecc9daa2d58bb7cb11a546b2d62225c7fdb04`.
+[CI run 37428983292](https://github.com/instruktlabs/kiln/actions/runs/37428983292)
+completed successfully for that exact head, including all twelve engine, package
+and render-service jobs. This qualifies the development commit; no RC or final
+registry release has been produced.
+Downloaded all seven package receipts and the software-renderer artifact. Every
+package receipt and the renderer checksum identify the same CI archive SHA-256:
+`1c85bca5f66d419fab3c77612d5aada070a8b311eb6dee1e17fecc578c642976`.
+The producer reports 23 checks (including consumer types); downstream platforms
+report 22. Retained locally in `.cache/v1-ci-ee7ecc9/`.
+
+### Exact-archive release workflow
+
+Added `.github/workflows/release.yml`, a manual workflow with a read-only default.
+Its preparation script requires a successful main push at the dispatch commit,
+the original repository ID, all twelve required jobs, eight retained artifact sets,
+one reviewed archive digest, platform/SDK/type receipts and hashed software-renderer
+views. Development versions and PR qualification runs are rejected. The optional
+stage job uses the protected `npm-release` environment, repeats verification after
+approval, and stages the unchanged archive through OIDC. It never promotes a stage.
+
+Focused tests first failed on the missing workflow, then passed with it; the
+metadata and artifact regressions include missing/expired/foreign receipts,
+unprotected environments and changed bytes. All 31 focused tests, typecheck and
+lint pass. The full offline unit suite passes: 3,241 tests, two platform skips,
+zero failures in 407 files; receipt `.cache/v1-release-workflow-tests.log`.
+This changes release tooling and documentation, not engine behavior; the prior
+runtime coverage receipt remains separate. CI against this slice is still required.
+The [maintainer runbook](../releasing.md) records first-package bootstrap, its
+public-placeholder side effect, trust setup, exact stage-ID review, human 2FA
+promotion and post-publication verification. No environment configuration, npm
+stage, placeholder or release has been created by this workflow preparation.
+Committed and pushed as `3e83a9cf9f54a3e94314a11fb9e05851683d9eb2`.
+[CI run 37431427439](https://github.com/instruktlabs/kiln/actions/runs/37431427439)
+is checking this exact release-tooling commit. The separate Website workflow on
+the preceding runtime commit failed a stale migration-heading link; its engine
+CI passed. The link correction is part of the following slice, not retroactive
+website acceptance.
+
+### Discovery stability at the model boundary
+
+Added failing tests for experimental operations/recipes, stable helpers and a
+deprecated catalog fixture, including the text adapter used by both agent skins.
+Search and overview now show the existing stability value before each summary's
+execution mode and limitations. This adds no opt-in requirement, changes no
+tool input schema, and does not relabel helpers used by experimental recipes.
+All 91 focused Discovery/context tests and 52 release-receipt tests pass.
+
+Rebuilt the compiled SDK and runtime bundles. The clean installed archive passes
+24 checks, including actual CLI and stdio MCP calls for stable helpers, implicit
+modeling and an experimental recipe. Its receipt is
+`.cache/v1-discovery-labels-package.log`; SHA-256:
+`77ddc78367a4a35a55236786b5542f9c5f313b3189ea59f91be1f0429f89506f`.
+The first smoke attempt had a new test-harness assertion treating its string result
+as an object; correcting that assertion produced the passing fresh-install run.
+Release receipt verification now requires `discovery-stability-labels` explicitly.
+Typecheck/lint pass. Full offline coverage passes: 3,245 tests, two platform skips,
+zero failures in 407 files; functions 95.20% and lines 92.52%, above unchanged
+thresholds. Receipt: `.cache/v1-discovery-labels-coverage.log`. This slice still
+needs its own exact-head CI before qualification.
+
+Corrected `docs/runtime.md` to link to the current 1.0 migration heading. Rendering
+the target document through the installed Astro Markdown processor confirms that
+the fragment exists. The complete Website CI still needs to verify the next head.
+
+### Local plugin packaging preflight
+
+Current official OpenAI documentation recommends a portable root `plugin.json`
+and `mcp.json`; `.codex-plugin/plugin.json` remains a supported fallback. Public
+submission still needs its direct remote MCP endpoint, separate from local plugin
+distribution. Source: [OpenAI packaging](https://developers.openai.com/plugins/build/plugins).
+
+Claude's strict marketplace validation passes, but explicitly validating the current
+root plugin fails strict mode because root `CLAUDE.md` is not loaded as plugin
+context. This is another reason to ship the planned small plugin directory instead
+of the engine checkout. Claude's loading rules also distinguish local-path plugins
+(loaded in place, without dependency installation) from copied marketplace plugins
+(cached with eligible dependency installation). Qualification must test the copied
+installation, and durable workspace/runtime state must not live in a removable
+plugin-version directory. Sources: [Claude publishing](https://code.claude.com/docs/en/plugins/publish),
+[loading rules](https://code.claude.com/docs/en/plugins/loading).
+No local plugin installation or directory candidate is qualified by these checks.
+
+### Verified Discovery candidate
+
+Commit `4ea07c62ef13f518f1ff15b32d0c7d7d33bf451a` completed all twelve jobs in
+[CI run 37432619561](https://github.com/instruktlabs/kiln/actions/runs/37432619561)
+successfully, including Windows and Linux engine tests, both macOS architectures,
+the consumer Node matrix and installed Linux software Vulkan. The separate
+[Website run 37432619572](https://github.com/instruktlabs/kiln/actions/runs/37432619572)
+also passed. This qualifies the development candidate's checks, not a published
+1.0.0 or the subsequent plugin bootstrap changes.
+
+### Local plugin workspace bootstrap
+
+Added `scripts/setup-plugin-workspace.mjs` as a standalone helper for the planned
+small local plugin. It pins `@instruktlabs/kiln` to an exact version, installs with
+optional dependencies and lifecycle scripts disabled, and keeps the installation
+in a persistent version directory outside the plugin cache and asset workspace.
+The existing engine generator remains the owner of `kiln_workspace` configuration,
+skill selection and conflict-preserving check/upgrade/repair. The planned plugin
+does not also start a global authoring MCP server.
+
+The helper verifies package identity and its dependency lock before reuse,
+refuses unknown existing runtime directories, checks canonical path separation,
+and serializes setup through an exclusive lock. An explicit qualification archive
+is bound to its SHA-256; different bytes with the same version require a separate
+data directory. No cleanup replaces an existing runtime or user workspace.
+
+The initial fifteen focused tests failed against the stub, then passed after
+implementation. Additional checks found and fixed a CLI exit-status mismatch:
+workspace checks report `status`, rather than a `current` boolean. A redirected
+`runtimes` directory also exposed a pre-install path-validation gap; the helper now
+rejects it before npm runs. All 23 focused tests pass, covering drift, interrupted
+setup, path aliases, dependency-lock changes, conflicting setup, argument validation
+and immutable candidate reuse.
+
+A separate local probe installed the actual development archive with SHA-256
+`77ddc78367a4a35a55236786b5542f9c5f313b3189ea59f91be1f0429f89506f` under
+Node 22.23.3 on Windows. All ten checks passed: both harness workspace layouts,
+one configured workspace MCP server, check/upgrade, CPU GLB rendering and working
+CLI discovery after the plugin directory was relocated. Receipt:
+`.cache/v1-local-plugin-setup-receipt.json`. This tests the copied helper against
+the installed engine; it does not yet prove an actual Claude or Codex marketplace
+cache installation, a live harness connection, or a published plugin.
+
+Typecheck and lint pass. The full offline unit run passed 3,267 tests with two
+platform skips and no failures across 408 files
+(`.cache/v1-plugin-bootstrap-tests.log`). That run started before the final
+redirected-store guard was added; the final helper's separate 23-test run and
+repeated ten-check installed-archive probe pass. Exact-head CI is still required
+for this implementation slice. Engine source and its coverage thresholds did not
+change.
+
+### Small local plugin bundle and owned catalogs
+
+Added `plugins/kiln-engine`, generated from the engine version, the standalone
+bootstrap and the maintained setup skill with its new plugin reference. It has a
+portable root manifest, a Claude manifest and a hash inventory. Both owned catalogs
+use `instruktlabs` and select this subdirectory. No engine implementation, examples,
+dependencies or assets are present in the cached bundle. The plugin registers only
+setup; the workspace supplies author/refine/QA skills and its one authoring MCP
+server. This implements the plan's pinned local launcher through managed workspace
+configuration instead of also declaring a global server.
+
+Updated the maintained skill and its two registered copies. The new reference
+explains persistent runtime locations, exact archive qualification, existing
+workspace reuse and conflict-preserving upgrades. The install/migration guides
+document the `kiln@kiln` transition and clearly mark the v1 release commands as
+unavailable until the release tag and npm package exist. The hosted public OpenAI
+candidate remains separate and will require its own remote MCP connection.
+
+The initial package-generator tests failed against the stub, and package/receipt
+tests first rejected the absent bundle and missing required receipt check. The
+implemented generator refuses existing output, detects byte drift and extra
+components in check mode, and has eight passing contract tests. It is checked by
+the normal unit suite. The npm archive now includes both catalogs and their complete
+target bundle; platform smoke receipts require `local-plugin-bundle` and verify
+each inventoried file against its digest.
+
+Validation for this slice: typecheck/lint and skill alignment pass; the full offline
+suite passed 3,277 tests, two platform skips, no failures across 409 files
+(`.cache/v1-local-plugin-bundle-tests.log`). The real installed Windows archive
+passes 25 checks, including the plugin bundle, SDK declarations and CLI/MCP flows.
+Its SHA-256 is `48f1f91887e80769897f4d4324401a4c496f95e6adfeb0ce3d7ff7eacc0fa1ff`;
+receipt: `.cache/v1-local-plugin-bundle-package.log`. Documentation edits after
+that archive still need the next exact-head CI archive.
+
+Claude's strict plugin and marketplace manifest validation reports no warnings or
+errors. Codex CLI 0.160.0 installed and enabled the portable plugin from the local
+catalog into an isolated profile's real versioned cache. Receipt:
+`.cache/v1-codex-local-plugin-install.json`. That isolated temporary profile emitted
+a helper-PATH warning; plugin installation succeeded, but this alone is not a live
+authoring-session qualification. The next probe uses a non-temporary isolated
+profile and the Git-backed marketplace, with no normal-profile mutation or model
+calls. Claude's local-path mode is loaded in place, so its copied cache must be
+qualified with a Git-backed source.
+
+Current primary references: [OpenAI portable packaging and marketplace sources](https://developers.openai.com/plugins/build/plugins),
+[Claude plugin loading](https://code.claude.com/docs/en/plugins/loading), and
+[Claude marketplace source formats](https://code.claude.com/docs/en/plugins/marketplace-reference).
+
+### Remote plugin and persistent workspace qualification
+
+Both installed harnesses fetched the Git-backed marketplace at commit
+`775491b638d978652bdba4fc688f24a6e3b7f7ab`: Claude Code 2.1.287 and Codex CLI
+0.160.0. Isolated profiles under the local application-data directory held real
+versioned plugin caches. Normal user profiles were untouched. Cached file hashes
+match the bundle inventory. Receipt: `.cache/v1-remote-plugin-install.json`.
+
+Each cached helper installed the reviewed development archive with digest
+`48f1f91887e80769897f4d4324401a4c496f95e6adfeb0ce3d7ff7eacc0fa1ff` into the shared
+persistent engine directory and created a separate authoring workspace. Twelve
+checks passed, covering native harness MCP inventory, all seventeen local tools,
+Discovery, CPU render, save, reconnect to exact retained source, workspace upgrade
+and CLI rendering. Receipt: `.cache/v1-cached-plugin-workflows.json`.
+
+Claude initially reported the expected project-server approval requirement. Its
+qualification command supplied approval for only the known fixture's
+`kiln_workspace` server through `--settings`; it then reported Connected. This
+did not approve arbitrary projects, change normal profile trust, or make the
+plugin approve itself. The user-facing installation still requires normal project
+and MCP trust. See [Claude's project-server approval rules](https://code.claude.com/docs/en/mcp#project-server-approvals-and-workspace-trust).
+
+The actual Codex app-server protocol returned one `kiln_workspace` with seventeen
+tools, engine version `1.0.0-dev.0` and no tool-discovery error. Skill inventory
+contains one each of workspace author/refine/QA plus the cached plugin's setup
+skill. No model turn was run; `runtimeStatus` is null without an active thread,
+so this receipt does not claim an active conversation connection status.
+Receipt: `.cache/v1-codex-plugin-appserver.json`.
+
+Actual CLI uninstall and reinstall passed five more checks. Claude retains
+uninstalled cache files until cleanup; after verifying uninstallation, the probe
+removed only its own retired test cache after canonical containment checks. Codex
+removed its cache itself. With each cache absent, the persistent runtime still
+served exact saved GLB, source and PNG bytes, verified by SHA-256, and its CLI read
+the source. Reinstall beside each existing workspace preserved launcher and MCP
+configuration bytes. Codex app-server discovery was repeated after reinstall and
+still returned one server and one copy of each Kiln skill. Receipt:
+`.cache/v1-plugin-removal-reinstall.json`. This is not yet an RC-to-final upgrade.
+
+The same commit passed all twelve jobs in
+[CI run 37436913727](https://github.com/instruktlabs/kiln/actions/runs/37436913727),
+including Intel macOS on its first attempt, and the separate
+[Website run 37436913674](https://github.com/instruktlabs/kiln/actions/runs/37436913674).
+Those jobs qualify their exact development archive. The local harness probe used
+the earlier archive digest above, with the same plugin/runtime bytes; it is not
+described as an installation of the CI archive or a final npm publication.
+
+### Bootstrap CI shutdown retry
+
+Bootstrap commit `41738812bc9f2b86119caec17f843473a1047c24` completed
+[CI run 37434989839](https://github.com/instruktlabs/kiln/actions/runs/37434989839)
+with eleven jobs passing initially. Intel macOS passed its installed package work
+through the npm MCP entry, then exceeded the five-second stdin-close check. The
+unchanged job rerun passed, making the run successful. This is an intermittent
+shutdown failure followed by a passing retry, not a diagnosed engine fix. The next
+smoke script retains the same bound and adds the exact launch command and captured
+stderr to any repeat failure. The final release still needs its own platform proof.
+
+### Release authorization timing
+
+Rechecked npm's current docs on 6 October. First-time staging creates a public
+`0.0.0-stage` placeholder, so it still waits for the reviewed candidate and the
+appropriate authorization. Configure trust close to the first workflow publish:
+unvalidated configurations now expire after 48 hours. Routine CI should have
+stage-only publishing access, with owner 2FA for promotion; use a permitted event
+such as `workflow_dispatch`, not `issue_comment` or `pull_request_target`.
+Sources: [staged publishing](https://docs.npmjs.com/staged-publishing/),
+[trusted publishing](https://docs.npmjs.com/trusted-publishers/),
+[October 2 trust-expiry update](https://github.blog/changelog/2026-10-02-unvalidated-npm-trusted-publishing-configurations-now-expire/).
+
+### Hosting probe preparation
+
+The new `cf` CLI (1.0.0-beta.12) runs under the pinned Node toolchain. Its read-only
+account probe found an invalid inherited API token; ignoring that token only in the
+probe process confirmed that a separate CLI login is needed. No token was printed
+or changed. Browser login does not itself establish CLI access.
+The Docker CLI is installed, but daemon/status checks timed out after starting
+Docker Desktop. No local container execution has been qualified. Neither
+local Docker nor package tests substitute for the required actual Cloudflare
+isolation and rendering probe.
+The later bounded daemon recheck also timed out; a fresh `cf auth whoami` still
+reports not logged in. The owner has been asked to finish any Docker Desktop
+startup/setup screen. No provider deployment has been attempted.
+
+### Repeatable native execution probe
+
+Added `scripts/hosting/` with a fixed one-shot runner and a non-root Dockerfile.
+It runs all ten existing engine isolation invariants before evaluating any source,
+then checks repeated isolated GLB output, a nonblank CPU preview, deadlines,
+cancellation, output limits, recovery and the existing textured software-Vulkan
+fixture. It cannot accept caller source, has no HTTP endpoint or fallback
+evaluator, and performs no provider deployment. The renderer fixture is trusted;
+its output is separate from the source-isolation evidence.
+
+All eight focused tests first failed against the stub and pass after implementation.
+Typecheck and lint pass. A real invocation against the installed development
+archive on Windows failed at the host gate with `UNSUPPORTED_HOST`, no evaluation
+and no render artifact, as required. Its receipt is
+`.cache/native-windows-negative/receipt.json`. This is negative-path qualification,
+not a passing Linux probe. The full offline suite passed 3,285 tests with two
+platform skips and no failures across 410 files in 364.88 seconds
+(`.cache/v1-native-qualification-tests.log`). No engine runtime source changed.
+Two stale consumer-guide statements about TypeScript source exports were also
+corrected to match the compiled SDK.
+
+The minimal six-file context in `.cache/native-probe-context/` uses the downloaded
+archive from CI run 37436913727. Its SHA-256
+`141a907f792beded74c7e6965b072cdfe6669c86b95d67c77b56a70c8e1f89a2` matches the
+run's installed SDK receipt. The Node 22.23.3 bookworm image index digest was read
+from Docker's registry and pinned in the Dockerfile; the final image, OS package
+inventory and resolved npm dependencies are still unqualified. The local Docker
+daemon again timed out after fifteen seconds, and `cf auth whoami` remains
+unauthenticated. No image was built, pushed or deployed.
+
+The runner records first/repeated call timings, parent-only process usage and
+available cgroup counters with explicit scope. These are not provider cold-start,
+per-job RSS, billed CPU or user-capacity claims. Its `provider` remains `unverified`;
+actual hosting proof must include a separate deployment and immutable image receipt.
+Cloudflare's [current Container API](https://developers.cloudflare.com/containers/api/durable-object-container/)
+is the preferred route for the eventual provider adapter; it does not prove nested
+namespace support. An unsupported boundary must remain a failed launch gate.
+
+Probe-preparation commit `16916d05b146d10699bb6c43b698233f981808c5` passed all
+twelve jobs in [CI run 37440387609](https://github.com/instruktlabs/kiln/actions/runs/37440387609)
+and [Website run 37440387590](https://github.com/instruktlabs/kiln/actions/runs/37440387590).
+The CI does not build or run this qualification image; passing those jobs does not
+close the provider execution gate.
+
+### SDK surface and optional-peer audit
+
+Reviewed the 55 export targets and their maintained consumer references. The SDK
+guide now classifies the root and 54 subpaths: all public entrypoints except
+`implicit` receive the stable v1 contract. The experimental exception follows
+`implicitSurface` through its `primitives` re-export; the existing experimental
+recipes and explicitly selected community exporter remain separately labeled.
+The deprecated `setApprovedTextureResolver` alias stays available, with its trusted
+host replacement documented. No existing public entry was removed or relabeled
+experimental to avoid supporting it. Final release freeze and upgrades still need
+their target-version evidence.
+
+The audit found a check omission: `/arena` is dependency-free ranking math, not an
+optional model adapter. Core smoke/type/release checks previously skipped it
+alongside `agent` and `composer/agent`. They now require 53 core entrypoints and
+exercise installed ranking behavior. Focused tests first demonstrated the omitted
+arena declaration and incomplete release count; all 33 type/release tests pass.
+The declaration checker also has an explicit `--with-agent-peers` mode for all 55
+entrypoints. The full offline run passed 3,287 tests, two platform skips and no
+failures across 411 files in 376.21 seconds. Typecheck/lint and the final focused
+tests pass; a lint-only fixture-cleanup guard placement was corrected separately.
+
+A fresh Windows development archive passed 25 package checks with 53 SDK imports
+and consumer declarations. SHA-256:
+`78aeaea9a5188466eeb2d28d1b3986ea1ea7388754ba7ef31b76c73b6a7dce7f`.
+Receipt: `.cache/v1-sdk-surface-package.json`. Later guide edits need the next
+exact-head CI archive; runtime bytes did not change.
+
+Two separate clean installations of that archive qualified the optional surface:
+
+| Install | Strands SDK | OpenRouter provider | AI SDK provider | Result |
+| --- | --- | --- | --- | --- |
+| Current maintainer family | 1.19.0 | 2.10.0 | 3.0.18 | Seven checks pass |
+| Declared peer floors | 1.18.0 | 2.10.0 | 3.0.0 | Seven checks pass |
+
+Each installation imports all 55 entrypoints, typechecks all declarations, builds
+an OpenRouter adapter without making a request, compares native tool names to the
+shared registry, invokes Discovery/render/finish against a fixed fixture, and
+invokes the composer catalog adapter. The retained GLB and canonical source
+reference are checked; no model runs or provider requests were made. An initial
+probe assertion incorrectly equated a public short reference with its canonical
+SHA reference. Correcting the assertion to verify their documented relationship
+passed without changing engine behavior. The failed assertion receipt is retained.
+
+Receipts: `.cache/v1-optional-sdk-receipt.json` and
+`.cache/v1-optional-sdk-floor-receipt.json`; the probe is
+`.cache/optional-sdk-probe.mjs`. They record installation paths, archive/dependency
+lock digests, runtime export inventories and native-tool results. These are Windows
+Node 22.23.3 package/adapter checks, not live-provider, model-quality, minimum-Node
+optional-agent or Cloudflare qualification. The installation guide now gives the
+tested optional-peer command and distinguishes it from ordinary CLI/MCP setup.
+
+### Linux image preflight
+
+Added a separate, path-filtered `Native hosting preflight` workflow. It builds the
+minimal six-file context from the exact PR head archive without publishing an
+image or deployment. The two sequential containers run with networking disabled,
+no host mounts, one CPU, 6 GiB memory, 256 PIDs, dropped capabilities and no new
+privileges. Isolation failure keeps the workflow failed; the trusted software
+fixture still runs independently to diagnose image dependencies. Artifacts retain
+archive/image identities, the installed npm lock, OS inventory, logs, container
+exit state and available probe receipts/images. Provider qualification remains
+separate, and neither the package CI contract nor runtime isolation was weakened.
+
+Local validation parsed the YAML, syntax-checked all eight shell steps with Bash,
+and passed 17 existing native-probe/repository-contract tests. The first real
+image build and execution were then performed in
+[run 37442916260](https://github.com/instruktlabs/kiln/actions/runs/37442916260)
+at `cbcaeece3db9d2884a73aeacc52fcd3fb648759a`. The image built, ran as UID 1000,
+and retained both failures: isolation `wrapper-launch` before any source execution,
+and no usable software adapter. The renderer log identifies missing Vulkan
+`shaderUniform*ArrayDynamicIndexing` support with Mesa 22.3.6 from Bookworm.
+The separate trusted fixture did build its GLB; this is not isolated evaluation.
+
+The first image ID is
+`sha256:5e248d4b7ebcf2d88a2e37495bc884c818d747e5468ee87546699da121edb120`;
+archive SHA-256 is
+`27aa75d582150473a8ffe10a0b89b20934cbffbb43587463184a1cc171038dc2`.
+Downloaded receipts are in `.cache/native-hosting-run-37442916260/`.
+The next image uses the registry-verified Node 22.23.3 Trixie digest, whose
+[Debian Mesa package](https://packages.debian.org/trixie/mesa-vulkan-drivers)
+is 25.0.7. A separate bounded namespace diagnostic records fixed command errors
+without changing the engine's failure policy or Docker restrictions. Both changes
+require a new image run. Cloudflare CLI was rechecked and is still unauthenticated.
+
+The Trixie run at `89b3e26bf6e7cea5b0e9042eaef2357697135c83`
+([37443271908](https://github.com/instruktlabs/kiln/actions/runs/37443271908))
+passed the independent software fixture with Mesa 25.0.7/LLVM 19.1.7, six textured
+128-pixel views and all material-color checks. The neutral view was also inspected.
+Its image ID is
+`sha256:ff9bbaa930cf651d0e4e8e8a19cb9b3bf9ff0f8b9818801a948645e74d5a0f62`;
+the archive digest is unchanged from the first image, isolating the OS update.
+The first two-view renderer call took 2,296.4 ms; subsequent dark/light calls took
+691.1/102.7 ms. Those are fixture-level timings on a one-CPU Docker limit, not
+Cloudflare cold-start, capacity, cost, or an optimized performance guarantee.
+
+Isolation still failed before source execution. The fixed diagnostic returned
+`Operation not permitted` for direct user-namespace creation. Bubblewrap 0.12.0
+also rejected `--disable-userns` without explicit `--unshare-user`.
+[Upstream's manual](https://github.com/containers/bubblewrap/blob/v0.12.0/bwrap.xml)
+confirms `--unshare-all` implies only `--unshare-user-try`. The engine launch now
+explicitly requires the user namespace; no restriction or readiness invariant is
+removed. This corrects argument construction but does not establish that this
+Docker host or Cloudflare allows the namespace. The diagnostic also exposed a
+measurement omission: `core_sched.force_idle_usec` contains a dot, causing the
+probe to discard the entire `cpu.stat` snapshot. Bounded snapshot capture now
+retains that kernel format.
+
+The launch regression and two cgroup tests first failed; all 18 focused tests now
+pass. Typecheck passes, and lint passes after a test-string formatting correction.
+Runtime bundles were rebuilt. The full offline suite passed 3,289 tests with two
+platform skips and no failures across 411 files in 367.79 seconds. A fresh Windows
+package passed all 25 installation checks, including the 53 core SDK imports and
+consumer declarations. Archive SHA-256:
+`a8c382e28b4d164c64628813bc4986f1ac72c9d0e6ac9b1dcd2bd3eea433a797`.
+Receipts: `.cache/v1-hosting-runtime-tests.log` and
+`.cache/v1-hosting-runtime-package.json`. The corrected Linux image needs its
+new-head CI run; these local results do not establish host namespace availability.
+
+The corrected image ran in
+[37444497913](https://github.com/instruktlabs/kiln/actions/runs/37444497913)
+at `56c3bef44ee5c50ad040ad9a780149c422c8c2b8`. Software rendering again passed
+all six views; both CPU-stat snapshots now include the dotted kernel counter.
+Bubblewrap no longer reports the missing argument and instead reports that it has
+no permission to create a namespace. Direct `unshare` also returns `Operation not
+permitted`. The default Docker host remains unqualified, with no source evaluated;
+no seccomp, capabilities or host policy was relaxed. This does not determine
+Cloudflare's behavior. Its live probe still requires authenticated provider access.
+The archive SHA-256 is
+`c0e6dc0f358c49b87ea0848d0fb77c2cc01e3b23882f791311fdce1d93dc2e93`, and image ID is
+`sha256:b4bb2b10a189b957f2403e234a8b716271d0a8d56dd3e1043ba9ebbe5ea14ebe`.
+Receipts: `.cache/native-hosting-run-37444497913/`. The separate twelve-job
+package/engine [CI run 37444496448](https://github.com/instruktlabs/kiln/actions/runs/37444496448)
+passed all twelve jobs. [Website run 37444497764](https://github.com/instruktlabs/kiln/actions/runs/37444497764)
+also passed. The native hosting workflow remains failed independently; these
+package checks do not qualify its unsupported Docker namespace boundary.
+
+### First release candidate and historical workspace upgrades
+
+Prepared the unpublished `1.0.0-rc.1` identity across the npm package, engine and
+legacy/local plugin manifests, rebuilt runtime bundles and regenerated the small
+local plugin bundle. The maintained roadmap now targets 1.0, incorporating the
+previously planned 0.11 changes. Dated release records retain their original scope.
+The hosting image workflow now also runs for package/dependency, evaluator and
+renderer changes, so a new candidate cannot silently retain an old image receipt.
+
+The fresh Windows RC archive passes all 25 installed-package checks, 53 core
+imports and consumer declarations. SHA-256:
+`6ea9b29408b99766f0636ef27f94d9edd01526c7fb45470d811f13afa3cb755b`.
+Receipt: `.cache/v1-rc1-package.json`. Fresh current-peer and declared-floor
+installations each pass all seven optional-SDK checks, including all 55 runtime
+imports/declarations, native render/finish, composer catalog and offline provider
+construction. Receipts: `.cache/v1-rc1-optional-sdk.json` and
+`.cache/v1-rc1-optional-sdk-floor.json`. No model requests were made.
+The full RC suite passed 3,289 tests, two platform skips and no failures across
+411 files in 378.52 seconds (`.cache/v1-rc1-tests.log`). Typecheck, lint, toolchain,
+skills checks and 39 focused plugin/release tests pass. Subsequent README/runbook
+updates need the RC commit's freshly packed CI archive; the local archive above is
+retained qualification evidence, not the future publishing artifact.
+
+Downloaded the actual `kiln-engine-0.10.0.tgz` from the existing GitHub release and
+matched its published SHA-256:
+`e1ce85d7a27106cc2706bb23d2707e3904e214cf4afda329da5dbfceabf60c9f`.
+A fresh old-package installation created Claude and Codex workspaces. Both saved
+an asset through the old MCP server and verified its GLB/source/preview downloads.
+The qualification then added owner instructions, a launcher customization and an
+unmanaged note. `--check` and the refused conflicting `--upgrade` changed no file
+in a full workspace hash inventory. After retaining the edited originals and
+explicitly resolving those fixture conflicts, upgrade selected the RC runtime,
+kept the harness and note, and accepted the reapplied guide/launcher customizations.
+
+Reopened RC MCP sessions retained all seventeen tools, the exact old source and
+byte-identical downloads. An edited asset saved a new revision with the old
+revision as parent; the old downloads remained unchanged. The upgraded customized
+CLI exported the exact revised source. Eleven checks pass across the two harness
+configurations. Receipt: `.cache/v1-rc1-v010-upgrade.json`; reproducible probe:
+`.cache/v010-rc-upgrade-probe.mjs`. This proves the installed upgrade and MCP/CLI
+flows, not yet a new remote plugin-cache install or final npm registry upgrade.
+The first probe incorrectly expected `status: upgraded`; the API returns
+`status: current, upgraded: true`. That assertion was corrected without an engine
+change, and its initial failed receipt was retained.
+
+### Protected npm staging environment
+
+Created the repository-scoped GitHub `npm-release` environment through the
+[documented environment API](https://docs.github.com/en/rest/deployments/environments#create-or-update-an-environment),
+then independently read it back. It has one required reviewer,
+`matthew-kissinger`, `can_admins_bypass: false`, self-review available to that owner,
+and protected branches only. Main's protected state was read back as true.
+Receipts: `.cache/npm-release-environment-created.json` and
+`.cache/npm-release-environment-verified.json`. The existing `github-pages`
+environment was not modified. This performs the planned repository setup;
+it creates no npm package, publisher trust, token, stage, release or deployment.
+
+### Real plugin updates to the release candidate
+
+Updated the existing isolated Claude Code and Codex qualification profiles through
+their actual marketplace and plugin commands. Both moved `kiln-engine@instruktlabs`
+from `1.0.0-dev.0` to `1.0.0-rc.1` in new versioned caches. Claude's marketplace
+checkout resolves to `3f4bd38d1d8a6a2a849f3f634bbc1cc8709ff25c`; both cached
+bundles have the RC runtime pin and verified file inventories. Ordinary owner
+profiles were not changed.
+
+Full workspace hashes stayed unchanged after each plugin update: the workspace
+continued to use its pinned development runtime. The helper's `--check` stayed
+read-only. Explicit `--upgrade` then installed the reviewed local RC archive in
+persistent storage outside the plugin cache and retained the unmanaged owner note.
+Reopened MCP sessions reported `1.0.0-rc.1`, seventeen tools and rendered images;
+old saved source, GLB and preview downloads remained byte-identical. The upgraded
+CLI exported exact source. All ten checks passed in
+`.cache/v1-rc1-plugin-upgrade.json`; probe:
+`.cache/rc1-plugin-upgrade-probe.mjs`.
+
+Claude's real `mcp list` reported the fixture's workspace server connected using
+server-specific fixture trust. Codex's real app server reported one
+`kiln_workspace`, seventeen tools and no tool-list error, and loaded each of the
+three workspace authoring skills and the plugin setup skill exactly once.
+Receipt: `.cache/v1-rc1-codex-appserver.json`; probe:
+`.cache/rc1-codex-appserver-probe.mjs`. No model request was made. These flows use
+the locally qualified archive with SHA-256
+`6ea9b29408b99766f0636ef27f94d9edd01526c7fb45470d811f13afa3cb755b`;
+they do not establish final registry/tag installation or a final 1.0 upgrade.
+
+The SDK and installation guides now state explicitly that both optional Strands
+SDK subpaths require Node 22.2.0+, like the built-in agent. The core package's
+Node 20.15 compatibility remains unchanged. Current and floor optional-SDK peer
+qualification used Node 22.23.3; it is not optional-Strands evidence for Node 20.
+
+### Release-candidate Linux image
+
+The RC image workflow
+[37446490940](https://github.com/instruktlabs/kiln/actions/runs/37446490940)
+at `3f4bd38d1d8a6a2a849f3f634bbc1cc8709ff25c` again passed all six textured
+software-renderer views. Its native isolation probe failed at `wrapper-launch`
+before evaluating source. Fixed diagnostics show the same namespace permission
+denial for both `unshare` and Bubblewrap; container CPU counters were retained.
+This is a failed hosting qualification, independently of renderer success, and
+does not establish Cloudflare's namespace behavior or provider costs.
+
+RC hosting archive SHA-256:
+`0f266b65ad4e8cae1e2c7cce18cac9a508b3ce96010bca2912ed81b3cfac9197`.
+Image ID:
+`sha256:ae6073107808c16384729fe655f116d76a5e1720ce359a7075772e506d5c4c67`.
+Receipts: `.cache/native-hosting-run-37446490940/`.
+The separate [Website run 37446490916](https://github.com/instruktlabs/kiln/actions/runs/37446490916)
+passed. Package/engine [CI 37446490984](https://github.com/instruktlabs/kiln/actions/runs/37446490984)
+subsequently completed successfully with all twelve jobs passed, including the
+Linux coverage/exporter gates, Windows suite, every installed-package platform
+and the separate installed software-renderer check. These results qualify that
+commit's artifacts; subsequent documentation or source edits need new release
+artifacts. They do not turn the failed hosting probe into a pass.
+
+### Hosted OAuth gateway and tenant routing
+
+Created the private `hosting/` package without changing the engine's dependencies
+or shipped file list. The production Worker combines the separate authorization
+and resource-server roles from `@cloudflare/[email protected]`.
+It uses the configured HTTPS issuer and `/mcp` audience, browser-bound consent,
+S256 PKCE for both client and upstream sign-in, metadata-based and dynamically
+registered clients, fifteen-minute access tokens, refresh and revocation.
+Scope enforcement happens before any tenant request. GitHub identity is the
+provisional adapter pending the owner's new sign-in preference question; no
+identity app or secret has been provisioned.
+
+Verified subjects select a private Durable Object using a versioned issuer/subject
+hash. Different OAuth clients for the same account reconnect to the same object;
+another account cannot choose it through tenant headers or MCP session ids.
+Bearer tokens, cookies and untrusted identity headers are removed before forwarding.
+GitHub tokens are discarded after resolving the immutable user id. Hosted MCP
+schemas are not duplicated: the future native backend must consume the registry.
+
+Fifteen workerd integration tests pass through the real OAuth library, KV and
+Durable Object simulation. They cover challenges/discovery, consent escaping and
+browser/origin binding, denial, missing audience/PKCE and unsupported scopes,
+authorization-code/state replay, wrong verifier, cross-account routing, scope
+denial, metadata clients, resource-bound refresh/revocation, request-size limits
+including chunked bodies, and absence of raw credentials from stored OAuth records.
+Ten initial tests were observed failing against the unavailable-handler baseline
+before implementation. The simulator caught two actual integration problems:
+Workers reject `redirect: error`, and the OAuth library forbids colons in subject
+ids. The adapter now refuses redirects through manual response checks and uses
+`github-<numeric id>`. The revocation test follows the advertised endpoint rather
+than assuming a path. See `hosting/README.md` for scope and limitations.
+
+The backend in these tests only records requests; it does not emulate successful
+engine tool calls. These passes do not establish native evaluation, cross-user
+asset/reference denial, production KV propagation or an authenticated live client
+connection. Public OAuth admission controls and deployed storage/tenant bindings
+remain mandatory. The separate tenant Worker and evaluator must not receive OAuth
+or identity-provider credentials.
+
+The Worker builds to 241,789 bytes, SHA-256
+`01c02255d7fc2aca4f81c6f28d40d05de56995530a8f4ebb122b7c28a793f975`,
+with only the OAuth library and four hosted modules in its input inventory.
+`build` produces `.cache/hosted-worker/` without deploying. A dedicated workflow
+runs hosted typechecking, workerd tests and bundle generation on Linux and Windows.
+Repository and hosted typechecking and lint pass. The full offline engine run
+passed 3,289 tests, two platform skips and no failures across 411 files in
+366.92 seconds (`.cache/v1-hosted-gateway-engine-tests.log`). The hosted receipt
+is `.cache/v1-hosted-gateway-tests.log`. The new workflow's remote result remains
+pending until the committed branch is checked in CI.
+
+Rechecked `cf auth whoami`: `authenticated: false`, `Not logged in`.
+No fresh device flow was started while the existing owner-readiness question was
+unanswered. The OAuth implementation needs a dedicated KV binding; current Paid
+plan inclusions and overage rates were added to the economics report. A future
+scoped deployment authorization must cover that resource too.
+
+### Tenant storage foundation and integrated download boundary
+
+Added a separate private tenant Worker with SQLite ownership/quota records and
+private R2 bytes. The gateway and tenant produce separate bundles; the build rejects
+test helpers in either bundle and OAuth code in the tenant bundle. No identity
+secret or OAuth KV binding is present in the tenant fixture. Its default public
+handler returns 404; private storage operations require its Durable Object binding.
+
+Uploads reserve quota transactionally before R2, stream with exact length/SHA-256,
+and become visible only after acknowledged storage. Saved groups atomically pin
+their inventory and metadata quota; active keys are immutable and identical saves
+are idempotent. Unsaved files deny reads after seven days without extending expiry.
+Deletion retains files shared by other saved groups. Bounded maintenance removes
+expired and failed writes and reconciles old orphan objects within one tenant only.
+
+The deadline fault test first demonstrated a late R2 acknowledgement being accepted
+as a successful upload. The fix bounds the whole operation, denies late publication,
+retains quota through failed cleanup and lets durable maintenance recover. The
+fault fixture uses actual workerd SQLite/R2 with a delayed acknowledgement or failed
+delete; none of its controls enter a production bundle. Recovery after eviction,
+checksum/length mismatch, corrupted/missing bytes, quota races, empty-file count
+limits, metadata admission and failed cross-tenant pinning are also exercised.
+
+Thirty-two hosted tests pass locally after a clean pinned-toolchain `npm ci`:
+sixteen authorization/integration tests, thirteen storage tests and three recovery
+fault tests. The integrated test runs both production Workers, issues OAuth grants
+to two fixed upstream identities, verifies own downloads/reconnection, and denies a
+second user's copied artifact id and forged tenant headers. Internal mutation routes
+remain unavailable through the gateway. Hosted typecheck/build and root typecheck/
+lint pass. Receipt: `.cache/v1-hosted-storage-tests.log`.
+
+The tenant bundle is 18,529 bytes, SHA-256
+`1158803f7733d58e459ad7a8d4d7cc9ded2c2c694a5e467851813dac99fe0d28`.
+Its only inputs are the HTTP helpers, artifact store, tenant class and tenant entry.
+The gateway bundle remains 241,789 bytes with the previously recorded hash.
+Both receipts are in `.cache/hosted-worker/`.
+
+These checks establish the local byte-storage boundary, not live provider tenancy
+or engine semantics. The program store, AssetLibrary/revision/material adapters,
+browser download tickets, account deletion, native execution and deployed tests
+remain open. `/mcp` returns 503 until the native backend is configured and qualified.
+Daily recovery alarms and SQLite costs are now included explicitly in the economics
+record; production quotas and usage measurements remain unset.
+
+CI at `693b0700f273367daf08b920e03530647c134d4b`:
+[hosted checks 37450009673](https://github.com/instruktlabs/kiln/actions/runs/37450009673)
+passed Linux and Windows; [Website 37450009523](https://github.com/instruktlabs/kiln/actions/runs/37450009523)
+passed. [Engine/package CI 37450009480](https://github.com/instruktlabs/kiln/actions/runs/37450009480)
+passed ten jobs and failed the two engine suites solely on the expanded root
+AGENTS.md exceeding its existing 12 KiB limit. Hosting instructions were moved to
+`hosting/AGENTS.md`; the unchanged reliability gate now passes all nine tests locally.
+This corrects the earlier local full-suite receipt, which preceded that documentation
+addition. A new complete CI run is required for the new commit.
+[Native preflight 37450009484](https://github.com/instruktlabs/kiln/actions/runs/37450009484)
+again passed software rendering but failed required namespace isolation before
+source execution. Actual Cloudflare qualification remains pending authentication.
+
+### Engine source-store adapter
+
+`HostedProgramStore` implements the engine's existing `ProgramStore` interface using
+its canonical reference, Unicode and size helpers. Exact UTF-8, including an authored
+BOM, round-trips through private storage. Canonical hashes and full-digest `p_`
+handles retain the existing engine syntax; unissued shortened prefixes do not resolve.
+This host choice avoids permanent alias growth and expired-handle reassignment.
+Ownership remains tenant-local even when two users know the same source digest.
+
+The source adapter reuses the artifact quota, checksum and retention boundary.
+Concurrent identical writes share one upload; a durable content index finds that
+same artifact after eviction. Reads and repeated writes do not extend expiry.
+Saved groups pin exact source artifacts; last-pin deletion removes their source.
+Quota failure preserves existing work and a subsequent retry can succeed after
+cleanup. Corrupt bytes are refused both on reads and idempotent writes.
+
+Six initial source lifecycle checks were observed failing before the endpoint was
+implemented; those and added shared-quota/retry coverage now pass with the adapter.
+The hosted suite now passes all 39 tests after a clean
+installation, along with hosted typecheck/build and root typecheck/lint. The four
+nearest engine program-reference suites passed 23 tests. Workerd's stricter ambient
+TextDecoder type required spelling out the existing `fatal: false` default in the
+portable helper; hashing/Unicode behavior is unchanged. Node runtime bundles were
+rebuilt after that source change.
+
+The full offline engine suite then passed 3,289 tests, two platform skips and no
+failures across 411 files in 369.08 seconds. Receipt:
+`.cache/v1-hosted-programs-engine-tests.log`. These local results supplement the
+new commit's required CI; they do not qualify live hosting or final npm publication.
+
+A fresh Windows Node 22.23.3/npm 12.2.0 installation passed 24 package checks,
+including all 53 core SDK imports, native dependency paths, CLI, stdio MCP,
+source-edit images, restart persistence and exact source export. A separate check
+against that same installed package passed all 53 consumer declaration entries.
+No models were called. Archive SHA-256:
+`1a16edd649e69eeb65008d06e22b24a5ce02b45c12fbd7fc471d0c268856e3c0`.
+Receipts: `.cache/v1-hosted-programs-package.json`,
+`.cache/v1-hosted-programs-types.json`, `.cache/v1-hosted-programs-full.log`.
+
+The tenant bundle is 25,318 bytes, SHA-256
+`08a84289e44260780c138ebe629a6e84f38a9dee7d74b67bf5072865b80fa90c`.
+Its new inputs are the portable engine program-store module and hosted adapter.
+No native engine, provider credential or fixture code enters that Worker.
+The shared portable-module dependency is now included in hosted CI path triggers.
+The `/internal/programs` endpoints remain private; native MCP dispatch still needs
+to inject the adapter and qualify actual source/edit/render/save/reconnect behavior.
+AssetLibrary, material/revision semantics and browser download tickets remain open.
+
+For the preceding `1251f360442186b437cbf9fa86275dd9cfdfa87f` commit,
+[engine/package CI 37453219496](https://github.com/instruktlabs/kiln/actions/runs/37453219496)
+passed all twelve jobs. [Hosted checks 37453219494](https://github.com/instruktlabs/kiln/actions/runs/37453219494)
+passed Linux and Windows; [Website 37453219517](https://github.com/instruktlabs/kiln/actions/runs/37453219517)
+passed. [Native preflight 37453219527](https://github.com/instruktlabs/kiln/actions/runs/37453219527)
+again passed the trusted software-renderer fixture and failed required namespace
+isolation before source execution. These are separate outcomes, not hosting acceptance.
+
+### Native source client and engine integration
+
+`NativeProgramStore` connects the real engine's source-reference tools to the
+tenant storage API. It uses one fixed internal hostname and carries no tenant
+selector, OAuth token or cloud credential. The future Cloudflare container
+controller must bind that hostname to the authenticated tenant outside the image;
+that interceptor and native MCP entrypoint remain unimplemented. The adapter alone
+does not create or qualify a hosted evaluator.
+
+Six new checks were first observed failing because the adapter did not exist.
+They now pass, including an actual `createKilnToolHost` fixture calling
+`kiln_validate`, `kiln_source`, `kiln_edit` and `kiln_render`. The edit produces a
+PNG and an immutable new source reference. A fresh host after Durable Object
+eviction retrieves both exact revisions and renders again; a separate tenant is
+denied the same reference. This is fixed trusted local execution, not a native
+process restart, production isolation or live Cloudflare evidence.
+
+The client verifies exact source bytes, Unicode and hashes, validates acknowledgements
+and stats, bounds streamed replies, disables redirects and credentials, and limits
+the entire HTTP operation. Fault checks cover stalled headers/bodies, invalid
+lengths, corruption, quota errors, cancellation and redacted diagnostics. A test
+exposed a cancellation race where closing the reader could resolve an empty body
+before the abort rejection; the abort now wins that race.
+
+After a clean private-package installation, all 45 hosted tests passed (6.23
+seconds), as did both hosted typechecks, the three hosted builds, root typecheck,
+root lint and whitespace checks. Receipt: `.cache/v1-native-programs-tests.log`.
+The Node adapter is separately built and absent from both Worker entrypoints.
+Gateway output remains unchanged. Current build receipts:
+
+- Native source client: 8,141 bytes, SHA-256
+ `2ce285fb5fde64b2ceefb42430ad0bfbdf5c1e82c076cfbf099c792884a6ed1d`.
+- Tenant Worker: 25,403 bytes, SHA-256
+ `740d86ef71653d63de7550f2e257be114ccd810406bf69cebff85c9c602f0250`.
+
+Hosted CI now rebuilds the current engine before the same integration tests on
+Linux and Windows, and triggers on engine source/dependency changes. The image,
+container controller, MCP HTTP transport, AssetLibrary/material/revision adapters,
+browser downloads, account deletion and deployed qualification remain open.
+
+At the preceding `349cf89e7652a075dbc0777ff883f2ca7b58fa5c` commit,
+[engine/package CI 37455478543](https://github.com/instruktlabs/kiln/actions/runs/37455478543)
+passed all twelve jobs, [hosted checks 37455478554](https://github.com/instruktlabs/kiln/actions/runs/37455478554)
+passed both platforms, and [Website 37455478462](https://github.com/instruktlabs/kiln/actions/runs/37455478462)
+passed. [Native preflight 37455478603](https://github.com/instruktlabs/kiln/actions/runs/37455478603)
+again failed required isolation before source execution while its independent
+trusted software-rendering fixture passed. Cloudflare authentication is still
+required for provider qualification; no production service or npm package is live.
+
+### Native saved assets and exact source restoration
+
+The private storage index and `NativeAssetLibrary` now implement the engine's
+existing project/library save, read, list, import and export contracts. The native
+adapter imports the public SDK's verifier and material dependency resolver;
+`resolveSavedAssetMaterials` is now exported from `@instruktlabs/kiln/assets/node`.
+Cloud code remains outside the published package, and Workers do not import the
+native engine. The shared HTTP transport preserves the source client's existing
+timeouts, cancellation, fixed internal origin and redacted diagnostics.
+
+Revision ownership, filename inventories, immutable ids and parent/first-revision
+conditions are enforced in tenant storage. Commit checks and file pins are atomic,
+so competing first saves cannot silently create independent histories. Imports
+validate the complete input first and commit each revision separately. Copies keep
+their collection identity; deleting one does not delete the other. A retry of an
+identical imported revision retains the same records without new quota consumption.
+
+Material resources use the canonical SDK closure semantics. The local fixture
+exports and imports a textured GLB with its source/materials, then rebuilds it
+byte-for-byte without the original material library. Imported closures are also
+installed in an injected MaterialLibrary. Implementing that library's standalone
+durable hosted adapter remains open.
+
+New tests were observed failing before the index/adapter implementation and missing
+SDK export were added. The full hosted suite now passes 57 checks, including actual
+registry save/list/restore/export, fresh hosts, storage eviction, cross-tenant
+denial, pagination, immutable conflicts, partial-upload cleanup, concurrent-save
+cleanup, lost commit acknowledgement, retained pins and corruption rejection.
+The lost-acknowledgement test confirms cleanup leaves all committed files readable
+after reconnect. Unacknowledged uploads or interrupted cleanup can remain charged
+until normal unsaved expiry; the controller's per-job recovery remains open.
+
+The source round trip exposed a real engine defect: default UTF-8 decoding removed
+an authored BOM and changed the program reference. Restore, MCP source reads,
+reviewed saves and CLI rebuild observations now preserve those exact source bytes.
+The focused 23 tests across five files passed after observing the failures, and
+runtime bundles were regenerated. Build identity:
+`sha256:4024be2f88cbe9582a83fc9250a90e44f1e2ec9255a65ba81f94db3a9ac08624`.
+
+The full engine suite passed 3,289 tests with two platform skips and no failures
+across 411 files in 369.68 seconds. Hosted typechecks, all four hosted builds, root
+typecheck and lint passed. Receipts: `.cache/v1-hosted-assets-engine-tests.log`,
+`.cache/v1-hosted-assets-tests.log` and `.cache/hosted-worker/`.
+These fixtures use fixed trusted local source. They do not establish untrusted
+native isolation, production persistence, live OAuth or capacity/costs.
+
+A fresh Windows Node 22.23.3/npm 12.2.0 installation passed 25 package checks,
+including all 53 core SDK imports/declarations, CLI, MCP, native dependency paths,
+source-edit images and restart persistence. Archive SHA-256:
+`c3fbbef710fbd56cc42897a10d803a5a534f9dcc27f713c7142fba93787aa951`.
+Receipt: `.cache/v1-hosted-assets-package.log`. Both separately built production
+native adapters also loaded against that exact fresh installation, including the
+new public material resolver; no test alias or repository SDK path was used.
+
+Build receipts identify the native asset adapter as 19,226 bytes, SHA-256
+`ea7055048ecd9f946f5537aeb89d0daf7ab4b9344f166e958d57d3e8bffa0995`,
+with three external public SDK imports. The tenant Worker is 31,244 bytes, SHA-256
+`dadf4d9d5d8be7d848479c2c2f9665e47e7a9670e1195529a0e309154ab2dbe9`.
+No model call, cloud provisioning, npm publication or production deployment was
+performed by this validation.
+
+For the preceding `194b0ba1d0080f4360fba5ae05e3feeb6b33266e` commit,
+[engine/package CI 37457310643](https://github.com/instruktlabs/kiln/actions/runs/37457310643),
+[hosted checks 37457310650](https://github.com/instruktlabs/kiln/actions/runs/37457310650)
+and [Website 37457310654](https://github.com/instruktlabs/kiln/actions/runs/37457310654)
+passed. [Native preflight 37457310791](https://github.com/instruktlabs/kiln/actions/runs/37457310791)
+failed the required isolated evaluation/rendering step. Exact CI for this new change
+and actual Cloudflare provider qualification remain required.
+
+### Native MCP HTTP transport
+
+The private native host now uses the pinned MCP server SDK 2.3.0 and the installed
+engine's real registry. It supports the current HTTP protocol and stateless 2025
+compatibility without duplicating tool schemas. Gateway forwarding now preserves
+the required method/name headers, and browser Origin validation is applied before
+dispatch. Credentials and tenant selectors cannot enter the private native route.
+
+The production loader requires isolated-evaluator readiness before it exposes an
+engine. Local tests use a fixed trusted fixture and make no isolation claim.
+Fresh request contexts inject the durable source and asset adapters. Body, response
+and deadline limits bound HTTP work; a cancelled evaluator retains its admission
+slot until it settles. Container execution and forced process cleanup still need
+their own implementation and real Cloudflare qualification.
+
+Tests first demonstrated missing transport behavior, dropped protocol headers and
+an accepted foreign Origin. Additional fault tests exposed cancellation/deadline
+handling and an unhandled rejection; the corrections pass the focused nine HTTP
+tests. After a clean private-package install, the complete hosted suite passes
+67 tests, both hosted typechecks and five production builds. Root typecheck, lint
+and whitespace checks pass. Receipt: `.cache/v1-native-mcp-tests.log`.
+The native MCP bundle is 33,262 bytes, SHA-256
+`0a2b1d06ecd4a5ca46141c0f6c859b6baac9cde84117c1dc372740fe34da6807`.
+
+For `1116ea6b5415482f7436e73830a60397bbc1dc5c`,
+[engine/package CI 37460519101](https://github.com/instruktlabs/kiln/actions/runs/37460519101)
+passed all twelve jobs. Hosted checks 37460519166 and Website 37460519321 passed.
+Native preflight 37460519128 failed its required isolated evaluation/rendering step.
+These results qualify that commit; this transport change needs its own CI.
+
+### Package release priority
+
+A fresh public registry lookup on 6 October still returns 404 for
+`@instruktlabs/kiln`. The RC is unpublished. Final 1.0 version/documents, exact
+candidate qualification, approved main integration, npm publisher authorization,
+publication/provenance and fresh registry installation remain open. As specified
+in the publication plan, npm release does not wait for hosted launch or directory
+approval. Those remain separate requirements of the overall active goal.
+
+### Authentication architecture and current client compatibility
+
+The owner expanded hosted v1 sign-in to Google and GitHub, with email later, and
+requested a current, provider-agnostic architecture review. The publication plan's
+[authentication review](../plans/2026-10-05-v1-publication-plan.md#authentication-architecture-review-6-october)
+records primary sources, the account boundary, library alternatives and required
+implementation/qualification. It recommends retaining the maintained Cloudflare
+MCP issuer, adding a standards-based Google adapter and a permanent internal Kiln
+account id, and keeping identity/lifecycle data separate from tenant artifacts.
+The existing `github-<id>` subject is not the final multi-provider account model.
+
+Live registry metadata confirms the existing Cloudflare OAuth provider pin 1.2.1
+is the current stable release. Read-only Google discovery and ChatGPT CIMD probes
+confirmed the documented endpoints, S256 and the current public/signed method
+offer. Two new checks prove the production gateway can negotiate the supported
+public method when the metadata's legacy preference is signed, still rejects a
+missing PKCE verifier, and refuses a signed-only client. All 19 focused auth
+checks and the complete 69-test hosted suite pass; root lint and whitespace checks
+pass after formatting the added fixtures. Receipts:
+`.cache/v1-auth-architecture-tests.log`, `.cache/v1-auth-review-hosted-tests.log`.
+This does not constitute
+live Google/OpenAI login or signed-client assertion support.
+
+Production dependency audit reported zero known advisories in the current private
+hosting package; `.cache/v1-auth-audit.json`. It is not a security certification.
+The review explicitly records the library's KV concurrent-consumption limitation,
+cross-region revocation concerns, missing account/linking/deletion controls and
+unfinished branded UI. No provider app, secret or cloud resource was created.
+
+### RC shutdown qualification and final-version preparation
+
+At `aa5bc2cba745f616a4775a60016cefb097621bcf`,
+[engine/package CI 37464347265](https://github.com/instruktlabs/kiln/actions/runs/37464347265)
+completed with eleven successful jobs. Intel macOS failed because the npm-launched
+MCP process did not exit within five seconds of stdin closing, after successfully
+listing tools. Hosted checks 37464347226 and Website 37464347348 passed. Native
+preflight 37464347408 failed required isolation, as before. This is not an
+all-green package candidate.
+
+A focused regression reproduced a real lifecycle defect locally: the executable's
+delayed warmup imported an unused engine after a tool-list-only client disconnected.
+The executable now cancels pending warmup on stdin end/close, checks the stream
+before starting it and unreferences the speculative timer. It does not force the
+process to exit or loosen the package smoke test's shutdown deadline. All six
+startup checks pass after rebuilding; the macOS outcome still requires fresh CI.
+Before/after receipts: `.cache/v1-mcp-close-before-fix.log` and
+`.cache/v1-mcp-close-after-fix.log`.
+The full offline unit suite passed 3,290 tests with two platform skips and no
+failures across 411 files (367.11 seconds); `.cache/v1-mcp-close-tests.log`.
+Typechecking, root lint and whitespace checks also pass. Exact-commit CI still
+must qualify coverage, other operating systems and installed software rendering.
+
+The corrected RC's fresh Windows installation passed all 25 package checks,
+including 53 core imports/declarations, npm-launched MCP shutdown, real CLI/MCP
+render/edit/save flows and textured community export. Archive SHA-256:
+`aab4be74024f93d1ef20a397d15807204b04cd81fb959fbee779c2e32997d14b`;
+receipt `.cache/v1-mcp-close-package.json`. Its installed production dependency
+audit reported zero known advisories in `.cache/v1-rc-consumer-audit.json`.
+Neither result is a security certification or a registry publication receipt.
+
+Final `1.0.0` version/documents/plugin preparation is preserved in
+`.cache/v1-final-preparation.patch`. Its preliminary Windows package check passed,
+but that archive predates this shutdown correction and is not a final candidate.
+The working branch remains `1.0.0-rc.1` so the plan's authorized RC publication and
+fresh registry/plugin installation precede final 1.0 qualification. Apply the
+saved source/document changes selectively after the RC step, then regenerate plugin
+metadata and runtime bundles; never restore its stale generated build files.
+
+## Owner handoffs
+
+Cloudflare CLI consent is complete. After the earlier consent expired, the owner
+approved a fresh request in external Chrome. The CLI reported successful login,
+and a separate `auth whoami` check confirmed authenticated and token-valid state
+for the intended account. The consent displayed 24 permissions covering identity,
+account/zone reads, Workers, Containers, R2, KV, D1 and observability; the CLI also
+records its refresh capability. No billing or API-token management permission was
+requested. This authorizes CLI access, not evidence of a deployed service.
+
+The owner selected Google and GitHub sign-in for free hosted v1 access, private
+saved assets and personal quotas, with email sign-in deferred and explicit requirements for correct implementation,
+professional presentation and end-user security. The package and local plugins
+remain account-free. The hosted launch gate includes clear Kiln / Instrukt Labs
+branding, verified domain, minimal provider permissions, privacy/support links,
+usable disconnect/deletion controls and actual deployed consent, cancellation,
+expiry/revocation and cross-user denial checks. Local fixtures do not establish
+those results. No identity app or secret has been provisioned yet.
+
+The CLI's read-only `npm whoami` check reports that this machine is not signed in.
+A browser login was opened in external Chrome and the owner's password/security-key
+step was surfaced through the question tool. Login does not stage or publish a
+package. Publisher verification and final external approvals remain separate;
+missing human steps do not block independent package work.
diff --git a/docs/runtime.md b/docs/runtime.md
index 3334da63..04b94739 100644
--- a/docs/runtime.md
+++ b/docs/runtime.md
@@ -7,8 +7,8 @@ The packaged local host also supplies optional project, material-library and rev
Compiled CLI/MCP commands share one Node compatibility check with workspace setup:
20.x from 20.15.0, or 22.2.0 and later. Optional Strands generation requires 22.2.0+;
the CLI checks this before loading its SDK or provider. These floors are separate
-from the exact maintainer versions in `toolchain.json`. Direct TypeScript library
-imports still need a loader or build system. See [installation](install.md) for
+from the exact maintainer versions in `toolchain.json`. The v1 SDK ships compiled
+ESM and declarations, so package imports need no TypeScript loader. See [installation](install.md) for
recommended Node releases and the distinction between checkout and package evidence.
## Optional native Strands workflow
@@ -48,7 +48,7 @@ the official Google adapter with Gemini 3.8 Flash and high thinking, in 33, 15
and 18 model calls. Retained source/export identities, GPU images, selected
interfaces and protected components were independently reviewed. Earlier failed
and partial provider attempts remain recorded. See the
-[native trace audit](reviews/2026-09-23-native-trace-audit.md#trial13-completed-baseline-and-both-refinements).
+[native trace audit](https://github.com/instruktlabs/kiln/blob/main/docs/reviews/2026-09-23-native-trace-audit.md#trial13-completed-baseline-and-both-refinements).
That trial qualifies this bounded route, not every provider or asset type. Other
adapters have offline contract evidence; their model access, quotas, tool schemas,
@@ -135,7 +135,7 @@ Advanced geometry callbacks also have operation-specific input limits. Those che
The rigid-group `full` contract and `rigid-v1` rebuild policy below describe the
unreleased alignment candidate planned for 0.11. They are not implemented by the
-downloadable 0.10.0 package; see the [migration notes](migration.md#unreleased-changes-planned-for-011).
+downloadable 0.10.0 package; see the [migration notes](migration.md#unreleased-changes-planned-for-10).
`KILN_BAKE_OPTIMIZE` and `KILN_BAKE_INSTANCE` choose the bake passes for a render that does not pass `optimize` or `instance`; a value the call passes always wins.
diff --git a/docs/sdk.md b/docs/sdk.md
new file mode 100644
index 00000000..3ea8dc0d
--- /dev/null
+++ b/docs/sdk.md
@@ -0,0 +1,135 @@
+# Kiln JavaScript and TypeScript SDK
+
+This describes the v1 package contract under development. Registry publication is
+a separate release gate; examples use the selected name `@instruktlabs/kiln`.
+
+## Imports
+
+Kiln ships compiled ESM and TypeScript declarations. The package root is a Node
+library entrypoint; importing it does not run the CLI or start a server. Consumers
+do not need Bun or a TypeScript runtime loader.
+
+```ts
+import { createDiscovery, engineIdentity, renderGLB, validateKilnCode } from '@instruktlabs/kiln';
+
+const code = `function build() {
+ return new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0x888888));
+}`;
+const validation = validateKilnCode(code);
+const result = await renderGLB(code);
+// result.glb is a Buffer containing the GLB. Persist or deliver it in your host.
+```
+
+The complete authoring and host APIs remain available through documented subpaths.
+The existing 55 export paths are retained. The root exposes rendering, validation,
+Discovery and engine identity; it does not re-export every name from every module.
+CommonJS is not part of this release's contract.
+
+Custom `AssetLibrary` hosts can import `verifyAssetRecord` and
+`resolveSavedAssetMaterials` from `@instruktlabs/kiln/assets/node`. The latter resolves
+the exact saved dependency manifests from a record's embedded material payload or
+an injected `MaterialLibrary`; it never substitutes a newer material revision.
+Use the existing material payload and asset-bundle encoders for portable delivery.
+
+| Area | Subpaths |
+| --- | --- |
+| Root library | `@instruktlabs/kiln` |
+| Authoring | `primitives`, `geometry`, `deform`, `sweep`, `architecture`, `assembly`, `character`, `vehicle`, `palette` |
+| Materials | `material-library`, `material-library/node`, `material-presets`, `material-recipes`, `material-resources`, `material-recipe-runtime`, `material-recipe-prompt`, `material-metrics`, `texture-resolver` |
+| Rendering and inspection | `render`, `views`, `validation`, `metrics`, `inspect`, `qa`, `asset-export`, `kit` |
+| Host contracts | `tools`, `evaluator`, `discovery`, `requirements`, `requirements/migration`, `contracts`, `prompt-api`, `profile` |
+| Records and storage | `assets`, `projects`, `project-bundle`, `workspace`, `live-review`, `programs`, `cache`, and each corresponding `/node` adapter |
+| Composition | `composer`, `world-runtime` |
+| Ranking math | `arena` |
+| Optional agent workflows | `agent`, `composer/agent` |
+| Experimental modeling | `implicit` |
+
+Read the [architecture reference](architecture.md) for the domains and the
+[runtime contract](runtime.md) for hosting boundaries. The export map is the public
+entrypoint list. Files inside `lib/`, including declaration dependencies under
+`lib/_types/`, are implementation details and are not additional public subpaths.
+
+## Stability in 1.x
+
+The table classifies all 55 public entrypoints. The root and every listed subpath
+except `implicit` are stable entrypoints for v1: their declared public signatures,
+record shapes and documented behavior receive normal semantic-versioning
+compatibility. Optional dependencies do not make the two agent APIs experimental.
+The `arena` entry is pure ranking math and needs no model SDK or provider key.
+This release candidate is not yet the published 1.0 contract.
+
+The exception follows the feature across imports: `implicitSurface` remains
+experimental when re-exported by `primitives` or used in authoring globals, and
+experimental Discovery recipes retain their individual labels. The alternative
+Three.js exporter also remains experimental and explicitly selected. Changes to
+these experimental features must be identified in release notes and migration
+guidance; the rest of an entrypoint does not inherit that exception.
+
+The deprecated `setApprovedTextureResolver` alias remains available from
+`material-resources`; new hosts use `setTrustedTextureByteResolver`. Deprecation
+does not authorize removal from a compatible 1.x release. Neither setter belongs
+in generated code: trusted hosts own the approved resource boundary.
+
+Human-readable prompts, descriptions, diagnostic prose and image pixels are not
+byte-stable API outputs. Consume documented structured records and version tags;
+ignore unknown additive result fields. Preserve an asset's exact engine identity
+and source/revision receipts for reproducible replay. Compatibility of the SDK
+does not imply identical generated GLB bytes or renderer output across releases.
+Persisted data and rebuild restrictions follow the [migration contract](migration.md).
+
+## Execution and dependencies
+
+The root SDK is Node-oriented. `/node` adapters use filesystem or server services;
+the remaining names do not by themselves promise browser compatibility. Portable
+record modules retain their existing boundaries. Browser use must follow a
+documented, qualified entrypoint rather than importing the entire Node host.
+
+`renderGLB` defaults to trusted in-process execution. A hosted service accepting
+untrusted programs must inject or select the qualified isolated evaluator described
+in the runtime contract. A subprocess provides a worker boundary; it does not alone
+establish filesystem, network or tenant isolation.
+
+The installed isolated evaluator uses compiled JavaScript workers and readiness
+probes, without a TypeScript loader. Linux hosts still need the required namespace
+and resource-limit tools and must pass the actual readiness probe. An unavailable
+boundary fails closed; a successful local worker render is not proof of isolation.
+
+Optional Strands workflows (`agent` and `composer/agent`) require Node **22.2.0+**
+and their documented peer dependencies. The core SDK, CLI and MCP retain the
+separate Node compatibility contract in the [installation guide](install.md).
+Core SDK imports and consumer types must work without those optional peers.
+Shared tool contracts contain host-neutral interfaces; they do not require the
+Strands SDK to typecheck an ordinary CLI/MCP host.
+
+Existing experimental features remain explicit: `/implicit` keeps its current
+availability and limitations, and the community exporter stays explicitly selected. CPU
+geometry previews do not establish texture or PBR material fidelity. Experimental
+labels do not waive installation, export-resolution or resource-bound checks.
+
+Discovery search and overview text include each entry's `stable`, `experimental`
+or `deprecated` label alongside its limitations. The CLI, SDK and MCP use the same
+catalog. A recipe's experimental label applies to that recipe; it does not change
+the stability of the helpers it uses. Exact details retain the same structured
+`stability` field. Implicit modeling remains available without a new opt-in switch;
+the community exporter retains its explicit selection.
+
+## Maintainer qualification
+
+`node scripts/build-runtime.mjs all` builds both executable bundles and the ESM SDK.
+`bun run build` remains typechecking only. SDK output replaces the generated `lib/`
+tree after successful compilation and module resolution, so removed modules cannot
+linger in a new package.
+
+On a fresh checkout, run `bun run build:sdk` before typechecking or running tests
+that exercise public package imports. Rebuild after source changes; package tests
+must exercise the generated code that a consumer will receive. Coverage measures
+the source engine and excludes its generated `lib/` copy without changing thresholds.
+
+The package checks import core entrypoints and render through the installed worker.
+With maintainer dependencies present, `node scripts/smoke-package.mjs --types` also
+typechecks a clean installed consumer without optional peers. CI qualifies this
+against the same tarball subsequently passed to the platform consumer jobs.
+The core check covers 53 entrypoints, including `arena`. After installing the
+optional peers, `node scripts/smoke-sdk-types.mjs INSTALLED_PACKAGE --with-agent-peers`
+checks declarations for all 55. Import/type qualification does not establish live
+model access or provider behavior.
diff --git a/hosting/AGENTS.md b/hosting/AGENTS.md
new file mode 100644
index 00000000..f636f689
--- /dev/null
+++ b/hosting/AGENTS.md
@@ -0,0 +1,23 @@
+# 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/README.md b/hosting/README.md
new file mode 100644
index 00000000..4fcae52a
--- /dev/null
+++ b/hosting/README.md
@@ -0,0 +1,318 @@
+# 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.
+
+## 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 network responses with fixed
+identities. 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.
+
+## 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. The current adapter implements GitHub only. It requests no repository scopes, uses upstream S256 PKCE,
+and resolves the current GitHub user for every login. Only `github-<immutable id>`
+becomes a subject. Login names and email addresses are not tenant identifiers.
+Upstream tokens are used only for the identity lookup and are not stored or passed
+to the backend. This needs a dedicated Instrukt Labs OAuth app; no app or secret
+has been provisioned by this implementation.
+
+Before launch, replace this direct provider subject with a permanent Kiln account
+id resolved from verified `(issuer, subject)` bindings. Google, account storage,
+explicit linking and recovery/account controls are not implemented yet. 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. 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 GitHub 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.
+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 OAuth subjects alone select a Durable Object, using a versioned hash of
+issuer and subject. Reconnecting through another client selects the same tenant.
+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.
+
+## Native saved assets
+
+`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. Browser/account deletion UI
+and its deployed lifecycle remain open.
+
+Embedded material records are retained and verified using the SDK's canonical
+dependency semantics. An injected MaterialLibrary receives the closure on import;
+the separate durable hosted MaterialLibrary is still unimplemented. 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.
+
+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).
diff --git a/hosting/package-lock.json b/hosting/package-lock.json
new file mode 100644
index 00000000..735d4383
--- /dev/null
+++ b/hosting/package-lock.json
@@ -0,0 +1,1913 @@
+{
+ "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/server": "2.3.0"
+ },
+ "devDependencies": {
+ "@cloudflare/workers-types": "5.20261006.1",
+ "esbuild": "0.28.1",
+ "miniflare": "5.20261001.0-alpha",
+ "typescript": "7.0.2"
+ }
+ },
+ "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/@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.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.4.tgz",
+ "integrity": "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.4.tgz",
+ "integrity": "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-freebsd-wasm32": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.4.tgz",
+ "integrity": "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.4"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.3.tgz",
+ "integrity": "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.3.tgz",
+ "integrity": "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.3.tgz",
+ "integrity": "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.3.tgz",
+ "integrity": "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.3.tgz",
+ "integrity": "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.3.tgz",
+ "integrity": "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.3.tgz",
+ "integrity": "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.3.tgz",
+ "integrity": "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.3.tgz",
+ "integrity": "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==",
+ "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.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.3.tgz",
+ "integrity": "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==",
+ "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.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.4.tgz",
+ "integrity": "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.4.tgz",
+ "integrity": "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-linux-ppc64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.4.tgz",
+ "integrity": "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-linux-riscv64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.4.tgz",
+ "integrity": "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-linux-s390x": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.4.tgz",
+ "integrity": "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.4.tgz",
+ "integrity": "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.4.tgz",
+ "integrity": "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.4.tgz",
+ "integrity": "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==",
+ "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.3"
+ }
+ },
+ "node_modules/@img/sharp-wasm32": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.4.tgz",
+ "integrity": "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==",
+ "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.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.4.tgz",
+ "integrity": "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.4"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-arm64": {
+ "version": "0.35.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.4.tgz",
+ "integrity": "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==",
+ "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.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.4.tgz",
+ "integrity": "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==",
+ "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.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.4.tgz",
+ "integrity": "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==",
+ "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/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/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/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.4",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.4.tgz",
+ "integrity": "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==",
+ "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.4",
+ "@img/sharp-darwin-x64": "0.35.4",
+ "@img/sharp-freebsd-wasm32": "0.35.4",
+ "@img/sharp-libvips-darwin-arm64": "1.3.3",
+ "@img/sharp-libvips-darwin-x64": "1.3.3",
+ "@img/sharp-libvips-linux-arm": "1.3.3",
+ "@img/sharp-libvips-linux-arm64": "1.3.3",
+ "@img/sharp-libvips-linux-ppc64": "1.3.3",
+ "@img/sharp-libvips-linux-riscv64": "1.3.3",
+ "@img/sharp-libvips-linux-s390x": "1.3.3",
+ "@img/sharp-libvips-linux-x64": "1.3.3",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.3",
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.3",
+ "@img/sharp-linux-arm": "0.35.4",
+ "@img/sharp-linux-arm64": "0.35.4",
+ "@img/sharp-linux-ppc64": "0.35.4",
+ "@img/sharp-linux-riscv64": "0.35.4",
+ "@img/sharp-linux-s390x": "0.35.4",
+ "@img/sharp-linux-x64": "0.35.4",
+ "@img/sharp-linuxmusl-arm64": "0.35.4",
+ "@img/sharp-linuxmusl-x64": "0.35.4",
+ "@img/sharp-webcontainers-wasm32": "0.35.4",
+ "@img/sharp-win32-arm64": "0.35.4",
+ "@img/sharp-win32-ia32": "0.35.4",
+ "@img/sharp-win32-x64": "0.35.4"
+ },
+ "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
new file mode 100644
index 00000000..bc9a0c48
--- /dev/null
+++ b/hosting/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@instruktlabs/kiln-hosted",
+ "version": "1.0.0-rc.1",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
+ "test": "node --test test/*.test.mjs",
+ "build": "node scripts/build.mjs"
+ },
+ "dependencies": {
+ "@cloudflare/workers-oauth-provider": "1.2.1",
+ "@modelcontextprotocol/server": "2.3.0"
+ },
+ "devDependencies": {
+ "@cloudflare/workers-types": "5.20261006.1",
+ "esbuild": "0.28.1",
+ "miniflare": "5.20261001.0-alpha",
+ "typescript": "7.0.2"
+ }
+}
diff --git a/hosting/scripts/build.mjs b/hosting/scripts/build.mjs
new file mode 100644
index 00000000..f614d843
--- /dev/null
+++ b/hosting/scripts/build.mjs
@@ -0,0 +1,50 @@
+import { mkdir, writeFile } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+import { build } from 'esbuild';
+
+const output = new URL('../../.cache/hosted-worker/', import.meta.url);
+await mkdir(output, { recursive: true });
+for (const entry of ['worker', 'tenant-worker', 'native-programs', 'native-assets', 'native-mcp']) {
+ 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',
+ target: 'es2022',
+ metafile: true,
+ external: [
+ 'cloudflare:workers',
+ '@instruktlabs/kiln',
+ '@instruktlabs/kiln/*',
+ '@modelcontextprotocol/server',
+ ],
+ });
+ const bytes = result.outputFiles[0].contents;
+ const inputs = Object.keys(result.metafile.inputs);
+ if (inputs.some((name) => /(?:^|\/)test\//.test(name.replaceAll('\\', '/')))) {
+ throw new Error('Production bundle includes test helpers');
+ }
+ if (
+ entry !== 'worker' &&
+ inputs.some((name) => /oauth|(?:^|\/)auth\.ts$/.test(name.replaceAll('\\', '/')))
+ ) {
+ throw new Error('Storage bundle includes authorization-server code');
+ }
+ 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/src/artifact-store.ts b/hosting/src/artifact-store.ts
new file mode 100644
index 00000000..9c9ef329
--- /dev/null
+++ b/hosting/src/artifact-store.ts
@@ -0,0 +1,525 @@
+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;
+
+ 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)`);
+ }
+
+ 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 !!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();
+ 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) {
+ 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 row: ArtifactRow = {
+ id,
+ object_key: this.prefix + id,
+ sha256,
+ bytes,
+ filename,
+ media_type: mediaType,
+ created_at: this.now(),
+ expires_at: this.now() + 7 * DAY,
+ state: 'uploading',
+ };
+ this.ctx.storage.transactionSync(() => {
+ 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,
+ );
+ });
+ 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.bucket.put(row.object_key, fixed.readable, {
+ sha256,
+ onlyIf: { etagDoesNotMatch: '*' },
+ httpMetadata: { contentType: mediaType },
+ }),
+ );
+ try {
+ const [, stored] = await Promise.race([Promise.all([pipe, put]), timeout]);
+ if (!stored || stored.size !== bytes) throw new Error('Artifact write did not complete');
+ 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]);
+ 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 } = {}) {
+ 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 }> {
+ const now = this.now();
+ let removed = 0;
+ try {
+ const 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)) LIMIT 32`,
+ now - UPLOAD_GRACE,
+ now,
+ )
+ .toArray();
+ for (const row of candidates)
+ this.sql.exec("UPDATE artifacts SET state = 'deleting' WHERE id = ?", 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,
+ });
+ 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));
+ 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-index.ts b/hosting/src/asset-index.ts
new file mode 100644
index 00000000..e0fb5986
--- /dev/null
+++ b/hosting/src/asset-index.ts
@@ -0,0 +1,93 @@
+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
new file mode 100644
index 00000000..7638eb3c
--- /dev/null
+++ b/hosting/src/auth.ts
@@ -0,0 +1,190 @@
+import {
+ AuthorizationError,
+ authorizationErrorRedirect,
+ type ConsentDescription,
+ type OAuthHelpers,
+} from '@cloudflare/workers-oauth-provider';
+import { HttpFailure, readBounded, sha256 } from './http';
+
+export const SCOPES = ['kiln:use', 'offline_access'];
+export interface SignInEnv {
+ GITHUB_CLIENT_ID: string;
+ GITHUB_CLIENT_SECRET: string;
+}
+const escapeHtml = (value: string) =>
+ value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
+
+function consentPage(details: ConsentDescription, handle: string): string {
+ 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 `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
+<title>Connect to Kiln</title><main><h1>Connect ${escapeHtml(details.clientName)} to Kiln</h1>
+<p>${details.clientDomain ? `Client domain: <strong>${escapeHtml(details.clientDomain)}</strong>.` : 'This client registered its own name; that name is not verified.'}</p>
+<p>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>${details.scope.map((scope) => `<li>${escapeHtml(descriptions[scope] ?? scope)}</li>`).join('')}</ul>
+<p>Sign in with GitHub to identify your Kiln account. Kiln requests no repository access.</p>
+<form method="post" action="/authorize"><input type="hidden" name="handle" value="${escapeHtml(handle)}">
+<button name="decision" value="approve">Continue with GitHub</button>
+<button name="decision" value="deny">Cancel</button></form></main></html>`;
+}
+
+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>;
+}
+
+async function githubIdentity(
+ code: string,
+ verifier: string,
+ origin: string,
+ env: SignInEnv,
+): Promise<string> {
+ 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; only this subject is retained by Kiln's OAuth grants.
+ return `github-${user.id}`;
+}
+
+export async function authorize(
+ request: Request,
+ oauth: OAuthHelpers,
+ origin: string,
+ env: SignInEnv,
+): Promise<Response> {
+ const url = new URL(request.url);
+ 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);
+ consent.headers.set('content-type', 'text/html; charset=utf-8');
+ consent.headers.set(
+ 'content-security-policy',
+ "default-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
+ );
+ return new Response(consentPage(details, consent.handle), { headers: 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();
+ const handle = String(form.get('handle') ?? '');
+ const decision = form.get('decision');
+ if (decision === 'deny') {
+ const result = await oauth.denyConsent(request, handle);
+ return new Response(null, { status: 302, headers: result.headers });
+ }
+ if (decision !== 'approve') throw new HttpFailure(400, 'Choose whether to connect');
+ const approved = await oauth.approveConsent(request, handle);
+ const verifier = crypto.randomUUID().replace(/-/g, '') + crypto.randomUUID().replace(/-/g, '');
+ const upstream = await oauth.beginUpstream(approved.request, {
+ data: { verifier },
+ headers: approved.headers,
+ });
+ 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: upstream.state,
+ code_challenge: await sha256(verifier),
+ code_challenge_method: 'S256',
+ }).toString();
+ upstream.headers.set('location', target.href);
+ return new Response(null, { status: 302, headers: upstream.headers });
+ }
+ if (url.pathname === '/oauth/github/callback' && request.method === 'GET') {
+ const resumed = await oauth.finishUpstream<{ verifier: string }>(request);
+ 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 userId = await githubIdentity(code, resumed.data.verifier, origin, env);
+ const { redirectTo } = await oauth.completeAuthorization({
+ request: resumed.request,
+ userId,
+ metadata: {},
+ scope: resumed.request.scope,
+ props: { userId },
+ });
+ resumed.headers.set('location', redirectTo);
+ 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/gateway.ts b/hosting/src/gateway.ts
new file mode 100644
index 00000000..4a92faf8
--- /dev/null
+++ b/hosting/src/gateway.ts
@@ -0,0 +1,60 @@
+import { insufficientScope, type OAuthResourceContext } from '@cloudflare/workers-oauth-provider';
+import { boundedRequest, HttpFailure, sha256 } from './http';
+
+export interface TenantEnv {
+ TENANTS: DurableObjectNamespace;
+}
+
+export async function forwardTenant(
+ request: Request,
+ env: TenantEnv,
+ 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 || !/^[A-Za-z0-9_-]{1,256}$/.test(userId))
+ throw new HttpFailure(401, 'Invalid identity');
+ 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 sha256(JSON.stringify(['kiln-tenant-v1', 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',
+ });
+ return env.TENANTS.getByName(tenant).fetch(internal);
+}
diff --git a/hosting/src/http.ts b/hosting/src/http.ts
new file mode 100644
index 00000000..6807844b
--- /dev/null
+++ b/hosting/src/http.ts
@@ -0,0 +1,96 @@
+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 (!body) return new Uint8Array();
+ const reader = body.getReader();
+ const chunks: Uint8Array[] = [];
+ 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);
+ });
+ try {
+ if (signal?.aborted) onAbort();
+ for (;;) {
+ const { done, value } = await Promise.race([reader.read(), timeout]);
+ if (done) break;
+ length += value.byteLength;
+ if (length > limit) {
+ void reader.cancel().catch(() => {});
+ throw new HttpFailure(413, 'Request too large');
+ }
+ chunks.push(value);
+ }
+ const bytes = new Uint8Array(length);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes;
+ } 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);
+ 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/native-assets.ts b/hosting/src/native-assets.ts
new file mode 100644
index 00000000..86a7948c
--- /dev/null
+++ b/hosting/src/native-assets.ts
@@ -0,0 +1,403 @@
+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';
+
+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 } = {},
+ ) {
+ 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 assetId = identity(draft.assetId ?? `a_${crypto.randomUUID().replaceAll('-', '')}`);
+ if (draft.parentRevision) await this.read(target, assetId, draft.parentRevision);
+ if (draft.code !== undefined) await programReference(draft.code);
+ const files: Record<string, Uint8Array> = { 'asset.glb': Uint8Array.from(draft.glb) };
+ if (draft.code !== undefined) files['source.kiln.js'] = new TextEncoder().encode(draft.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: draft.code !== undefined,
+ files: inventory,
+ build: draft.build
+ ? { ...draft.build, rebuild: draft.build.rebuild ?? 'engine-required' }
+ : undefined,
+ 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));
+ }
+ /** 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-http.ts b/hosting/src/native-http.ts
new file mode 100644
index 00000000..b7c53735
--- /dev/null
+++ b/hosting/src/native-http.ts
@@ -0,0 +1,155 @@
+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[];
+}
+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>;
+ constructor(
+ private readonly options: NativeStorageOptions = {},
+ private readonly label = 'Storage',
+ ) {
+ 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] } = request;
+ const url = new URL(path, 'http://kiln-storage.internal');
+ if (
+ url.href !== `http://kiln-storage.internal${path}` ||
+ url.search ||
+ url.hash ||
+ !(path.startsWith('/internal/') || /^\/mcp\/artifacts\/[a-f0-9]{32}$/.test(path))
+ )
+ throw new Error('Invalid private storage 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);
+ for (const name of outgoing.keys())
+ if (!['content-type', 'x-artifact-name', 'x-artifact-sha256'].includes(name))
+ throw new Error('Invalid private storage 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 cancel = () => controller.abort();
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
+ let timedOut = false;
+ let finished = false;
+ let abortListener: () => void = () => {};
+ 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) => {
+ // Even a non-cooperative injected transport cannot leave a late body open.
+ if (finished || controller.signal.aborted) void response.body?.cancel().catch(() => {});
+ return response;
+ });
+ const response = await Promise.race([pending, aborted]);
+ 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`);
+ }
+ 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();
+ const chunks: Uint8Array[] = [];
+ let length = 0;
+ for (;;) {
+ const { done, value } = await Promise.race([reader.read(), aborted]);
+ if (done) break;
+ length += value.byteLength;
+ if (length > limit) {
+ void reader.cancel().catch(() => {});
+ throw new StorageFailure(502, `${this.label} response exceeds its size limit`);
+ }
+ chunks.push(value);
+ }
+ if (declared !== null && Number(declared) !== length)
+ throw new StorageFailure(502, `Invalid ${this.label.toLowerCase()} response`);
+ const bytes = new Uint8Array(length);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes;
+ } 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);
+ reader?.releaseLock();
+ }
+ }
+}
diff --git a/hosting/src/native-mcp.ts b/hosting/src/native-mcp.ts
new file mode 100644
index 00000000..4aa06346
--- /dev/null
+++ b/hosting/src/native-mcp.ts
@@ -0,0 +1,248 @@
+import { createMcpHandler, type Server } from '@modelcontextprotocol/server';
+import type { KilnToolContext } from '@instruktlabs/kiln/tools';
+import type { EvaluatorPortV2, IsolatedEvaluatorHost } from '@instruktlabs/kiln/evaluator';
+import { NativeProgramStore } from './native-programs';
+import { NativeAssetLibrary } from './native-assets';
+import type { NativeStorageOptions } from './native-http';
+import { HttpFailure, privateResponse, readBounded, serviceFailure } from './http';
+
+export interface NativeMcpRuntime {
+ createServer: (context: KilnToolContext) => Server;
+ evaluatorPort: EvaluatorPortV2;
+}
+
+/** Installed-package production route. A failed isolation probe has no fallback. */
+export async function loadNativeMcpRuntime(
+ host: IsolatedEvaluatorHost = { bwrapPath: '/usr/bin/bwrap' },
+): Promise<NativeMcpRuntime> {
+ let engine: { createKilnMcpServer: NativeMcpRuntime['createServer'] };
+ let evaluator: typeof import('@instruktlabs/kiln/evaluator');
+ 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.
+ engine = await import(new URL('../dist/mcp-engine.mjs', entry).href);
+ evaluator = await import('@instruktlabs/kiln/evaluator');
+ } catch {
+ throw new Error('Native engine installation is unavailable');
+ }
+ try {
+ await evaluator.assertIsolatedEvaluatorReady(host);
+ return {
+ createServer: engine.createKilnMcpServer,
+ evaluatorPort: {
+ render: (code, options, controls) =>
+ evaluator.renderGLBViaIsolatedEvaluator(code, options, { ...controls, host }),
+ },
+ };
+ } catch {
+ throw new Error('Native isolation readiness failed; no evaluator is available');
+ }
+}
+
+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 };
+ return runtime.createServer({
+ programStore: new NativeProgramStore(storage),
+ assetLibrary: new NativeAssetLibrary(storage),
+ evaluatorProfile: 'evaluator-required',
+ evaluatorPort: {
+ render: async (code, renderOptions, controls) => {
+ if (controller.signal.aborted) throw abortError();
+ evaluations++;
+ try {
+ return await runtime.evaluatorPort.render(code, renderOptions, controls);
+ } finally {
+ evaluations--;
+ release();
+ }
+ },
+ },
+ 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
new file mode 100644
index 00000000..8595e836
--- /dev/null
+++ b/hosting/src/native-programs.ts
@@ -0,0 +1,111 @@
+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/program-contract.ts b/hosting/src/program-contract.ts
new file mode 100644
index 00000000..f24f1c99
--- /dev/null
+++ b/hosting/src/program-contract.ts
@@ -0,0 +1,2 @@
+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
new file mode 100644
index 00000000..67b318d7
--- /dev/null
+++ b/hosting/src/programs.ts
@@ -0,0 +1,125 @@
+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/tenant-worker.ts b/hosting/src/tenant-worker.ts
new file mode 100644
index 00000000..77fda7f2
--- /dev/null
+++ b/hosting/src/tenant-worker.ts
@@ -0,0 +1,8 @@
+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
new file mode 100644
index 00000000..d2d5b60e
--- /dev/null
+++ b/hosting/src/tenant.ts
@@ -0,0 +1,152 @@
+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';
+
+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;
+
+ 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);
+ }
+
+ async alarm(): Promise<void> {
+ 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 (
+ ['/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 (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')
+ 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
new file mode 100644
index 00000000..f640abf1
--- /dev/null
+++ b/hosting/src/worker.ts
@@ -0,0 +1,80 @@
+import { OAuthAuthorizationServer, OAuthResourceServer } from '@cloudflare/workers-oauth-provider';
+import { authorize, authorizationFailure, SCOPES, type SignInEnv } from './auth';
+import { forwardTenant, type TenantEnv } from './gateway';
+import { boundedRequest, HttpFailure, privateResponse } from './http';
+
+export interface Env extends SignInEnv, TenantEnv {
+ OAUTH_KV: KVNamespace;
+ PUBLIC_ORIGIN: string;
+}
+
+export default {
+ async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
+ try {
+ const configured = new URL(env.PUBLIC_ORIGIN);
+ if (configured.protocol !== 'https:' || configured.origin !== env.PUBLIC_ORIGIN)
+ throw new Error('Invalid origin configuration');
+ const origin = configured.origin;
+ 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 resource = `${origin}/mcp`;
+ const auth = new OAuthAuthorizationServer<Env>({
+ issuer: origin,
+ resources: [resource],
+ authorizeEndpoint: `${origin}/authorize`,
+ tokenEndpoint: `${origin}/oauth/token`,
+ clientRegistrationEndpoint: `${origin}/register`,
+ clientIdMetadataDocumentEnabled: true,
+ scopesSupported: SCOPES,
+ accessTokenTTL: 900,
+ refreshTokenTTL: 30 * 24 * 60 * 60,
+ // Deliberately do not log request data or provider error descriptions.
+ onError: () => {},
+ });
+ const protectedResource = new OAuthResourceServer<Env>({
+ resourceMetadata: { resource, authorization_servers: [origin] },
+ requiredScopes: ['kiln:use'],
+ validateToken: (bindings) => (audience, token) =>
+ auth.validateToken(audience, token, bindings),
+ 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 === '/authorize' || url.pathname === '/oauth/github/callback') {
+ if (!env.GITHUB_CLIENT_ID || !env.GITHUB_CLIENT_SECRET)
+ throw new HttpFailure(503, 'Sign-in is not configured');
+ response = await authorize(
+ await boundedRequest(request, 16_384),
+ auth.getOAuthApi(env),
+ origin,
+ env,
+ );
+ } 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>;
diff --git a/hosting/test/asset-index.test.mjs b/hosting/test/asset-index.test.mjs
new file mode 100644
index 00000000..fcabcd49
--- /dev/null
+++ b/hosting/test/asset-index.test.mjs
@@ -0,0 +1,181 @@
+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
new file mode 100644
index 00000000..1915f548
--- /dev/null
+++ b/hosting/test/auth.test.mjs
@@ -0,0 +1,622 @@
+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 { build } from 'esbuild';
+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
+
+const origin = 'https://kiln.example.com';
+let runtime;
+let outboundCalls = 0;
+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',
+ external: ['cloudflare:workers'],
+ });
+ runtime = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ script: bundle.outputFiles[0].text,
+ compatibilityDate: '2026-10-06',
+ compatibilityFlags: ['global_fetch_strictly_public'],
+ kvNamespaces: ['OAUTH_KV'],
+ durableObjects: { TENANTS: 'TestTenant' },
+ bindings: {
+ PUBLIC_ORIGIN: origin,
+ GITHUB_CLIENT_ID: 'fixture-client',
+ GITHUB_CLIENT_SECRET: 'fixture-secret-not-a-real-credential',
+ },
+ outboundService: async (request) => {
+ outboundCalls++;
+ 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') {
+ const token = request.headers.get('authorization');
+ assert.match(token, /^Bearer fixture-(alice|bob)$/);
+ return Response.json({
+ id: token.endsWith('alice') ? 1001 : 1002,
+ login: 'not-used-as-identity',
+ });
+ }
+ throw new Error(`Unexpected outbound URL ${new URL(request.url).origin}`);
+ },
+ }),
+ );
+});
+after(async () => runtime?.dispose());
+
+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 = 'approve' } = {}) {
+ 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 approved = await approve(start);
+ assert.equal(approved.status, 302);
+ const upstream = new URL(approved.headers.get('location'));
+ assert.equal(upstream.origin, 'https://github.com');
+ assert.equal(upstream.searchParams.get('code_challenge_method'), 'S256');
+ assert.equal(upstream.searchParams.get('scope'), '');
+ const callback = `${origin}/oauth/github/callback?${new URLSearchParams({ state: upstream.searchParams.get('state'), code: user })}`;
+ 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),
+ };
+}
+
+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/list' }),
+ });
+}
+
+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('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/);
+ 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('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 from a separate tenant Worker', async () => {
+ const [gateway, storage] = await Promise.all(
+ ['worker', 'tenant-worker'].map((entry) =>
+ build({
+ entryPoints: [fileURLToPath(new URL(`../src/${entry}.ts`, import.meta.url))],
+ bundle: true,
+ write: false,
+ format: 'esm',
+ platform: 'browser',
+ 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'],
+ durableObjects: {
+ TENANTS: { className: 'KilnTenant', scriptName: 'tenant', useSQLite: true },
+ },
+ bindings: {
+ PUBLIC_ORIGIN: origin,
+ GITHUB_CLIENT_ID: 'fixture-client',
+ GITHUB_CLIENT_SECRET: 'fixture-only-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 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 name = digest(JSON.stringify(['kiln-tenant-v1', origin, 'github-1001']));
+ 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, 503);
+ const privateWorker = await server.getWorker('tenant');
+ assert.equal(
+ (
+ await privateWorker.fetch('https://tenant.internal/internal/artifacts', {
+ method: 'POST',
+ body: bytes,
+ })
+ ).status,
+ 404,
+ );
+ } finally {
+ await server.dispose();
+ }
+});
diff --git a/hosting/test/native-assets.test.mjs b/hosting/test/native-assets.test.mjs
new file mode 100644
index 00000000..e939e375
--- /dev/null
+++ b/hosting/test/native-assets.test.mjs
@@ -0,0 +1,387 @@
+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('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-mcp.test.mjs b/hosting/test/native-mcp.test.mjs
new file mode 100644
index 00000000..67d06346
--- /dev/null
+++ b/hosting/test/native-mcp.test.mjs
@@ -0,0 +1,390 @@
+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 { createKilnMcpServer, kilnMcpToolDefs } from '../../dist/mcp-engine.mjs';
+import { renderGLB } from '../../lib/render.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 runtime;
+let namespace;
+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'],
+ ['evaluator', 'evaluator/index'],
+ ].map(([name, file]) => [
+ `@instruktlabs/kiln/${name}`,
+ fileURLToPath(new URL(`../../lib/${file}.js`, import.meta.url)),
+ ]),
+ ),
+ });
+ ({ createNativeMcpHandler, loadNativeMcpRuntime } = await import(
+ new URL('../../.cache/hosted-mcp-test/native-mcp.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({
+ 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');
+});
+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);
+ },
+ },
+) {
+ const handler = createNativeMcpHandler(
+ { createServer: createKilnMcpServer, evaluatorPort: evaluator },
+ {
+ 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: {} })
+ .map((def) => def.name)
+ .sort();
+ const current = await rpc(handler, 'tools/list');
+ assert.deepEqual(current.tools.map((item) => item.name).sort(), expected);
+ 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);
+ 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 () => {
+ const first = host('lifecycle');
+ 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'));
+ const saved = await tool(first, 'kiln_save', {
+ programRef: validated.programRef,
+ collection: 'project',
+ name: 'HTTP box',
+ });
+ 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 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('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('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
new file mode 100644
index 00000000..3eb312ba
--- /dev/null
+++ b/hosting/test/native-programs.test.mjs
@@ -0,0 +1,280 @@
+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/programs.test.mjs b/hosting/test/programs.test.mjs
new file mode 100644
index 00000000..fd4efa01
--- /dev/null
+++ b/hosting/test/programs.test.mjs
@@ -0,0 +1,187 @@
+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/storage-fault-worker.ts b/hosting/test/storage-fault-worker.ts
new file mode 100644
index 00000000..661cb7c3
--- /dev/null
+++ b/hosting/test/storage-fault-worker.ts
@@ -0,0 +1,71 @@
+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;
+ 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 bucket = new Proxy(env.ARTIFACTS, {
+ get(target, key) {
+ if (key === 'put')
+ return async (...args: Parameters<R2Bucket['put']>) => {
+ const result = await target.put(...args);
+ if (fault('slow-ack')) await new Promise((resolve) => setTimeout(resolve, 1500));
+ 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;
+ },
+ });
+ this.artifacts = new ArtifactStore(
+ ctx,
+ bucket,
+ { maxBytes: 1024 * 1024, maxObjects: 32, maxGroups: 8 },
+ () => 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 === '/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
new file mode 100644
index 00000000..e1d3cb7b
--- /dev/null
+++ b/hosting/test/storage-fault.test.mjs
@@ -0,0 +1,103 @@
+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/`;
+
+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
new file mode 100644
index 00000000..06658957
--- /dev/null
+++ b/hosting/test/storage.test.mjs
@@ -0,0 +1,262 @@
+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 usage = async (owner) => (await send(owner, '/internal/usage')).json();
+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,
+ );
+});
+
+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
new file mode 100644
index 00000000..0fd3bc0b
--- /dev/null
+++ b/hosting/test/worker.ts
@@ -0,0 +1,15 @@
+import { DurableObject } 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,
+ });
+ }
+}
diff --git a/hosting/tsconfig.json b/hosting/tsconfig.json
new file mode 100644
index 00000000..7be393f5
--- /dev/null
+++ b/hosting/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "lib": ["ES2022"],
+ "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
new file mode 100644
index 00000000..48e2185c
--- /dev/null
+++ b/hosting/tsconfig.native.json
@@ -0,0 +1,16 @@
+{
+ "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/node": ["../lib/material-library-node.d.ts"],
+ "@instruktlabs/kiln/evaluator": ["../lib/evaluator/index.d.ts"],
+ "@instruktlabs/kiln/tools": ["../lib/tools/registry.d.ts"]
+ }
+ },
+ "include": ["src/native-*.ts"],
+ "exclude": []
+}
diff --git a/package.json b/package.json
index a54fadde..798b1e46 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,6 @@
{
- "name": "@kiln/engine",
- "private": true,
- "version": "0.10.0",
+ "name": "@instruktlabs/kiln",
+ "version": "1.0.0-rc.1",
"description": "Create and refine procedural 3D assets with JavaScript, image feedback, and reusable source revisions.",
"license": "MIT",
"author": "Matthew Kissinger",
@@ -12,66 +11,233 @@
},
"bin": {
"kiln": "./dist/cli.mjs",
- "kiln-init": "./scripts/create-workspace.mjs"
+ "kiln-init": "./scripts/create-workspace.mjs",
+ "kiln-mcp": "./dist/mcp-server.mjs"
},
"exports": {
- "./assets": "./src/assets.ts",
- "./assets/node": "./src/assets-node.ts",
- "./projects": "./src/projects.ts",
- "./projects/node": "./src/projects-node.ts",
- "./project-bundle": "./src/project-bundle.ts",
- "./project-bundle/node": "./src/project-bundle-node.ts",
- "./workspace": "./src/workspace.ts",
- "./workspace/node": "./src/workspace-node.ts",
- "./material-library": "./src/material-library.ts",
- "./material-library/node": "./src/material-library-node.ts",
- "./material-presets": "./src/material-presets.ts",
- "./live-review": "./src/live-review.ts",
- "./live-review/node": "./src/live-review-node.ts",
- "./asset-export": "./src/asset-export.ts",
- ".": "./src/cli.ts",
- "./agent": "./src/agent/index.ts",
- "./tools": "./src/tools/registry.ts",
- "./arena": "./src/arena/index.ts",
- "./render": "./src/render.ts",
- "./evaluator": "./src/evaluator/index.ts",
- "./requirements": "./src/requirements.ts",
- "./requirements/migration": "./src/contracts/requirements-migration.ts",
- "./kit": "./src/kit.ts",
- "./palette": "./src/palette.ts",
- "./views": "./src/views/index.ts",
- "./validation": "./src/validation.ts",
- "./primitives": "./src/primitives.ts",
- "./geometry": "./src/geometry.ts",
- "./deform": "./src/deform.ts",
- "./sweep": "./src/sweep.ts",
- "./implicit": "./src/implicit.ts",
- "./programs": "./src/program-store.ts",
- "./programs/node": "./src/program-store-node.ts",
- "./cache": "./src/build-cache.ts",
- "./cache/node": "./src/build-cache-node.ts",
- "./profile": "./src/profile.ts",
- "./architecture": "./src/architecture.ts",
- "./assembly": "./src/assembly.ts",
- "./character": "./src/character.ts",
- "./vehicle": "./src/vehicle.ts",
- "./material-recipes": "./src/material-recipes.ts",
- "./material-resources": "./src/material-resources.ts",
- "./texture-resolver": "./src/texture-resolver.ts",
- "./material-recipe-runtime": "./src/material-recipe-runtime.ts",
- "./material-recipe-prompt": "./src/material-recipe-prompt.ts",
- "./material-metrics": "./src/material-metrics.ts",
- "./prompt-api": "./src/prompt-api.ts",
- "./discovery": "./src/discovery/index.ts",
- "./metrics": "./src/metrics.ts",
- "./inspect": "./src/inspect.ts",
- "./contracts": "./src/contracts/index.ts",
- "./qa": "./src/qa/index.ts",
- "./composer": "./src/composer/index.ts",
- "./composer/agent": "./src/composer/agent/index.ts",
- "./world-runtime": "./src/composer/terrain-runtime.ts"
+ "./assets": {
+ "types": "./lib/assets.d.ts",
+ "import": "./lib/assets.js"
+ },
+ "./assets/node": {
+ "types": "./lib/assets-node.d.ts",
+ "import": "./lib/assets-node.js"
+ },
+ "./projects": {
+ "types": "./lib/projects.d.ts",
+ "import": "./lib/projects.js"
+ },
+ "./projects/node": {
+ "types": "./lib/projects-node.d.ts",
+ "import": "./lib/projects-node.js"
+ },
+ "./project-bundle": {
+ "types": "./lib/project-bundle.d.ts",
+ "import": "./lib/project-bundle.js"
+ },
+ "./project-bundle/node": {
+ "types": "./lib/project-bundle-node.d.ts",
+ "import": "./lib/project-bundle-node.js"
+ },
+ "./workspace": {
+ "types": "./lib/workspace.d.ts",
+ "import": "./lib/workspace.js"
+ },
+ "./workspace/node": {
+ "types": "./lib/workspace-node.d.ts",
+ "import": "./lib/workspace-node.js"
+ },
+ "./material-library": {
+ "types": "./lib/material-library.d.ts",
+ "import": "./lib/material-library.js"
+ },
+ "./material-library/node": {
+ "types": "./lib/material-library-node.d.ts",
+ "import": "./lib/material-library-node.js"
+ },
+ "./material-presets": {
+ "types": "./lib/material-presets.d.ts",
+ "import": "./lib/material-presets.js"
+ },
+ "./live-review": {
+ "types": "./lib/live-review.d.ts",
+ "import": "./lib/live-review.js"
+ },
+ "./live-review/node": {
+ "types": "./lib/live-review-node.d.ts",
+ "import": "./lib/live-review-node.js"
+ },
+ "./asset-export": {
+ "types": "./lib/asset-export.d.ts",
+ "import": "./lib/asset-export.js"
+ },
+ ".": {
+ "types": "./lib/index.d.ts",
+ "import": "./lib/index.js"
+ },
+ "./agent": {
+ "types": "./lib/agent/index.d.ts",
+ "import": "./lib/agent/index.js"
+ },
+ "./tools": {
+ "types": "./lib/tools/registry.d.ts",
+ "import": "./lib/tools/registry.js"
+ },
+ "./arena": {
+ "types": "./lib/arena/index.d.ts",
+ "import": "./lib/arena/index.js"
+ },
+ "./render": {
+ "types": "./lib/render.d.ts",
+ "import": "./lib/render.js"
+ },
+ "./evaluator": {
+ "types": "./lib/evaluator/index.d.ts",
+ "import": "./lib/evaluator/index.js"
+ },
+ "./requirements": {
+ "types": "./lib/requirements.d.ts",
+ "import": "./lib/requirements.js"
+ },
+ "./requirements/migration": {
+ "types": "./lib/contracts/requirements-migration.d.ts",
+ "import": "./lib/contracts/requirements-migration.js"
+ },
+ "./kit": {
+ "types": "./lib/kit.d.ts",
+ "import": "./lib/kit.js"
+ },
+ "./palette": {
+ "types": "./lib/palette.d.ts",
+ "import": "./lib/palette.js"
+ },
+ "./views": {
+ "types": "./lib/views/index.d.ts",
+ "import": "./lib/views/index.js"
+ },
+ "./validation": {
+ "types": "./lib/validation.d.ts",
+ "import": "./lib/validation.js"
+ },
+ "./primitives": {
+ "types": "./lib/primitives.d.ts",
+ "import": "./lib/primitives.js"
+ },
+ "./geometry": {
+ "types": "./lib/geometry.d.ts",
+ "import": "./lib/geometry.js"
+ },
+ "./deform": {
+ "types": "./lib/deform.d.ts",
+ "import": "./lib/deform.js"
+ },
+ "./sweep": {
+ "types": "./lib/sweep.d.ts",
+ "import": "./lib/sweep.js"
+ },
+ "./implicit": {
+ "types": "./lib/implicit.d.ts",
+ "import": "./lib/implicit.js"
+ },
+ "./programs": {
+ "types": "./lib/program-store.d.ts",
+ "import": "./lib/program-store.js"
+ },
+ "./programs/node": {
+ "types": "./lib/program-store-node.d.ts",
+ "import": "./lib/program-store-node.js"
+ },
+ "./cache": {
+ "types": "./lib/build-cache.d.ts",
+ "import": "./lib/build-cache.js"
+ },
+ "./cache/node": {
+ "types": "./lib/build-cache-node.d.ts",
+ "import": "./lib/build-cache-node.js"
+ },
+ "./profile": {
+ "types": "./lib/profile.d.ts",
+ "import": "./lib/profile.js"
+ },
+ "./architecture": {
+ "types": "./lib/architecture.d.ts",
+ "import": "./lib/architecture.js"
+ },
+ "./assembly": {
+ "types": "./lib/assembly.d.ts",
+ "import": "./lib/assembly.js"
+ },
+ "./character": {
+ "types": "./lib/character.d.ts",
+ "import": "./lib/character.js"
+ },
+ "./vehicle": {
+ "types": "./lib/vehicle.d.ts",
+ "import": "./lib/vehicle.js"
+ },
+ "./material-recipes": {
+ "types": "./lib/material-recipes.d.ts",
+ "import": "./lib/material-recipes.js"
+ },
+ "./material-resources": {
+ "types": "./lib/material-resources.d.ts",
+ "import": "./lib/material-resources.js"
+ },
+ "./texture-resolver": {
+ "types": "./lib/texture-resolver.d.ts",
+ "import": "./lib/texture-resolver.js"
+ },
+ "./material-recipe-runtime": {
+ "types": "./lib/material-recipe-runtime.d.ts",
+ "import": "./lib/material-recipe-runtime.js"
+ },
+ "./material-recipe-prompt": {
+ "types": "./lib/material-recipe-prompt.d.ts",
+ "import": "./lib/material-recipe-prompt.js"
+ },
+ "./material-metrics": {
+ "types": "./lib/material-metrics.d.ts",
+ "import": "./lib/material-metrics.js"
+ },
+ "./prompt-api": {
+ "types": "./lib/prompt-api.d.ts",
+ "import": "./lib/prompt-api.js"
+ },
+ "./discovery": {
+ "types": "./lib/discovery/index.d.ts",
+ "import": "./lib/discovery/index.js"
+ },
+ "./metrics": {
+ "types": "./lib/metrics.d.ts",
+ "import": "./lib/metrics.js"
+ },
+ "./inspect": {
+ "types": "./lib/inspect.d.ts",
+ "import": "./lib/inspect.js"
+ },
+ "./contracts": {
+ "types": "./lib/contracts/index.d.ts",
+ "import": "./lib/contracts/index.js"
+ },
+ "./qa": {
+ "types": "./lib/qa/index.d.ts",
+ "import": "./lib/qa/index.js"
+ },
+ "./composer": {
+ "types": "./lib/composer/index.d.ts",
+ "import": "./lib/composer/index.js"
+ },
+ "./composer/agent": {
+ "types": "./lib/composer/agent/index.d.ts",
+ "import": "./lib/composer/agent/index.js"
+ },
+ "./world-runtime": {
+ "types": "./lib/composer/terrain-runtime.d.ts",
+ "import": "./lib/composer/terrain-runtime.js"
+ }
},
"files": [
+ "lib/",
"dist/viewer/",
"src/**/*.ts",
"src/**/*.mjs",
@@ -83,6 +249,8 @@
"plugin.json",
".claude-plugin/",
".codex-plugin/",
+ ".agents/plugins/",
+ "plugins/kiln-engine/",
".mcp.json",
"scripts/create-workspace.mjs",
"scripts/package-plugin.mjs",
@@ -91,7 +259,27 @@
"render-service/package-lock.json",
"render-service/README.md",
"skills/",
- "docs/",
+ "docs/architecture.md",
+ "docs/cameras.md",
+ "docs/chatgpt.md",
+ "docs/collections.md",
+ "docs/community-exporter.md",
+ "docs/engine-handoff.md",
+ "docs/examples.md",
+ "docs/export-profiles.md",
+ "docs/extending.md",
+ "docs/geometry.md",
+ "docs/google.md",
+ "docs/harnesses.md",
+ "docs/install.md",
+ "docs/material-library.md",
+ "docs/migration.md",
+ "docs/programs.md",
+ "docs/projects-and-live-review.md",
+ "docs/rendering.md",
+ "docs/runtime.md",
+ "docs/sdk.md",
+ "docs/tools.md",
"README.md",
"CONTRIBUTING.md",
"LICENSE",
@@ -124,7 +312,9 @@
"site:build": "bun run --cwd site build",
"smoke:harness": "node scripts/harness-smoke.mjs",
"dogfood:gallery": "node scripts/dogfood-gallery.mjs",
- "dogfood:tier2": "node scripts/tier2-dogfood.mjs"
+ "dogfood:tier2": "node scripts/tier2-dogfood.mjs",
+ "build:sdk": "node scripts/build-sdk.mjs",
+ "test:sdk": "node scripts/smoke-sdk.mjs"
},
"dependencies": {
"@gltf-transform/core": "4.5.1",
@@ -181,5 +371,17 @@
"optionalDependencies": {
"@napi-rs/canvas": "1.0.10",
"webgpu": "0.6.2"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/instruktlabs/kiln.git"
+ },
+ "homepage": "https://github.com/instruktlabs/kiln",
+ "bugs": {
+ "url": "https://github.com/instruktlabs/kiln/issues"
+ },
+ "publishConfig": {
+ "access": "public",
+ "provenance": true
}
}
diff --git a/plugin.json b/plugin.json
index 33795400..70fb1275 100644
--- a/plugin.json
+++ b/plugin.json
@@ -2,8 +2,15 @@
"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": "0.10.0",
+ "version": "1.0.0-rc.1",
"license": "MIT",
- "homepage": "https://github.com/matthew-kissinger/kiln",
- "keywords": ["3d", "glb", "gltf", "asset-generation", "three.js", "gamedev"]
+ "homepage": "https://github.com/instruktlabs/kiln",
+ "keywords": [
+ "3d",
+ "glb",
+ "gltf",
+ "asset-generation",
+ "three.js",
+ "gamedev"
+ ]
}
diff --git a/plugins/kiln-engine/.claude-plugin/plugin.json b/plugins/kiln-engine/.claude-plugin/plugin.json
new file mode 100644
index 00000000..0fb53522
--- /dev/null
+++ b/plugins/kiln-engine/.claude-plugin/plugin.json
@@ -0,0 +1,18 @@
+{
+ "name": "kiln-engine",
+ "version": "1.0.0-rc.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"
+ },
+ "homepage": "https://github.com/instruktlabs/kiln",
+ "repository": "https://github.com/instruktlabs/kiln",
+ "license": "MIT",
+ "keywords": [
+ "3d",
+ "glb",
+ "gltf",
+ "asset-generation",
+ "gamedev"
+ ]
+}
diff --git a/plugins/kiln-engine/LICENSE b/plugins/kiln-engine/LICENSE
new file mode 100644
index 00000000..f2bfd501
--- /dev/null
+++ b/plugins/kiln-engine/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Matthew Kissinger
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/kiln-engine/README.md b/plugins/kiln-engine/README.md
new file mode 100644
index 00000000..39daddbb
--- /dev/null
+++ b/plugins/kiln-engine/README.md
@@ -0,0 +1,27 @@
+# Kiln Engine local plugin
+
+**Release candidate.** Use the reviewed archive via `--archive` for local qualification. Registry installation requires this exact version to be available on npm.
+
+Version 1.0.0-rc.1, published by Instrukt Labs under the MIT license.
+
+Ask your coding agent to set up a Kiln workspace. The setup skill installs
+`@instruktlabs/[email protected]` with npm and creates a separate asset workspace.
+Use a supported Node.js installation with npm; no Bun, engine clone or separate
+model API key is required. The workspace's START.md explains how to reopen it.
+
+The plugin registers setup only. The workspace supplies the authoring skills
+and one local MCP server, `kiln_workspace`. Open Claude Code in that workspace;
+launch Codex there with `node codex.mjs`. Accept the host's ordinary trust prompts
+and verify live tool discovery before authoring.
+
+The engine installation and your assets stay outside the disposable plugin cache.
+Plugin removal or updating its cached files does not delete them. An existing
+workspace remains on its installed engine until an explicit managed upgrade.
+Read [setup and upgrade guidance](skills/kiln-setup-workspace/references/plugin-install.md).
+
+CPU rendering is available locally. Material appearance requires a qualified
+renderer; follow the setup skill's renderer checks rather than assuming GPU support.
+Hosted ChatGPT access is a separate integration, and this local bundle is not a
+public OpenAI directory submission.
+
+[Source and issues](https://github.com/instruktlabs/kiln)
diff --git a/plugins/kiln-engine/package-provenance.json b/plugins/kiln-engine/package-provenance.json
new file mode 100644
index 00000000..5a14c490
--- /dev/null
+++ b/plugins/kiln-engine/package-provenance.json
@@ -0,0 +1,15 @@
+{
+ "schemaVersion": 1,
+ "kind": "kiln-local-plugin",
+ "engineVersion": "1.0.0-rc.1",
+ "files": {
+ ".claude-plugin/plugin.json": "sha256:5bf6fedd28a3b9ee3fa93bd6a89874a4ed5993c62473e05ac77960f4040be0d3",
+ "LICENSE": "sha256:cdba278ebf1d6de618869936226bf03be4887179c128efc7aaa13d22034826a5",
+ "plugin.json": "sha256:2410014ba1112930d7a1b20dd1e6ce12508b26551a6cce970a00b2c84015ef90",
+ "README.md": "sha256:5c773283968b63a29c05edf1f517cc0b5e5d9d44880442a4f76b35a540300744",
+ "runtime.json": "sha256:4deba826fd99f813d0a401add295f99b75937377af6cb45539bf63c9ff58d6f5",
+ "scripts/setup-workspace.mjs": "sha256:0936f482a213706cf1576da11e57d40993b90f42b486f262e55d38d8d27b2e4d",
+ "skills/kiln-setup-workspace/references/plugin-install.md": "sha256:84f4ce4c9620aae1e6b37a6a04f5c874feae507c9e7a2f24fe62e48bbe6c09bd",
+ "skills/kiln-setup-workspace/SKILL.md": "sha256:9dbcb66514e21ea11b097bb1cd4b27b616834ded3e8182ea804f370add37a69f"
+ }
+}
diff --git a/plugins/kiln-engine/plugin.json b/plugins/kiln-engine/plugin.json
new file mode 100644
index 00000000..5e034443
--- /dev/null
+++ b/plugins/kiln-engine/plugin.json
@@ -0,0 +1,38 @@
+{
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
+ "name": "kiln-engine",
+ "version": "1.0.0-rc.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"
+ },
+ "homepage": "https://github.com/instruktlabs/kiln",
+ "repository": "https://github.com/instruktlabs/kiln",
+ "license": "MIT",
+ "keywords": [
+ "3d",
+ "glb",
+ "gltf",
+ "asset-generation",
+ "gamedev"
+ ],
+ "extensions": {
+ "com.openai": {
+ "interface": {
+ "displayName": "Kiln Engine",
+ "shortDescription": "Create editable 3D assets in a local workspace",
+ "longDescription": "Install the pinned Kiln engine and set up a workspace with local MCP tools and maintained authoring skills. Your coding agent supplies the model.",
+ "developerName": "Instrukt Labs",
+ "category": "Developer Tools",
+ "capabilities": [
+ "Read",
+ "Write"
+ ],
+ "defaultPrompt": [
+ "Set up a Kiln workspace for this coding agent.",
+ "Check and upgrade my existing Kiln workspace."
+ ]
+ }
+ }
+ }
+}
diff --git a/plugins/kiln-engine/runtime.json b/plugins/kiln-engine/runtime.json
new file mode 100644
index 00000000..86a2a1dc
--- /dev/null
+++ b/plugins/kiln-engine/runtime.json
@@ -0,0 +1,4 @@
+{
+ "name": "@instruktlabs/kiln",
+ "version": "1.0.0-rc.1"
+}
diff --git a/plugins/kiln-engine/scripts/setup-workspace.mjs b/plugins/kiln-engine/scripts/setup-workspace.mjs
new file mode 100644
index 00000000..e0c774ab
--- /dev/null
+++ b/plugins/kiln-engine/scripts/setup-workspace.mjs
@@ -0,0 +1,337 @@
+#!/usr/bin/env node
+// Copied into the local plugin: keep this entry independent of the engine checkout.
+import { spawn } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import {
+ lstat,
+ mkdir,
+ mkdtemp,
+ open,
+ readFile,
+ readdir,
+ realpath,
+ rename,
+ rm,
+ stat,
+ writeFile,
+} from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const packageName = '@instruktlabs/kiln';
+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const exactVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:rc|dev)\.(0|[1-9]\d*))?$/;
+
+function inside(parent, child) {
+ const path = relative(parent, child);
+ return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));
+}
+
+async function exists(path) {
+ try {
+ await lstat(path);
+ return true;
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ return false;
+ }
+}
+
+// Canonicalize future paths too, including Windows junctions and macOS /var aliases.
+async function canonical(path) {
+ const target = resolve(path);
+ let ancestor = target;
+ while (true) {
+ try {
+ return resolve(await realpath(ancestor), relative(ancestor, target));
+ } catch (error) {
+ if (error.code !== 'ENOENT' || dirname(ancestor) === ancestor) throw error;
+ ancestor = dirname(ancestor);
+ }
+ }
+}
+
+function defaultDataDirectory() {
+ if (process.platform === 'win32')
+ return join(process.env.LOCALAPPDATA || join(homedir(), 'AppData/Local'), 'InstruktLabs/Kiln');
+ return join(process.env.XDG_DATA_HOME || join(homedir(), '.local/share'), 'instruktlabs/kiln');
+}
+
+async function npmCli(explicit) {
+ const executable = await realpath(process.execPath);
+ const candidates = explicit
+ ? [explicit]
+ : [
+ process.env.npm_execpath,
+ join(dirname(executable), 'node_modules/npm/bin/npm-cli.js'),
+ resolve(dirname(executable), '../lib/node_modules/npm/bin/npm-cli.js'),
+ ];
+ for (const candidate of candidates.filter(Boolean)) {
+ if (!candidate.endsWith('npm-cli.js')) continue;
+ try {
+ if ((await stat(candidate)).isFile()) return await realpath(candidate);
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ }
+ }
+ throw new Error(
+ 'Cannot locate npm. Install Node with npm, or pass --npm-cli /absolute/path/to/npm-cli.js.',
+ );
+}
+
+function installWithNpm(npm, args, cwd) {
+ return new Promise((done, fail) => {
+ const child = spawn(process.execPath, [npm, ...args], {
+ cwd,
+ shell: false,
+ windowsHide: true,
+ stdio: ['ignore', 'ignore', 'pipe'],
+ });
+ let stderr = '';
+ let timedOut = false;
+ child.stderr.on('data', (data) => {
+ stderr = (stderr + data).slice(-6000);
+ });
+ const timer = setTimeout(() => {
+ timedOut = true;
+ child.kill();
+ }, 300000);
+ child.once('error', (error) => {
+ clearTimeout(timer);
+ fail(error);
+ });
+ child.once('close', (code) => {
+ clearTimeout(timer);
+ if (timedOut)
+ fail(
+ new Error('npm installation exceeded five minutes. Retry after checking network access.'),
+ );
+ else if (code !== 0) fail(new Error(`npm installation failed (${code}):\n${stderr}`));
+ else done();
+ });
+ });
+}
+
+async function readJson(path) {
+ return JSON.parse(await readFile(path, 'utf8'));
+}
+
+async function verifyPackage(root, pin) {
+ const runtime = join(root, 'node_modules/@instruktlabs/kiln');
+ const pkg = await readJson(join(runtime, 'package.json'));
+ if (pkg.name !== pin.name || pkg.version !== pin.version)
+ throw new Error(`Installed package identity does not match ${pin.name}@${pin.version}.`);
+ if (!inside(root, await realpath(runtime)))
+ throw new Error('Installed runtime escapes its version directory.');
+ if (!(await stat(join(runtime, 'scripts/create-workspace.mjs'))).isFile())
+ throw new Error('Installed runtime has no workspace setup entry.');
+ return runtime;
+}
+
+async function verifyRuntime(root, pin, archiveHash) {
+ try {
+ const marker = await readJson(join(root, 'kiln-runtime.json'));
+ if (marker.schemaVersion !== 1 || marker.name !== pin.name || marker.version !== pin.version)
+ throw new Error('Runtime marker identity mismatch.');
+ if (marker.lockSha256 !== hash(await readFile(join(root, 'package-lock.json'))))
+ throw new Error('Runtime lockfile changed.');
+ if (archiveHash && marker.archiveSha256 !== archiveHash)
+ throw new Error(
+ 'Runtime was installed from a different archive. Use a separate --data-dir for this candidate.',
+ );
+ return await verifyPackage(root, pin);
+ } catch (error) {
+ throw new Error(
+ `Cannot reuse runtime at ${root}: ${error.message}. Existing files were left unchanged.`,
+ { cause: error },
+ );
+ }
+}
+
+async function removeStage(stage, runtimes) {
+ const resolvedStage = await realpath(stage);
+ const resolvedRuntimes = await realpath(runtimes);
+ if (!inside(resolvedRuntimes, resolvedStage) || dirname(resolvedStage) !== resolvedRuntimes)
+ throw new Error('Refusing to remove a staging directory outside the runtime store.');
+ await rm(resolvedStage, { recursive: true, force: true });
+}
+
+async function installRuntime(data, pin, archive, archiveHash, options) {
+ const runtimes = join(data, 'runtimes');
+ if (relative(runtimes, await canonical(runtimes)) !== '')
+ throw new Error(
+ 'The runtime store must remain inside its persistent data directory, without a redirected runtimes path.',
+ );
+ const target = join(runtimes, pin.version);
+ if (await exists(target)) return verifyRuntime(target, pin, archiveHash);
+ if (options.mode === 'check')
+ throw new Error(`Pinned runtime ${pin.version} is not installed; check makes no changes.`);
+ const npm = options.run ? options.npmPath : await npmCli(options.npmPath);
+ await mkdir(runtimes, { recursive: true });
+ // Serialize competing setup processes without treating a crashed lock as safe to delete.
+ const lockPath = join(runtimes, `${pin.version}.lock`);
+ let lock;
+ try {
+ lock = await open(lockPath, 'wx');
+ } catch (error) {
+ if (error.code !== 'EEXIST') throw error;
+ throw new Error(
+ `Runtime setup is locked at ${lockPath}. Wait for the other setup, or verify it has stopped before removing its lock.`,
+ );
+ }
+ let stage;
+ try {
+ if (await exists(target)) return await verifyRuntime(target, pin, archiveHash);
+ stage = await mkdtemp(join(runtimes, `${pin.version}.staging-`));
+ await writeFile(
+ join(stage, 'package.json'),
+ JSON.stringify({ name: 'kiln-plugin-runtime', version: '0.0.0', private: true }),
+ );
+ const args = [
+ 'install',
+ archive || `${pin.name}@${pin.version}`,
+ '--save-exact',
+ '--ignore-scripts',
+ '--omit=dev',
+ '--include=optional',
+ '--no-audit',
+ '--no-fund',
+ '--registry=https://registry.npmjs.org',
+ ];
+ if (options.run) await options.run(args, stage);
+ else await installWithNpm(npm, args, stage);
+ await verifyPackage(stage, pin);
+ await writeFile(
+ join(stage, 'kiln-runtime.json'),
+ `${JSON.stringify(
+ {
+ schemaVersion: 1,
+ ...pin,
+ lockSha256: hash(await readFile(join(stage, 'package-lock.json'))),
+ archiveSha256: archiveHash || null,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ if (await exists(target))
+ throw new Error('The runtime destination appeared during setup; no files were replaced.');
+ await rename(stage, target);
+ stage = undefined;
+ return await verifyRuntime(target, pin, archiveHash);
+ } finally {
+ try {
+ if (stage) await removeStage(stage, runtimes);
+ } finally {
+ await lock.close();
+ await rm(lockPath);
+ }
+ }
+}
+
+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))
+ throw new Error('Unknown workspace setup mode.');
+ if (!options.directory) throw new Error('Provide a workspace directory.');
+ if (
+ options.skills &&
+ (mode !== 'create' ||
+ !Array.isArray(options.skills) ||
+ options.skills.some((name) => !['compose', 'batch'].includes(name)))
+ )
+ throw new Error('Optional skills compose,batch apply only to workspace creation.');
+ const plugin = await canonical(
+ options.pluginRoot || resolve(dirname(fileURLToPath(import.meta.url)), '..'),
+ );
+ const pin = await readJson(join(plugin, 'runtime.json'));
+ 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.');
+ const directory = await canonical(options.directory);
+ const data = await canonical(options.dataDirectory || defaultDataDirectory());
+ for (const [a, b] of [
+ [plugin, directory],
+ [plugin, data],
+ [directory, data],
+ ])
+ 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 (!(await lstat(directory)).isDirectory() || (await readdir(directory)).length)
+ throw new Error(
+ 'The workspace destination must be an empty directory; no existing files were changed.',
+ );
+ }
+ const archive = options.archive ? await realpath(resolve(options.archive)) : undefined;
+ const archiveHash = archive ? hash(await readFile(archive)) : undefined;
+ const runtime = await installRuntime(
+ data,
+ { name: pin.name, version: pin.version },
+ archive,
+ archiveHash,
+ { ...options, mode },
+ );
+ const { createWorkspace } = await import(
+ pathToFileURL(join(runtime, 'scripts/create-workspace.mjs')).href
+ );
+ const workspace = await createWorkspace(directory, harness, {
+ installation: runtime,
+ ...(mode === 'create' ? {} : { [mode]: true }),
+ ...(options.skills ? { skills: options.skills } : {}),
+ });
+ return { runtime, workspace };
+}
+
+export function parseSetupArguments(args) {
+ if (args.includes('--help') || args.includes('-h')) return { help: true };
+ const values = [...args];
+ const directory = values.shift();
+ if (!directory || directory.startsWith('--'))
+ throw new Error('Provide a workspace directory. Run with --help for usage.');
+ const result = { directory };
+ const valueFlags = {
+ '--harness': 'harness',
+ '--data-dir': 'dataDirectory',
+ '--archive': 'archive',
+ '--npm-cli': 'npmPath',
+ '--skills': 'skills',
+ };
+ 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.');
+ result.mode = flag.slice(2);
+ } else if (Object.hasOwn(valueFlags, flag)) {
+ const value = values.shift();
+ if (!value || value.startsWith('--')) throw new Error(`Missing value for ${flag}.`);
+ if (Object.hasOwn(result, valueFlags[flag])) throw new Error(`Repeated option ${flag}.`);
+ result[valueFlags[flag]] = flag === '--skills' ? value.split(',') : value;
+ } else throw new Error(`Unknown option ${flag}.`);
+ }
+ return result;
+}
+
+if (
+ process.argv[1] &&
+ (await canonical(process.argv[1])) === (await realpath(fileURLToPath(import.meta.url)))
+) {
+ try {
+ const options = parseSetupArguments(process.argv.slice(2));
+ if (options.help)
+ console.log(
+ 'Usage: node scripts/setup-workspace.mjs <directory> [--harness claude|codex] [--skills compose,batch]\n node scripts/setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>',
+ );
+ else {
+ const result = await setupPluginWorkspace(options);
+ console.log(JSON.stringify(result, null, 2));
+ if (options.mode === 'check' && result.workspace.status !== 'current') process.exitCode = 1;
+ }
+ } catch (error) {
+ console.error(error.message);
+ process.exitCode = 1;
+ }
+}
diff --git a/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md b/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md
new file mode 100644
index 00000000..2f0aef1c
--- /dev/null
+++ b/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md
@@ -0,0 +1,108 @@
+---
+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.
+license: MIT
+metadata:
+ kiln-workflow: workspace
+---
+
+# Set up a workspace for asset authoring
+
+Kiln's engine installation and its asset workspaces serve different tasks. Establish whether the user wants asset authoring or engine development before running anything.
+
+Authoring an asset needs a workspace. Changing the engine's own behaviour does not; read `AGENTS.md` at the repository root instead and stay in the checkout.
+
+A workspace does not require a Kiln project. It supplies the tools and local stores for standalone assets, experiments, scenes or projects. Do not turn setup into project planning unless the user's task calls for related assets with a shared brief, inventory, art direction or material lock.
+
+Do not author assets inside the engine checkout. The authoring skills assume a workspace, and giving a model the engine implementation and the example collection alongside its task changes what it produces.
+
+## Create the workspace
+
+When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `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.
+
+```bash
+node scripts/create-workspace.mjs /absolute/empty-workspace --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.
+
+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.
+
+| `--harness` | Launch from the workspace |
+| --- | --- |
+| `claude` | `claude` |
+| `copilot` | `copilot` |
+| `cursor-agent` | `cursor-agent` |
+| `opencode` | `opencode` |
+| `agy` | `node agy.mjs` |
+| `codex` | `node codex.mjs` |
+| `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.
+
+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.
+
+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.
+
+## Verify the loadout before authoring
+
+Accept the project and MCP trust prompts, then confirm the server is actually live rather than assuming it from configuration. Call `kiln_discover` on `kiln_workspace` with `{ capabilities: true }`; it returns the runtime, source, export and camera contract and proves the tools resolved. For OpenCode, `opencode debug config` from the workspace is the configuration check: it shows the resolved `kiln_workspace` entry. `opencode mcp list` reports what OpenCode's shared background service loaded, so it can print "No MCP servers configured" in a correctly configured workspace. `node kiln.mjs discover --capabilities --json` from the workspace is the harness-independent proof; it reports the same runtime, collections and source storage as the MCP server. Compare `capabilities.engine.installUrl` with `runtime` in `.kiln/workspace.json`. A server named `kiln` from a global installation is a different thing. Do not substitute it silently; report the setup problem instead. When another agent is to do the authoring, start it as a separate harness process in the workspace directory (for OpenCode, `opencode run --standalone "<brief>"` after changing into the workspace); a subagent of the current session inherits this session's tools and never sees the workspace's MCP server, so it would be left with the CLI alone.
+
+When the task includes that separate author's result, retain its process/session
+identifier and wait for its terminal result. A launch message, session ID or empty
+log proves no authoring work. Use the harness's noninteractive mode with closed
+stdin for an unattended child, preserve stdout/stderr, and check the requested
+files and saved revision before reporting completion. If it stops early, report
+the incomplete handoff; confirm it has stopped before launching a replacement.
+
+For modeling, `kiln_discover({})` supplies a compact orientation and starting signatures. Use natural-language `query` for related operations, assemblies, and optional recipes; use exact `ids` for complete contracts. Discovery needs no separate search model or asset-category selection. The local equivalent is `node kiln.mjs discover --query "curved hollow tube"`, followed by `node kiln.mjs discover --id RETURNED_ID`.
+
+Confirm the installed skills are readable at `skills/` in the workspace, and read the relevant one from there rather than a global copy. Whether the harness also registers them natively depends on the harness.
+
+## Choose standalone or project work
+
+Standalone authoring is the default even when the workspace contains projects. An explicitly configured `KILN_PROJECT` opts into a default project; CLI `--no-project` or MCP `projectId: null` selects standalone work despite that setting. Materials, Live Review, saving and export do not require a project. The save collection named `project` is just a destination, not project membership.
+
+For a pack or other related work, create a project with `node kiln.mjs project create --id my-pack --name "My pack"`, or `kiln_project({action:"create", draft:{projectId:"my-pack", name:"My pack"}})`. Read the returned revision, then update its brief, design, inventory and material dependencies using `project update --expected` or the MCP `expectedRevision` field. Each supplied top-level field replaces its value, including the whole design object; read and merge preferences before updating. Authoring uses explicit `--project my-pack` / `projectId: "my-pack"`; add `--project-revision` / `projectRevision` when reproducing an exact configuration. Creating or viewing a project does not activate it for other calls.
+
+Read `skills/kiln-author-asset/references/projects-and-materials.md` in the generated workspace when configuring project records or pinned materials. Run `node kiln.mjs view` for the local library, materials, projects and Live Review. The dashboard observes authoring; feedback still goes to the agent's conversation. Verify the connected tool schemas before assuming optional host capabilities.
+
+Report the rest of the session's loadout at the same time. Skills and MCP servers from user-level configuration load here too, and an authoring session carrying a dozen unrelated skills spends context and invites the wrong tool. List whatever is registered that has nothing to do with this task and let the user decide whether to narrow it. Do not change their global configuration.
+
+## Wiring a workspace by hand
+
+`--harness` covers claude, codex, opencode, hermes, agy, copilot and cursor-agent. For any other harness, or an engine installed as a package elsewhere, assemble the same loadout in an empty directory: register the installation's `dist/mcp-server.mjs` as a stdio MCP server named `kiln_workspace`, give it `KILN_WORKSPACE` pointing at that directory, `KILN_PROGRAM_STORE` pointing at its `.kiln/programs`, plus `KILN_RENDER=auto` (the generated Antigravity entry also sets `KILN_RESULT_DETAIL=lean`, since that harness writes large results to files), and copy the skills you need from `skills/` into the one directory that harness reads (`.claude/skills/` for Claude Code, `.agents/skills/` for the others; OpenCode instead takes a `skills.paths` entry naming the copy).
+
+A hand-wired directory carries no manifest, so it gets no runtime preflight and `--repair` cannot correct its paths later. Prefer the generated workspace wherever the harness is supported, and tell the user which of the two they have.
+
+## Relocation and repair
+
+Moving the workspace or the engine installation breaks the generated absolute paths, and so does replacing the Node that setup validated.
+
+```bash
+node /current/kiln/scripts/create-workspace.mjs /absolute/empty-workspace --repair
+```
+
+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.
+
+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.
+
+Discovery replaces the removed `kiln_list_primitives` tool; its old `name`, `names`, and `category` selectors have no alias. Update copied guidance through the explicit workspace upgrade, then verify Discovery against the installation as above.
+
+## 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.
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
new file mode 100644
index 00000000..09df1184
--- /dev/null
+++ b/plugins/kiln-engine/skills/kiln-setup-workspace/references/plugin-install.md
@@ -0,0 +1,66 @@
+# Local plugin setup
+
+The local `kiln-engine` plugin installs Kiln's exact pinned npm version and creates
+an asset workspace. It carries setup guidance and a small installer; the engine,
+source stores and authored assets live outside the plugin cache. It needs a
+supported Node.js installation with npm, network access for first installation,
+and no separate model API key.
+
+Resolve the plugin root from this installed skill's absolute path: it is two
+directories above `skills/kiln-setup-workspace`. Confirm `runtime.json` and
+`scripts/setup-workspace.mjs` exist there. Do not assume plugin path variables are
+available in an ordinary shell, and do not substitute an engine checkout.
+
+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:
+
+```sh
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --harness codex
+```
+
+The installer verifies the package name and exact version from `runtime.json`.
+It uses npm with lifecycle scripts disabled and optional dependencies included.
+The versioned engine stays under `%LOCALAPPDATA%/InstruktLabs/Kiln` on Windows,
+or `$XDG_DATA_HOME/instruktlabs/kiln` on other systems, falling back to
+`~/.local/share/instruktlabs/kiln`. `--data-dir` selects another persistent directory.
+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
+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.
+
+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
+registered twice. An old global plugin/server named `kiln` is a separate
+installation: explain the conflict and surface its removal or disabling before
+continuing; do not silently redirect stores or edit global configuration.
+
+For an existing managed workspace, stop its harness session and run the new
+plugin's helper with `--check`, then `--upgrade` when an update is intended:
+
+```sh
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --check
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --upgrade
+```
+
+Check is read-only and reports a missing pinned engine without installing it.
+Upgrade installs that version when needed, then delegates to Kiln's managed
+upgrade. It preserves sources and saved assets and refuses conflicting edits to
+managed files. Resolve those conflicts explicitly rather than overwriting them.
+Use the same `--data-dir` if setup used a custom location. `--repair` corrects
+relocated paths without updating copied skills. Restart the harness afterward.
+
+For release qualification only, `--archive /absolute/candidate.tgz` installs a
+reviewed local archive with the same required identity. Different archive bytes
+at the same version need a separate data directory. An unpublished development
+plugin is not a working registry release; use its reviewed development archive.
+
+If installation fails, report the error. An unknown existing runtime is never
+replaced automatically. A setup lock may belong to another running installer;
+verify that process has stopped before removing a stale lock. If npm cannot be
+located, fix the Node/npm installation or pass `--npm-cli` with its actual
+`npm-cli.js` path. Never request registry credentials for this public package.
diff --git a/scripts/build-runtime.mjs b/scripts/build-runtime.mjs
index ca5c493d..12547e27 100644
--- a/scripts/build-runtime.mjs
+++ b/scripts/build-runtime.mjs
@@ -4,6 +4,7 @@ import { spawnSync } from 'node:child_process';
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { buildSdk } from './build-sdk.mjs';
const sha = (value) => createHash('sha256').update(value).digest('hex');
const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -135,6 +136,7 @@ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.ur
const entry = await buildRuntime(target);
console.log(`${entry.file} ${entry.bundleHash} (${entry.identity})`);
}
+ if (process.argv[2] === 'all') await buildSdk();
} catch (error) {
console.error(error.message);
process.exitCode = 1;
diff --git a/scripts/build-sdk.mjs b/scripts/build-sdk.mjs
new file mode 100644
index 00000000..2cba740b
--- /dev/null
+++ b/scripts/build-sdk.mjs
@@ -0,0 +1,194 @@
+#!/usr/bin/env node
+import { execFileSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
+import { dirname, join, relative, resolve, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { API } from 'typescript/unstable/async';
+import { SyntaxKind } from 'typescript/unstable/ast';
+
+const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const tsc = fileURLToPath(new URL('../node_modules/typescript/bin/tsc', import.meta.url));
+const posix = (path) => path.split(sep).join('/');
+const declarationPath = (path) => path.replace(/\.js$/, '.d.ts');
+
+async function filesIn(root) {
+ const files = [];
+ for (const item of await readdir(root, { withFileTypes: true })) {
+ const path = join(root, item.name);
+ if (item.isDirectory()) files.push(...(await filesIn(path)));
+ else files.push(path);
+ }
+ return files;
+}
+
+function moduleLiterals(node, visit) {
+ if (node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ExportDeclaration)
+ visit(node.moduleSpecifier);
+ if (node.kind === SyntaxKind.CallExpression && node.expression.kind === SyntaxKind.ImportKeyword)
+ visit(node.arguments[0]);
+ if (node.kind === SyntaxKind.ImportType) visit(node.argument.literal);
+ node.forEachChild((child) => {
+ moduleLiterals(child, visit);
+ });
+}
+
+/** Emit with the pinned compiler CLI; parse emitted modules to resolve ESM paths. */
+export async function buildSdk(root = repo) {
+ root = resolve(root);
+ const lib = join(root, 'lib');
+ const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
+ const entries = {};
+ const roots = [];
+ for (const [name, contract] of Object.entries(pkg.exports)) {
+ const target = typeof contract === 'string' ? contract : contract.import;
+ if (!/^\.\/(?:src\/.+\.ts|lib\/.+\.js)$/.test(target ?? ''))
+ throw new Error(`Unsupported SDK entry ${name}: ${target}`);
+ const source = target.replace(/^\.\/lib\//, './src/').replace(/\.js$/, '.ts');
+ const output = source.replace(/^\.\/src\//, './lib/').replace(/\.ts$/, '.js');
+ const sourcePath = resolve(root, source);
+ if (!sourcePath.startsWith(`${join(root, 'src')}${sep}`))
+ throw new Error(`SDK entry escapes src/: ${name}`);
+ roots.push(sourcePath);
+ entries[name] = { types: declarationPath(output), import: output };
+ }
+ // Worker URLs are runtime data, so the TypeScript import graph omits them.
+ if (pkg.exports['./evaluator'])
+ for (const name of ['worker.ts', 'probe-worker.ts', 'transport-worker.mjs'])
+ roots.push(join(root, 'src/evaluator', name));
+ await mkdir(join(root, '.cache'), { recursive: true });
+ const stage = await mkdtemp(join(root, '.cache', 'sdk-'));
+ const out = join(stage, 'output');
+ const config = join(stage, 'emit.json');
+ const rootConfig = join(root, 'tsconfig.json');
+ const compilerOptions = {
+ target: 'ES2022',
+ lib: ['ESNext', 'DOM'],
+ module: 'ESNext',
+ moduleResolution: 'Bundler',
+ strict: true,
+ skipLibCheck: true,
+ allowJs: true,
+ checkJs: false,
+ noEmit: false,
+ noEmitOnError: true,
+ declaration: true,
+ emitDeclarationOnly: false,
+ declarationMap: false,
+ sourceMap: false,
+ rewriteRelativeImportExtensions: true,
+ rootDir: root,
+ outDir: out,
+ };
+ let api;
+ try {
+ await writeFile(
+ config,
+ JSON.stringify({
+ ...(existsSync(rootConfig) ? { extends: rootConfig } : {}),
+ compilerOptions,
+ files: roots,
+ include: [posix(join(root, 'src/**/*.d.ts'))],
+ }),
+ );
+ execFileSync('node', [tsc, '--project', config], {
+ cwd: root,
+ encoding: 'utf8',
+ windowsHide: true,
+ });
+ const outputs = await filesIn(out);
+ const declaration = (path) => /\.d\.(?:ts|mts)$/.test(path);
+ const targetPath = (path, types) => {
+ const name = relative(out, path);
+ if (name.startsWith(`src${sep}`)) return join(lib, name.slice(4));
+ return types ? join(lib, '_types', name) : join(root, name);
+ };
+ const scripts = outputs.filter((path) => /\.(?:js|mjs|ts|mts)$/.test(path));
+ const parseConfig = join(stage, 'parse.json');
+ await writeFile(
+ parseConfig,
+ JSON.stringify({
+ compilerOptions: {
+ allowJs: true,
+ noEmit: true,
+ module: 'ESNext',
+ moduleResolution: 'Bundler',
+ },
+ files: scripts,
+ }),
+ );
+ api = new API({ cwd: root });
+ const snapshot = await api.updateSnapshot({ openProjects: [parseConfig] });
+ const project = snapshot.getProject(parseConfig);
+ const emitted = new Map();
+ for (const path of outputs) {
+ const types = declaration(path);
+ if (!relative(out, path).startsWith(`src${sep}`) && !types) continue;
+ let body = await readFile(path, 'utf8');
+ if (scripts.includes(path)) {
+ const sourceFile = await project.program.getSourceFile(path);
+ if (!sourceFile) throw new Error(`Cannot parse emitted SDK module: ${path}`);
+ const edits = [];
+ moduleLiterals(sourceFile, (literal) => {
+ if (
+ !literal ||
+ literal.kind !== SyntaxKind.StringLiteral ||
+ !literal.text.startsWith('.')
+ )
+ return;
+ const base = resolve(dirname(path), literal.text);
+ const resolved = [base, `${base}.js`, `${base}.mjs`, join(base, 'index.js')].find(
+ (candidate) => outputs.includes(candidate),
+ );
+ if (!resolved) throw new Error(`Unresolved emitted import ${literal.text} in ${path}`);
+ let specifier = posix(
+ relative(dirname(targetPath(path, types)), targetPath(resolved, types)),
+ );
+ if (!specifier.startsWith('.')) specifier = `./${specifier}`;
+ edits.push({
+ start: literal.getStart(sourceFile),
+ end: literal.end,
+ value: JSON.stringify(specifier),
+ });
+ });
+ for (const edit of edits.sort((a, b) => b.start - a.start))
+ body = body.slice(0, edit.start) + edit.value + body.slice(edit.end);
+ }
+ emitted.set(targetPath(path, types), body);
+ }
+ const libraryStage = join(stage, 'library');
+ const previousLibrary = join(stage, 'previous-library');
+ for (const [path, body] of emitted) {
+ if (!path.startsWith(`${lib}${sep}`)) throw new Error('SDK output escapes lib/.');
+ const stagedPath = join(libraryStage, relative(lib, path));
+ await mkdir(dirname(stagedPath), { recursive: true });
+ await writeFile(stagedPath, body);
+ }
+ // Both targets are fixed descendants of the resolved build root. Replace the
+ // generated directory only after compilation and import validation succeed.
+ const hadPrevious = existsSync(lib);
+ if (hadPrevious) await rename(lib, previousLibrary);
+ try {
+ await rename(libraryStage, lib);
+ } catch (error) {
+ if (hadPrevious) await rename(previousLibrary, lib);
+ throw error;
+ }
+ return { entries, files: [...emitted.keys()].map((path) => posix(relative(root, path))) };
+ } finally {
+ await api?.close();
+ await rm(stage, { recursive: true, force: true });
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ try {
+ const result = await buildSdk();
+ console.log(
+ `SDK: ${Object.keys(result.entries).length} entrypoints, ${result.files.length} files.`,
+ );
+ } catch (error) {
+ console.error(error.stdout || error.message);
+ process.exitCode = 1;
+ }
+}
diff --git a/scripts/build-sdk.test.mjs b/scripts/build-sdk.test.mjs
new file mode 100644
index 00000000..cc7df299
--- /dev/null
+++ b/scripts/build-sdk.test.mjs
@@ -0,0 +1,98 @@
+import { test, expect } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { buildSdk } from './build-sdk.mjs';
+
+test('SDK output supports Node imports, dynamic imports and consumer declarations', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-sdk-build-café-'));
+ try {
+ await mkdir(join(root, 'src/nested'), { recursive: true });
+ await mkdir(join(root, 'src/evaluator'), { recursive: true });
+ await mkdir(join(root, 'service'), { recursive: true });
+ await writeFile(
+ join(root, 'package.json'),
+ JSON.stringify({
+ type: 'module',
+ exports: { '.': './src/index.ts', './evaluator': './src/evaluator/index.ts' },
+ }),
+ );
+ await writeFile(join(root, 'service/id.mjs'), 'export const protocol = "fixture-v1";\n');
+ await writeFile(join(root, 'src/nested/index.ts'), 'export const value: number = 42;\n');
+ await writeFile(join(root, 'src/lazy.ts'), 'export const label = "loaded";\n');
+ await writeFile(join(root, 'src/evaluator/index.ts'), 'export const available = true;\n');
+ for (const name of ['worker', 'probe-worker'])
+ await writeFile(
+ join(root, `src/evaluator/${name}.ts`),
+ 'import { value } from "../nested"; console.log(value);\n',
+ );
+ await writeFile(
+ join(root, 'src/evaluator/transport-worker.mjs'),
+ 'console.log("transport");\n',
+ );
+ await writeFile(
+ join(root, 'src/index.ts'),
+ 'export { value } from "./nested";\n' +
+ 'import { protocol } from "../service/id.mjs";\n' +
+ 'export const identity: typeof protocol = protocol;\n' +
+ 'export async function lazy() { return (await import("./lazy.ts")).label; }\n',
+ );
+ const result = await buildSdk(root);
+ expect(result.entries).toEqual({
+ '.': { types: './lib/index.d.ts', import: './lib/index.js' },
+ './evaluator': { types: './lib/evaluator/index.d.ts', import: './lib/evaluator/index.js' },
+ });
+ // These entry files are opened by URL at runtime, not by TS import edges.
+ for (const [worker, value] of [
+ ['worker.js', '42'],
+ ['probe-worker.js', '42'],
+ ['transport-worker.mjs', 'transport'],
+ ])
+ expect(
+ execFileSync('node', [join(root, 'lib/evaluator', worker)], {
+ cwd: root,
+ encoding: 'utf8',
+ windowsHide: true,
+ }).trim(),
+ ).toBe(value);
+ const output = execFileSync(
+ 'node',
+ [
+ '--input-type=module',
+ '-e',
+ 'import {value, identity, lazy} from "./lib/index.js"; console.log(JSON.stringify([value, identity, await lazy()]));',
+ ],
+ { cwd: root, encoding: 'utf8', windowsHide: true },
+ );
+ expect(JSON.parse(output)).toEqual([42, 'fixture-v1', 'loaded']);
+ expect(await readFile(join(root, 'lib/index.d.ts'), 'utf8')).toContain('./nested/index.js');
+ await writeFile(
+ join(root, 'consumer.ts'),
+ 'import { value, identity, lazy } from "./lib/index.js";\n' +
+ 'const number: number = value; const id: "fixture-v1" = identity;\n' +
+ 'const result: Promise<string> = lazy(); void [number, id, result];\n',
+ );
+ execFileSync(
+ 'node',
+ [
+ fileURLToPath(new URL('../node_modules/typescript/bin/tsc', import.meta.url)),
+ '--noEmit',
+ '--strict',
+ '--module',
+ 'NodeNext',
+ '--target',
+ 'ES2022',
+ 'consumer.ts',
+ ],
+ { cwd: root, encoding: 'utf8', windowsHide: true },
+ );
+ await writeFile(join(root, 'lib/stale.js'), 'throw new Error("obsolete output");');
+ await buildSdk(root);
+ expect(existsSync(join(root, 'lib/stale.js'))).toBe(false);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/scripts/hosting/Dockerfile b/scripts/hosting/Dockerfile
new file mode 100644
index 00000000..b7ae4d83
--- /dev/null
+++ b/scripts/hosting/Dockerfile
@@ -0,0 +1,26 @@
+# Qualification image only. Supply a minimal context as described in README.md.
+# Pin the Node 22.23.3 multi-platform image index; build specifically for linux/amd64.
+# Bookworm Mesa 22.3 lacks shaderUniform*ArrayDynamicIndexing required by Dawn.
+FROM node:22.23.3-trixie-slim@sha256:154ba2f4d6fec323d28e4f4bb86bba4677f1223391a1979cf521304e03a98dfa
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bubblewrap util-linux mesa-vulkan-drivers libvulkan1 ca-certificates \
+ && chmod u-s,g-s /usr/bin/bwrap \
+ && rm -rf /var/lib/apt/lists/*
+RUN npm install --global [email protected] --no-audit --no-fund
+WORKDIR /app
+COPY candidate.tgz candidate.sha256 /probe/
+RUN cd /probe && sha256sum -c candidate.sha256
+RUN npm init -y && npm install /probe/candidate.tgz --omit=dev --include=optional \
+ --ignore-scripts --no-audit --no-fund
+COPY native-qualification.mjs run-native-qualification.mjs /probe/hosting/
+COPY smoke-renderer.mjs /probe/
+# Retain the OS dependency inventory next to the exact npm lock in the image.
+RUN dpkg-query -W > /probe/os-packages.txt \
+ && node --version > /probe/node-version.txt \
+ && set -- /usr/share/vulkan/icd.d/lvp_icd*.json \
+ && test "$#" -eq 1 && test -f "$1" \
+ && ln -s "$1" /probe/lvp-icd.json
+ENV VK_ICD_FILENAMES=/probe/lvp-icd.json
+ENV KILN_RENDER=cpu
+USER node
+CMD ["node", "/probe/hosting/run-native-qualification.mjs", "/app/node_modules/@instruktlabs/kiln", "/tmp/qualification", "/probe/candidate.tgz"]
diff --git a/scripts/hosting/README.md b/scripts/hosting/README.md
new file mode 100644
index 00000000..9a3ecf4e
--- /dev/null
+++ b/scripts/hosting/README.md
@@ -0,0 +1,71 @@
+# Native hosting qualification
+
+This is a fixed, one-shot probe for an installed Kiln archive. It accepts no user
+source, has no HTTP endpoint, deploys nothing and contains no cloud credentials.
+Its output is provider-neutral evidence; the caller must separately record the
+actual provider deployment and immutable image digest. A local run never proves
+Cloudflare compatibility.
+
+Build a minimal Docker context containing only these six files:
+
+- `Dockerfile`, `native-qualification.mjs`, `run-native-qualification.mjs` from this directory.
+- `smoke-renderer.mjs` from the parent scripts directory.
+- The reviewed npm archive renamed `candidate.tgz` and a `candidate.sha256` file
+ containing its reviewed SHA-256 followed by two spaces and `candidate.tgz`.
+
+Use `docker build --platform linux/amd64 --tag kiln-native-probe CONTEXT`.
+Do not send the engine checkout, credentials, authored workspaces or the entire
+local cache as the build context. The image checks the archive digest, uses the
+pinned Node base and npm toolchain, installs dependencies without lifecycle
+scripts, retains the resolved npm lock and OS package inventory, and runs as the
+non-root `node` user. The image's installed dependency graph and final digest still
+need review; the archive alone does not pin its transitive dependencies.
+
+Run without host mounts, provider keys or network access. For a local Docker
+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.
+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.
+
+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.
+Its separate namespace probe still fails on the GitHub Docker host; an explicit
+user namespace is required by the engine launch, and unsupported hosts stop before
+evaluating source. See the [execution record](../../docs/reviews/2026-10-06-v1-execution.md#linux-image-preflight)
+for exact run/image/archive identities and retained failures.
+
+The probe stops at the first failure. Successful readiness must contain all ten
+engine invariants. Only then does it evaluate a fixed box twice through the
+isolated evaluator, verify matching GLB bytes and a nonblank CPU preview, enforce
+deadline/cancellation/output limits, and render again after the limit tests. The
+existing renderer probe separately requires a software adapter and verifies a
+textured fixture with six retained PNGs. That fixture is trusted; it does not
+establish the source isolation boundary.
+
+Timing names mean first/repeated evaluator calls, not measured cold/warm provider
+starts. Deadlines and cancellation include worker startup, so these checks do not
+prove that native compute was running at interruption. Process resource usage is
+for the parent only. Available cgroup counters cover the container, and may include
+startup or earlier work; retain the before/after snapshots without relabeling them
+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.
+
+References checked 6 October 2026:
+[container lifecycle](https://developers.cloudflare.com/containers/concepts/architecture/),
+[sandbox security](https://developers.cloudflare.com/sandbox/concepts/security/),
+[local build prerequisites](https://developers.cloudflare.com/containers/get-started/).
diff --git a/scripts/hosting/native-qualification.mjs b/scripts/hosting/native-qualification.mjs
new file mode 100644
index 00000000..186c2e50
--- /dev/null
+++ b/scripts/hosting/native-qualification.mjs
@@ -0,0 +1,156 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { performance } from 'node:perf_hooks';
+
+const READINESS = [
+ 'user-namespace',
+ 'no-new-privileges',
+ 'capabilities-empty',
+ 'environment-exact',
+ 'product-filesystem-denied',
+ 'host-filesystem-denied',
+ 'runtime-filesystem-read-only',
+ 'network-namespace-empty',
+ 'metadata-and-local-network-denied',
+ 'generated-capabilities-denied',
+];
+const FAILURE_CODES = new Set([
+ 'UNSUPPORTED_HOST',
+ 'ISOLATION_UNAVAILABLE',
+ 'INPUT_INVALID',
+ 'EXECUTION_REJECTED',
+ 'DEADLINE_EXCEEDED',
+ 'CANCELLED',
+ 'OUTPUT_LIMIT_EXCEEDED',
+ 'wrapper-launch',
+ 'fd3-transport',
+ 'loader-probe-boot',
+ 'invariant-namespace',
+ 'invariant-environment',
+ 'invariant-filesystem',
+ 'invariant-network',
+ 'invariant-generated-policy',
+ 'deadline',
+]);
+const BOX = `function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}`;
+const NEVER = `async function build(){await new Promise(() => {});}`;
+const LIMITS = {
+ deadlineMs: 30000,
+ maxGlbBytes: 2 * 1024 * 1024,
+ maxResponseBytes: 4 * 1024 * 1024,
+};
+const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
+
+export async function captureCgroupSnapshot(readText) {
+ const snapshot = {};
+ for (const name of ['memory.current', 'memory.peak', 'memory.max', 'cpu.stat']) {
+ try {
+ const value = await readText(`/sys/fs/cgroup/${name}`, 'utf8');
+ // Kernel counter names include dots, e.g. core_sched.force_idle_usec.
+ if (value.length < 2048 && /^[a-z0-9_.\s]+$/.test(value)) snapshot[name] = value.trim();
+ } catch {
+ /* Not all providers expose a readable cgroup v2 mount. */
+ }
+ }
+ return snapshot;
+}
+
+/** Fixed qualification fixtures only. No caller-supplied source and no fallback evaluator. */
+export async function qualifyNativeRuntime(ports) {
+ const receipt = {
+ version: 'kiln.host-native-qualification.v1',
+ status: 'running',
+ checks: [],
+ artifacts: [],
+ };
+ let phase = 'host';
+ async function check(name, run) {
+ phase = name;
+ const start = performance.now();
+ const result = await run();
+ receipt.checks.push({ name, elapsedMs: performance.now() - start });
+ return result;
+ }
+ async function artifact(name, bytes) {
+ await ports.artifact(name, bytes);
+ receipt.artifacts.push({ name, bytes: bytes.length, sha256: sha(bytes) });
+ }
+ async function render() {
+ const result = await ports.render(BOX, { ...LIMITS });
+ assert(
+ Buffer.isBuffer(result.glb) &&
+ result.glb.length >= 8 &&
+ result.glb.length <= LIMITS.maxGlbBytes,
+ );
+ assert.equal(result.glb.subarray(0, 4).toString('ascii'), 'glTF');
+ return result.glb;
+ }
+ async function rejects(code, invoke) {
+ try {
+ await invoke();
+ } catch (error) {
+ if (error?.code !== code) throw error;
+ return;
+ }
+ assert.fail('Expected bounded failure was not observed');
+ }
+ try {
+ await check('host', async () => {
+ if (ports.platform !== 'linux' || !Number.isInteger(ports.uid) || ports.uid <= 0) {
+ throw Object.assign(new Error('Unsupported qualification host'), {
+ code: 'UNSUPPORTED_HOST',
+ });
+ }
+ });
+ receipt.isolation = await check('isolation', async () => {
+ const result = await ports.ready();
+ assert.equal(result.version, 'kiln.evaluator.isolation-readiness.v1');
+ assert.equal(result.mode, 'isolated');
+ assert.deepEqual([...result.checks].sort(), [...READINESS].sort());
+ return { version: result.version, mode: result.mode, checks: [...result.checks] };
+ });
+ const glb = await check('first-evaluation', render);
+ await artifact('fixture.glb', glb);
+ await check('repeat-evaluation', async () => assert.equal(sha(await render()), sha(glb)));
+ await check('cpu-preview', async () => {
+ const image = await ports.cpu(glb);
+ assert(image.png instanceof Uint8Array && image.png.length <= 1024 * 1024);
+ const decoded = ports.inspectPng(image.png);
+ assert.equal(decoded.width, 128);
+ assert.equal(decoded.height, 128);
+ assert(decoded.distinctPixels > 1, 'CPU fixture is blank');
+ await artifact('cpu-preview.png', image.png);
+ });
+ await check('deadline', () =>
+ rejects('DEADLINE_EXCEEDED', () => ports.render(NEVER, { ...LIMITS, deadlineMs: 100 })),
+ );
+ await check('cancellation', async () => {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 50);
+ try {
+ await rejects('CANCELLED', () =>
+ ports.render(NEVER, { ...LIMITS, signal: controller.signal }),
+ );
+ } finally {
+ clearTimeout(timer);
+ }
+ });
+ await check('output-limit', () =>
+ 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 };
+ });
+ receipt.status = 'passed';
+ } catch (error) {
+ const code = ports.readinessCode(error) ?? error?.code;
+ receipt.status = 'failed';
+ receipt.failure = { phase, code: FAILURE_CODES.has(code) ? code : 'CHECK_FAILED' };
+ }
+ return receipt;
+}
diff --git a/scripts/hosting/native-qualification.test.mjs b/scripts/hosting/native-qualification.test.mjs
new file mode 100644
index 00000000..28845ff2
--- /dev/null
+++ b/scripts/hosting/native-qualification.test.mjs
@@ -0,0 +1,186 @@
+import { expect, test } from 'bun:test';
+import { captureCgroupSnapshot, qualifyNativeRuntime } from './native-qualification.mjs';
+
+test('cgroup evidence retains dotted kernel counters from the Linux preflight', async () => {
+ const cpu =
+ 'usage_usec 58167\nuser_usec 41686\nsystem_usec 16480\ncore_sched.force_idle_usec 0\n';
+ const snapshot = await captureCgroupSnapshot(async (path) =>
+ path.endsWith('cpu.stat') ? cpu : '6442450944\n',
+ );
+ expect(snapshot['cpu.stat']).toBe(cpu.trim());
+ expect(snapshot['memory.max']).toBe('6442450944');
+});
+
+test('cgroup evidence bounds malformed values and tolerates unavailable counters', async () => {
+ const snapshot = await captureCgroupSnapshot(async (path) => {
+ if (path.endsWith('memory.current')) return '9'.repeat(2048);
+ if (path.endsWith('memory.peak')) throw new Error('not exposed');
+ if (path.endsWith('cpu.stat')) return 'usage_usec 1\u0000';
+ return 'max\n';
+ });
+ expect(snapshot).toEqual({ 'memory.max': 'max' });
+});
+
+const checks = [
+ 'user-namespace',
+ 'no-new-privileges',
+ 'capabilities-empty',
+ 'environment-exact',
+ 'product-filesystem-denied',
+ 'host-filesystem-denied',
+ 'runtime-filesystem-read-only',
+ 'network-namespace-empty',
+ 'metadata-and-local-network-denied',
+ 'generated-capabilities-denied',
+];
+const glb = Buffer.from('glTFfixture');
+function fixture() {
+ const calls = [];
+ const ports = {
+ platform: 'linux',
+ uid: 1000,
+ ready: async () => ({
+ version: 'kiln.evaluator.isolation-readiness.v1',
+ mode: 'isolated',
+ checks,
+ }),
+ readinessCode: (error) => error.readinessCode,
+ render: async (_code, controls) => {
+ calls.push(controls);
+ if (controls.signal) {
+ return await new Promise((_, reject) =>
+ controls.signal.addEventListener('abort', () => reject({ code: 'CANCELLED' }), {
+ once: true,
+ }),
+ );
+ }
+ if (controls.deadlineMs === 100) throw { code: 'DEADLINE_EXCEEDED' };
+ if (controls.maxGlbBytes === 32) throw { code: 'OUTPUT_LIMIT_EXCEEDED' };
+ return { glb };
+ },
+ cpu: async () => ({ png: Buffer.from('pngfixture'), width: 128, height: 128 }),
+ inspectPng: () => ({ width: 128, height: 128, distinctPixels: 12 }),
+ artifact: async () => {},
+ software: async () => ({ status: 'passed', software: true, rendererId: 'test-software' }),
+ };
+ return { ports, calls };
+}
+
+test('non-Linux and root hosts cannot attempt evaluation', async () => {
+ for (const override of [{ platform: 'win32' }, { uid: 0 }]) {
+ const { ports, calls } = fixture();
+ const result = await qualifyNativeRuntime({ ...ports, ...override });
+ expect(result).toMatchObject({
+ status: 'failed',
+ failure: { phase: 'host', code: 'UNSUPPORTED_HOST' },
+ });
+ expect(calls).toHaveLength(0);
+ }
+});
+
+test('failed readiness stops before source execution without exposing diagnostics', async () => {
+ const { ports, calls } = fixture();
+ ports.ready = async () => {
+ throw { readinessCode: 'fd3-transport', message: 'private-token-value' };
+ };
+ const result = await qualifyNativeRuntime(ports);
+ expect(result).toMatchObject({
+ status: 'failed',
+ failure: { phase: 'isolation', code: 'fd3-transport' },
+ });
+ expect(JSON.stringify(result)).not.toContain('private-token-value');
+ expect(calls).toHaveLength(0);
+});
+
+test('partial and duplicated readiness assertions do not qualify the boundary', async () => {
+ for (const invalid of [checks.slice(1), [...checks.slice(1), checks[1]]]) {
+ const { ports, calls } = fixture();
+ ports.ready = async () => ({
+ version: 'kiln.evaluator.isolation-readiness.v1',
+ mode: 'isolated',
+ checks: invalid,
+ });
+ expect(await qualifyNativeRuntime(ports)).toMatchObject({
+ status: 'failed',
+ failure: { phase: 'isolation', code: 'CHECK_FAILED' },
+ });
+ expect(calls).toHaveLength(0);
+ }
+});
+
+test('successful qualification retains bounded artifacts and separate safety checks', async () => {
+ const { ports, calls } = fixture();
+ const result = await qualifyNativeRuntime(ports);
+ 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',
+ 'software-vulkan',
+ ]);
+ expect(result.artifacts.map((item) => item.name)).toEqual(['fixture.glb', 'cpu-preview.png']);
+ expect(result.artifacts[0].sha256).toMatch(/^[a-f0-9]{64}$/);
+ expect(
+ result.checks.every((item) => Number.isFinite(item.elapsedMs) && item.elapsedMs >= 0),
+ ).toBe(true);
+ expect(calls.every((item) => item.deadlineMs <= 30000 && item.maxResponseBytes <= 4194304)).toBe(
+ true,
+ );
+});
+
+test('a deadline check that resolves instead of rejecting is a failure', async () => {
+ const { ports } = fixture();
+ ports.render = async () => ({ glb });
+ expect(await qualifyNativeRuntime(ports)).toMatchObject({
+ status: 'failed',
+ failure: { phase: 'deadline', code: 'CHECK_FAILED' },
+ });
+});
+
+test('wrong negative outcome is not accepted as a successful limit', async () => {
+ const { ports } = fixture();
+ const original = ports.render;
+ ports.render = async (source, controls) => {
+ if (controls.deadlineMs === 100) throw { code: 'EXECUTION_REJECTED' };
+ return original(source, controls);
+ };
+ expect(await qualifyNativeRuntime(ports)).toMatchObject({
+ status: 'failed',
+ failure: { phase: 'deadline', code: 'EXECUTION_REJECTED' },
+ });
+});
+
+test('hardware or missing renderer proof cannot qualify software rendering', async () => {
+ for (const response of [
+ { status: 'passed', software: false },
+ { status: 'failed', software: true },
+ ]) {
+ const { ports } = fixture();
+ ports.software = async () => response;
+ expect(await qualifyNativeRuntime(ports)).toMatchObject({
+ status: 'failed',
+ failure: { phase: 'software-vulkan', code: 'CHECK_FAILED' },
+ });
+ }
+});
+
+test('malformed GLBs and blank CPU previews fail before safety/renderer qualification', async () => {
+ const { ports } = fixture();
+ ports.render = async () => ({ glb: Buffer.from('wrong') });
+ expect(await qualifyNativeRuntime(ports)).toMatchObject({
+ status: 'failed',
+ failure: { phase: 'first-evaluation', code: 'CHECK_FAILED' },
+ });
+ const other = fixture().ports;
+ other.inspectPng = () => ({ width: 128, height: 128, distinctPixels: 1 });
+ expect(await qualifyNativeRuntime(other)).toMatchObject({
+ status: 'failed',
+ failure: { phase: 'cpu-preview', code: 'CHECK_FAILED' },
+ });
+});
diff --git a/scripts/hosting/run-native-qualification.mjs b/scripts/hosting/run-native-qualification.mjs
new file mode 100644
index 00000000..5b107370
--- /dev/null
+++ b/scripts/hosting/run-native-qualification.mjs
@@ -0,0 +1,125 @@
+#!/usr/bin/env node
+// One-shot fixed probe, never an HTTP evaluation service. Run inside the target image.
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+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';
+
+const [installationArg, outputArg, archiveArg] = process.argv.slice(2);
+assert(
+ installationArg && outputArg && archiveArg && process.argv.length === 5,
+ 'Usage: run-native-qualification.mjs INSTALLED_PACKAGE NEW_OUTPUT_DIRECTORY EXACT_ARCHIVE',
+);
+const installation = await realpath(resolve(installationArg));
+const output = resolve(outputArg);
+const parent = await realpath(resolve(output, '..'));
+assert(
+ parent !== installation && !parent.startsWith(installation + sep),
+ 'Output must be outside the installed engine',
+);
+// Do not replace receipts, arbitrary files, or a redirected output directory.
+await mkdir(output);
+const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const record = {
+ platform: process.platform,
+ arch: process.arch,
+ node: process.version,
+ uid: process.getuid?.() ?? null,
+ provider: 'unverified',
+ processMeasurements: { scope: 'probe parent process only; excludes evaluator/renderer children' },
+};
+const cgroupSnapshot = () => captureCgroupSnapshot(readFile);
+try {
+ const pkg = JSON.parse(await readFile(join(installation, 'package.json'), 'utf8'));
+ assert.equal(pkg.name, '@instruktlabs/kiln');
+ const archive = await readFile(resolve(archiveArg));
+ record.candidate = { name: pkg.name, version: pkg.version, archiveSha256: sha(archive) };
+ record.files = {};
+ for (const file of [
+ 'lib/evaluator/isolation.js',
+ 'lib/evaluator/worker.js',
+ 'lib/evaluator/probe-worker.js',
+ 'dist/cli.mjs',
+ ]) {
+ record.files[file] = sha(await readFile(join(installation, file)));
+ }
+ record.dependencyLockSha256 = sha(
+ await readFile(join(installation, '../../..', 'package-lock.json')),
+ );
+ const module = (path) => import(pathToFileURL(join(installation, path)).href);
+ const evaluator = await module('lib/evaluator/index.js');
+ const host = { bwrapPath: '/usr/bin/bwrap' };
+ const require = createRequire(pathToFileURL(join(installation, 'package.json')));
+ const { PNG } = require('pngjs');
+ record.cgroupBefore = await cgroupSnapshot();
+ const result = await qualifyNativeRuntime({
+ platform: process.platform,
+ uid: record.uid,
+ ready: () => evaluator.assertIsolatedEvaluatorReady(host),
+ readinessCode: evaluator.isolationReadinessFailureCode,
+ render: (source, controls) =>
+ evaluator.renderGLBViaIsolatedEvaluator(source, {}, { ...controls, host }),
+ cpu: async (glb) => {
+ const views = await module('lib/views/index.js');
+ return views.renderGlbViewCell(
+ glb,
+ { name: 'qualification', dir: [1, 0.4, 1] },
+ { size: 128 },
+ );
+ },
+ inspectPng: (bytes) => {
+ const image = PNG.sync.read(Buffer.from(bytes));
+ const pixels = new Set();
+ for (let index = 0; index < image.data.length; index += 4)
+ pixels.add(image.data.readUInt32BE(index));
+ return { width: image.width, height: image.height, distinctPixels: pixels.size };
+ },
+ artifact: (name, bytes) => writeFile(join(output, name), bytes, { flag: 'wx' }),
+ software: async () => {
+ const rendererOutput = join(output, 'software-vulkan');
+ // This separate existing smoke renders a fixed trusted material fixture. It
+ // does not accept source and is not evidence of source-evaluator isolation.
+ const env = evaluator.sanitizedEvaluatorEnv();
+ env.KILN_RENDER = 'cpu';
+ if (process.env.VK_ICD_FILENAMES) env.VK_ICD_FILENAMES = process.env.VK_ICD_FILENAMES;
+ const child = spawnSync(
+ process.execPath,
+ [
+ fileURLToPath(new URL('../smoke-renderer.mjs', import.meta.url)),
+ installation,
+ rendererOutput,
+ 'software',
+ ],
+ {
+ env,
+ encoding: 'utf8',
+ timeout: 120000,
+ maxBuffer: 1024 * 1024,
+ windowsHide: true,
+ },
+ );
+ assert.equal(child.status, 0, 'Software-renderer qualification process failed');
+ return JSON.parse(await readFile(join(rendererOutput, 'receipt.json'), 'utf8'));
+ },
+ });
+ Object.assign(record, result);
+} catch {
+ Object.assign(record, {
+ version: 'kiln.host-native-qualification.v1',
+ status: 'failed',
+ checks: [],
+ artifacts: [],
+ failure: { phase: 'setup', code: 'SETUP_FAILED' },
+ });
+}
+record.processMeasurements.usage = process.resourceUsage();
+record.cgroupAfter = await cgroupSnapshot();
+await writeFile(join(output, 'receipt.json'), `${JSON.stringify(record, null, 2)}\n`, {
+ flag: 'wx',
+});
+console.log(JSON.stringify(record));
+process.exitCode = record.status === 'passed' ? 0 : 1;
diff --git a/scripts/package-local-plugin.mjs b/scripts/package-local-plugin.mjs
new file mode 100644
index 00000000..425306ac
--- /dev/null
+++ b/scripts/package-local-plugin.mjs
@@ -0,0 +1,155 @@
+#!/usr/bin/env node
+import { createHash } from 'node:crypto';
+import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const json = (value) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
+
+async function inventory(directory, prefix = '') {
+ const files = new Map();
+ for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) =>
+ a.name.localeCompare(b.name, 'en'),
+ )) {
+ if (entry.isSymbolicLink())
+ throw new Error(`Plugin components must be real files: ${prefix}${entry.name}`);
+ if (entry.isDirectory()) {
+ for (const [name, bytes] of await inventory(
+ join(directory, entry.name),
+ `${prefix}${entry.name}/`,
+ ))
+ files.set(name, bytes);
+ } else if (entry.isFile())
+ files.set(`${prefix}${entry.name}`, await readFile(join(directory, entry.name)));
+ else throw new Error(`Unsupported plugin component: ${prefix}${entry.name}`);
+ }
+ return files;
+}
+
+async function expectedFiles() {
+ const pkg = JSON.parse(await readFile(join(repo, 'package.json'), 'utf8'));
+ if (
+ pkg.name !== '@instruktlabs/kiln' ||
+ !/^\d+\.\d+\.\d+(?:-(?:rc|dev)\.\d+)?$/.test(pkg.version)
+ )
+ throw new Error('The local plugin requires the exact Kiln release identity.');
+ const identity = {
+ name: 'kiln-engine',
+ version: pkg.version,
+ description:
+ 'Set up a local Kiln workspace to create, inspect and revise editable 3D assets with Claude Code or Codex.',
+ author: { name: 'Instrukt Labs' },
+ homepage: 'https://github.com/instruktlabs/kiln',
+ repository: 'https://github.com/instruktlabs/kiln',
+ license: 'MIT',
+ keywords: ['3d', 'glb', 'gltf', 'asset-generation', 'gamedev'],
+ };
+ const portable = {
+ $schema: 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json',
+ ...identity,
+ extensions: {
+ 'com.openai': {
+ interface: {
+ displayName: 'Kiln Engine',
+ shortDescription: 'Create editable 3D assets in a local workspace',
+ longDescription:
+ 'Install the pinned Kiln engine and set up a workspace with local MCP tools and maintained authoring skills. Your coding agent supplies the model.',
+ developerName: 'Instrukt Labs',
+ category: 'Developer Tools',
+ capabilities: ['Read', 'Write'],
+ defaultPrompt: [
+ 'Set up a Kiln workspace for this coding agent.',
+ 'Check and upgrade my existing Kiln workspace.',
+ ],
+ },
+ },
+ },
+ };
+ const files = new Map([
+ ['plugin.json', json(portable)],
+ ['.claude-plugin/plugin.json', json(identity)],
+ ['runtime.json', json({ name: pkg.name, version: pkg.version })],
+ ['LICENSE', await readFile(join(repo, 'LICENSE'))],
+ [
+ 'scripts/setup-workspace.mjs',
+ await readFile(join(repo, 'scripts/setup-plugin-workspace.mjs')),
+ ],
+ ]);
+ for (const [name, bytes] of await inventory(
+ join(repo, 'skills/kiln-setup-workspace'),
+ 'skills/kiln-setup-workspace/',
+ ))
+ files.set(name, bytes);
+ const development = pkg.version.includes('-dev.')
+ ? '**Development candidate.** This version is not published to npm. Qualification requires the reviewed local engine archive via `--archive`.\n\n'
+ : pkg.version.includes('-rc.')
+ ? '**Release candidate.** Use the reviewed archive via `--archive` for local qualification. Registry installation requires this exact version to be available on npm.\n\n'
+ : '';
+ files.set(
+ 'README.md',
+ Buffer.from(
+ `# Kiln Engine local plugin\n\n${development}Version ${pkg.version}, published by Instrukt Labs under the MIT license.\n\nAsk your coding agent to set up a Kiln workspace. The setup skill installs\n\`${pkg.name}@${pkg.version}\` with npm and creates a separate asset workspace.\nUse a supported Node.js installation with npm; no Bun, engine clone or separate\nmodel API key is required. The workspace's START.md explains how to reopen it.\n\nThe plugin registers setup only. The workspace supplies the authoring skills\nand one local MCP server, \`kiln_workspace\`. Open Claude Code in that workspace;\nlaunch Codex there with \`node codex.mjs\`. Accept the host's ordinary trust prompts\nand verify live tool discovery before authoring.\n\nThe engine installation and your assets stay outside the disposable plugin cache.\nPlugin removal or updating its cached files does not delete them. An existing\nworkspace remains on its installed engine until an explicit managed upgrade.\nRead [setup and upgrade guidance](skills/kiln-setup-workspace/references/plugin-install.md).\n\nCPU rendering is available locally. Material appearance requires a qualified\nrenderer; follow the setup skill's renderer checks rather than assuming GPU support.\nHosted ChatGPT access is a separate integration, and this local bundle is not a\npublic OpenAI directory submission.\n\n[Source and issues](https://github.com/instruktlabs/kiln)\n`,
+ ),
+ );
+ const hashes = Object.fromEntries(
+ [...files]
+ .sort(([a], [b]) => a.localeCompare(b, 'en'))
+ .map(([name, bytes]) => [name, `sha256:${createHash('sha256').update(bytes).digest('hex')}`]),
+ );
+ files.set(
+ 'package-provenance.json',
+ json({
+ schemaVersion: 1,
+ kind: 'kiln-local-plugin',
+ engineVersion: pkg.version,
+ files: hashes,
+ }),
+ );
+ return { files, version: pkg.version };
+}
+
+export async function packageLocalPlugin(destination, options = {}) {
+ const directory = resolve(destination);
+ const { files, version } = await expectedFiles();
+ if (options.check) {
+ const actual = await inventory(directory);
+ const names = [...new Set([...files.keys(), ...actual.keys()])].sort();
+ const changed = names.filter(
+ (name) => !files.get(name)?.equals(actual.get(name) || Buffer.alloc(0)),
+ );
+ if (changed.length)
+ throw new Error(
+ `Local plugin is stale: ${changed.join(', ')}. Generate a fresh bundle and review its changes.`,
+ );
+ return { directory, version, files: files.size - 1, current: true };
+ }
+ // Refuse both populated and empty existing destinations, including symlinks.
+ try {
+ await lstat(directory);
+ throw new Error('Plugin output already exists. Generate into a fresh directory.');
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ }
+ await mkdir(dirname(directory), { recursive: true });
+ await mkdir(directory);
+ for (const [name, bytes] of files) {
+ await mkdir(dirname(join(directory, name)), { recursive: true });
+ await writeFile(join(directory, name), bytes, { flag: 'wx' });
+ }
+ return { directory, version, files: files.size - 1 };
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const args = process.argv.slice(2);
+ const destination = args.shift();
+ if (!destination || args.some((arg) => arg !== '--check'))
+ throw new Error('Usage: node scripts/package-local-plugin.mjs OUTPUT_DIRECTORY [--check]');
+ console.log(
+ JSON.stringify(
+ await packageLocalPlugin(destination, { check: args.includes('--check') }),
+ null,
+ 2,
+ ),
+ );
+}
diff --git a/scripts/package-local-plugin.test.mjs b/scripts/package-local-plugin.test.mjs
new file mode 100644
index 00000000..0c690680
--- /dev/null
+++ b/scripts/package-local-plugin.test.mjs
@@ -0,0 +1,141 @@
+import { afterEach, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve, sep } from 'node:path';
+import { packageLocalPlugin } from './package-local-plugin.mjs';
+
+const roots = [];
+afterEach(async () => {
+ for (const root of roots.splice(0)) {
+ if (!root.startsWith((await realpath(tmpdir())) + sep))
+ throw new Error('Unsafe fixture cleanup');
+ await rm(root, { recursive: true, force: true });
+ }
+});
+async function destination() {
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'kiln-plugin-package-')));
+ roots.push(root);
+ return join(root, 'kiln-engine');
+}
+const readJson = async (file) => JSON.parse(await readFile(file, 'utf8'));
+
+test('local plugin has portable and Claude identities pinned to the engine', async () => {
+ const directory = await destination();
+ await packageLocalPlugin(directory);
+ const pkg = await readJson(resolve('package.json'));
+ const portable = await readJson(join(directory, 'plugin.json'));
+ const claude = await readJson(join(directory, '.claude-plugin/plugin.json'));
+ expect(portable.$schema).toBe('https://agent-plugins.org/schemas/1.0.0/plugin.schema.json');
+ expect(portable).toMatchObject({
+ name: 'kiln-engine',
+ version: pkg.version,
+ author: { name: 'Instrukt Labs' },
+ });
+ expect(claude.name).toBe(portable.name);
+ expect(claude.version).toBe(portable.version);
+ expect(await readJson(join(directory, 'runtime.json'))).toEqual({
+ name: pkg.name,
+ version: pkg.version,
+ });
+ expect(portable.extensions['com.openai'].interface.displayName).toBe('Kiln Engine');
+ expect(portable.mcpServers).toBeUndefined();
+ expect(claude.mcpServers).toBeUndefined();
+});
+
+test('bundle registers setup alone and keeps its complete maintained reference and helper', async () => {
+ const directory = await destination();
+ await packageLocalPlugin(directory);
+ expect(await readdir(join(directory, 'skills'))).toEqual(['kiln-setup-workspace']);
+ for (const file of ['SKILL.md', 'references/plugin-install.md']) {
+ expect(await readFile(join(directory, 'skills/kiln-setup-workspace', file), 'utf8')).toBe(
+ await readFile(resolve('skills/kiln-setup-workspace', file), 'utf8'),
+ );
+ }
+ expect(await readFile(join(directory, 'scripts/setup-workspace.mjs'), 'utf8')).toBe(
+ await readFile(resolve('scripts/setup-plugin-workspace.mjs'), 'utf8'),
+ );
+ const entries = await readdir(directory);
+ for (const excluded of [
+ 'src',
+ 'dist',
+ 'node_modules',
+ 'examples',
+ '.mcp.json',
+ 'mcp.json',
+ '.app.json',
+ 'CLAUDE.md',
+ 'AGENTS.md',
+ 'package.json',
+ 'hooks',
+ ])
+ expect(entries).not.toContain(excluded);
+});
+
+test('bundle retains an exact inventory and deterministic hashes', async () => {
+ const first = await destination();
+ const second = await destination();
+ const result = await packageLocalPlugin(first);
+ await packageLocalPlugin(second);
+ const receipt = await readJson(join(first, 'package-provenance.json'));
+ expect(receipt.kind).toBe('kiln-local-plugin');
+ expect(receipt.engineVersion).toBe((await readJson(resolve('package.json'))).version);
+ expect(Object.keys(receipt.files).length).toBe(result.files);
+ for (const [file, digest] of Object.entries(receipt.files)) {
+ expect(digest).toBe(
+ `sha256:${createHash('sha256')
+ .update(await readFile(join(first, file)))
+ .digest('hex')}`,
+ );
+ expect(await readFile(join(first, file), 'utf8')).toBe(
+ await readFile(join(second, file), 'utf8'),
+ );
+ }
+});
+
+test('creation refuses even an empty existing output directory', async () => {
+ const directory = await destination();
+ await mkdir(directory);
+ await expect(packageLocalPlugin(directory)).rejects.toThrow('exist');
+ expect(await readdir(directory)).toEqual([]);
+});
+
+test('check reports source drift and unexpected files without modifying output', async () => {
+ const directory = await destination();
+ await packageLocalPlugin(directory);
+ expect(await packageLocalPlugin(directory, { check: true })).toMatchObject({ current: true });
+ const target = join(directory, 'runtime.json');
+ await writeFile(target, 'edited');
+ await expect(packageLocalPlugin(directory, { check: true })).rejects.toThrow('runtime.json');
+ expect(await readFile(target, 'utf8')).toBe('edited');
+});
+
+test('check rejects extra components even when the known files still match', async () => {
+ const directory = await destination();
+ await packageLocalPlugin(directory);
+ await writeFile(join(directory, '.mcp.json'), '{}');
+ await expect(packageLocalPlugin(directory, { check: true })).rejects.toThrow('.mcp.json');
+});
+
+test('check never creates a missing output', async () => {
+ const directory = await destination();
+ await expect(packageLocalPlugin(directory, { check: true })).rejects.toThrow();
+ await expect(readdir(directory)).rejects.toThrow();
+});
+
+test('checked-in marketplace bundle matches maintained sources and both catalogs select it', async () => {
+ await expect(
+ packageLocalPlugin(resolve('plugins/kiln-engine'), { check: true }),
+ ).resolves.toMatchObject({ current: true });
+ const claude = await readJson(resolve('.claude-plugin/marketplace.json'));
+ const codex = await readJson(resolve('.agents/plugins/marketplace.json'));
+ expect(claude.name).toBe('instruktlabs');
+ expect(codex.name).toBe('instruktlabs');
+ expect(claude.plugins).toHaveLength(1);
+ expect(codex.plugins).toHaveLength(1);
+ expect(claude.plugins[0]).toMatchObject({ name: 'kiln-engine', source: './plugins/kiln-engine' });
+ expect(codex.plugins[0]).toMatchObject({
+ name: 'kiln-engine',
+ source: { source: 'local', path: './plugins/kiln-engine' },
+ });
+});
diff --git a/scripts/prepare-npm-release.mjs b/scripts/prepare-npm-release.mjs
new file mode 100644
index 00000000..84d8018b
--- /dev/null
+++ b/scripts/prepare-npm-release.mjs
@@ -0,0 +1,327 @@
+#!/usr/bin/env node
+// Release preparation is read-only against GitHub/npm. Only release.yml stages bytes.
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { appendFile, mkdir, mkdtemp, readFile, readdir, writeFile } from 'node:fs/promises';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { receiptProblems } from './verify-package-receipt.mjs';
+
+export const RELEASE_REPOSITORY = 'instruktlabs/kiln';
+export const RELEASE_REPOSITORY_ID = 1278326592;
+export const RELEASE_JOBS = [
+ 'typecheck · lint · test',
+ 'typecheck · lint · test (Windows)',
+ 'render service tests',
+ 'build portable Node package',
+ 'Node package · macOS arm64',
+ 'Node package · macOS x64',
+ 'Node package · Windows',
+ 'Node package · Linux 20.15.0',
+ 'Node package · Linux 22.2.0',
+ 'Node package · Linux 24.20.0',
+ 'Node package · Linux',
+ 'Installed renderer · Linux software Vulkan',
+];
+export const RELEASE_RECEIPTS = [
+ {
+ artifact: 'node-package-candidate',
+ file: 'candidate-sdk-receipt.json',
+ platform: 'linux',
+ arch: 'x64',
+ types: true,
+ },
+ { artifact: 'windows-package', platform: 'win32', arch: 'x64' },
+ { artifact: 'macos-package-arm64', platform: 'darwin', arch: 'arm64' },
+ { artifact: 'macos-package-x64', platform: 'darwin', arch: 'x64' },
+ {
+ artifact: 'linux-package-20.15.0',
+ platform: 'linux',
+ arch: 'x64',
+ node: '20.15.0',
+ npm: '10.7.0',
+ },
+ {
+ artifact: 'linux-package-22.2.0',
+ platform: 'linux',
+ arch: 'x64',
+ node: '22.2.0',
+ npm: '10.7.0',
+ },
+ {
+ artifact: 'linux-package-24.20.0',
+ platform: 'linux',
+ arch: 'x64',
+ node: '24.20.0',
+ npm: '11.19.0',
+ },
+];
+export const RELEASE_ARTIFACTS = [
+ ...RELEASE_RECEIPTS.map((item) => item.artifact),
+ 'linux-software-vulkan',
+];
+
+export function releaseMetadataProblems(metadata, target) {
+ const problems = [];
+ const require = (condition, message) => {
+ if (!condition) problems.push(message);
+ };
+ require(/^[1-9]\d*$/.test(target.runId), 'Invalid CI run ID');
+ require(/^[a-f0-9]{40}$/.test(target.commit), 'Invalid commit SHA');
+ require(/^[a-f0-9]{64}$/.test(target.digest), 'Invalid archive SHA-256');
+ require(['verify', 'stage'].includes(target.mode), 'Mode must be verify or stage');
+ const { run = {}, jobs = [], artifacts = [], environment } = metadata;
+ require(String(run.id) === target.runId, 'CI run ID mismatch');
+ require(run.path === '.github/workflows/ci.yml', 'Source must be the CI workflow');
+ require(run.event === 'push' && run.head_branch === 'main', 'Source must be a main push');
+ require(run.head_sha === target.commit, 'CI commit differs from the release checkout');
+ require(run.status === 'completed' &&
+ run.conclusion === 'success', 'CI must finish successfully');
+ for (const field of ['repository', 'head_repository'])
+ require(run[field]?.id === RELEASE_REPOSITORY_ID &&
+ run[field]?.full_name === RELEASE_REPOSITORY, 'CI repository identity mismatch');
+ for (const name of RELEASE_JOBS) {
+ const matching = jobs.filter((job) => job.name === name);
+ require(matching.length === 1, `Missing or duplicate CI job: ${name}`);
+ }
+ require(jobs.every(
+ (job) => job.status === 'completed' && job.conclusion === 'success',
+ ), 'Every CI job must pass; skipped jobs are not qualification');
+ for (const name of RELEASE_ARTIFACTS) {
+ const matching = artifacts.filter((artifact) => artifact.name === name);
+ require(matching.length === 1, `Missing or duplicate artifact: ${name}`);
+ const artifact = matching[0];
+ require(artifact?.expired === false, `Artifact is expired: ${name}`);
+ const source = artifact?.workflow_run;
+ require(String(source?.id) === target.runId &&
+ source?.head_sha === target.commit &&
+ source?.repository_id === RELEASE_REPOSITORY_ID &&
+ source?.head_repository_id === RELEASE_REPOSITORY_ID, `Artifact source mismatch: ${name}`);
+ }
+ if (target.mode === 'stage') {
+ require(environment?.name === 'npm-release', 'Configure npm-release before staging');
+ require(environment?.can_admins_bypass ===
+ false, 'Release approval must not allow admin bypass');
+ require(environment?.deployment_branch_policy?.protected_branches === true &&
+ environment?.deployment_branch_policy?.custom_branch_policies ===
+ false, 'Release environment must restrict deployment to protected branches');
+ const reviewers = environment?.protection_rules?.find(
+ (rule) => rule.type === 'required_reviewers',
+ )?.reviewers;
+ require(reviewers?.length === 1 &&
+ reviewers[0]?.type === 'User' &&
+ reviewers[0]?.reviewer?.login ===
+ 'matthew-kissinger', 'Release environment requires the owner reviewer');
+ }
+ return problems;
+}
+
+const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const json = async (path) => JSON.parse(await readFile(path, 'utf8'));
+
+export async function verifyReleaseArtifacts(directory, { manifest, toolchain, digest }) {
+ assert.equal(manifest.name, '@instruktlabs/kiln', 'Wrong release package');
+ assert.match(
+ manifest.version,
+ /^1\.0\.0(?:-rc\.(?:0|[1-9]\d*))?$/,
+ 'Expected a v1 release version',
+ );
+ assert.notEqual(manifest.private, true, 'Private packages cannot be staged');
+ assert.deepEqual(manifest.publishConfig, { access: 'public', provenance: true });
+ assert.equal(manifest.repository?.url, 'git+https://github.com/instruktlabs/kiln.git');
+ assert.match(digest, /^[a-f0-9]{64}$/, 'Expected archive SHA-256');
+ const candidate = join(directory, 'node-package-candidate');
+ const archives = (await readdir(candidate)).filter((file) => file.endsWith('.tgz'));
+ assert.deepEqual(
+ archives,
+ [`instruktlabs-kiln-${manifest.version}.tgz`],
+ 'Expected exactly one versioned archive',
+ );
+ const tarball = join(candidate, archives[0]);
+ assert.equal(sha(await readFile(tarball)), digest, 'Candidate archive digest mismatch');
+ // Read one member without extracting or executing anything from the archive.
+ const packedManifest = JSON.parse(
+ execFileSync('tar', ['-xOf', tarball, 'package/package.json'], {
+ encoding: 'utf8',
+ windowsHide: true,
+ timeout: 10000,
+ maxBuffer: 1024 * 1024,
+ }),
+ );
+ assert.deepEqual(packedManifest, manifest, 'Packed manifest differs from the release checkout');
+ const coreExports = Object.keys(manifest.exports).filter(
+ (name) => !['./agent', './composer/agent'].includes(name),
+ ).length;
+ const receipts = [];
+ for (const item of RELEASE_RECEIPTS) {
+ const path = join(directory, item.artifact, item.file ?? 'package-smoke.json');
+ const receipt = await json(path);
+ const problems = receiptProblems(receipt, { ...item, manifest, toolchain });
+ assert.equal(problems.length, 0, `${item.artifact}: ${problems.join('; ')}`);
+ assert.equal(receipt.tarballSha256, digest, `${item.artifact}: archive digest mismatch`);
+ assert.equal(receipt.sdk?.imports, coreExports, `${item.artifact}: SDK import coverage`);
+ assert(
+ receipt.sdk?.renderBytes > 0 && receipt.compiledWorker?.renderBytes > 0,
+ `${item.artifact}: missing worker result`,
+ );
+ if (item.types) {
+ assert(
+ receipt.checks.includes('sdk-consumer-types-without-optional-peers'),
+ 'Missing consumer types check',
+ );
+ assert.deepEqual(receipt.sdkTypes, {
+ package: manifest.name,
+ entries: coreExports,
+ status: 'passed',
+ });
+ }
+ receipts.push({ artifact: item.artifact, sha256: sha(await readFile(path)) });
+ }
+ const rendererRoot = join(directory, 'linux-software-vulkan');
+ const checksum = (await readFile(join(rendererRoot, 'candidate-sha256.txt'), 'utf8')).trim();
+ assert.match(
+ checksum,
+ new RegExp(`^${digest} [ *][^\\r\\n]+$`),
+ 'Renderer archive digest mismatch',
+ );
+ const renderer = await json(join(rendererRoot, 'renderer-receipt/receipt.json'));
+ assert.equal(renderer.version, 'kiln.renderer-qualification.v1');
+ assert.equal(renderer.status, 'passed');
+ assert.equal(renderer.expected, 'software');
+ assert.equal(renderer.software, true);
+ assert.equal(renderer.backend, 'vulkan');
+ assert.equal(renderer.platform, 'linux');
+ assert.equal(renderer.arch, 'x64');
+ assert.equal(renderer.node, `v${toolchain.node}`);
+ const names = ['neutral', 'dark', 'light'].flatMap((backdrop) =>
+ [0, 1].map((n) => `${backdrop}-${n}.png`),
+ );
+ assert.deepEqual(
+ renderer.views.map((view) => view.name).sort(),
+ names.sort(),
+ 'Missing renderer views',
+ );
+ for (const view of renderer.views) {
+ assert(view.red > 20 && view.green > 20, 'Missing textured-view evidence');
+ assert.equal(
+ sha(await readFile(join(rendererRoot, 'renderer-receipt', view.name))),
+ view.sha256,
+ 'Renderer image digest mismatch',
+ );
+ }
+ receipts.push({
+ artifact: 'linux-software-vulkan',
+ sha256: sha(await readFile(join(rendererRoot, 'renderer-receipt/receipt.json'))),
+ });
+ return {
+ name: manifest.name,
+ version: manifest.version,
+ digest,
+ tarball,
+ tag: manifest.version.includes('-rc.') ? 'next' : 'latest',
+ receipts,
+ };
+}
+
+function gh(args) {
+ return execFileSync('gh', args, {
+ encoding: 'utf8',
+ windowsHide: true,
+ timeout: 120000,
+ maxBuffer: 16 * 1024 * 1024,
+ });
+}
+
+async function main() {
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+ const target = {
+ runId: process.env.CI_RUN_ID,
+ commit: process.env.GITHUB_SHA,
+ digest: process.env.CANDIDATE_SHA256,
+ mode: process.env.RELEASE_MODE ?? 'verify',
+ };
+ assert.match(target.runId ?? '', /^[1-9]\d*$/, 'CI_RUN_ID must be numeric');
+ assert.match(target.commit ?? '', /^[a-f0-9]{40}$/, 'GITHUB_SHA must be a commit SHA');
+ assert.match(target.digest ?? '', /^[a-f0-9]{64}$/, 'CANDIDATE_SHA256 must be an exact digest');
+ assert(['verify', 'stage'].includes(target.mode), 'Invalid release mode');
+ assert.equal(
+ process.env.GITHUB_REPOSITORY,
+ RELEASE_REPOSITORY,
+ 'Release must run in Instrukt Labs',
+ );
+ assert.equal(process.env.GITHUB_REF, 'refs/heads/main', 'Release must run from main');
+ assert.equal(
+ execFileSync('git', ['rev-parse', 'HEAD'], {
+ cwd: root,
+ encoding: 'utf8',
+ windowsHide: true,
+ }).trim(),
+ target.commit,
+ 'Checkout commit mismatch',
+ );
+ const route = `repos/${RELEASE_REPOSITORY}/actions/runs/${target.runId}`;
+ const pages = (path, key) =>
+ JSON.parse(gh(['api', '--paginate', '--slurp', `${path}?per_page=100`])).flatMap(
+ (page) => page[key],
+ );
+ const metadata = {
+ run: JSON.parse(gh(['api', route])),
+ jobs: pages(`${route}/jobs`, 'jobs'),
+ artifacts: pages(`${route}/artifacts`, 'artifacts'),
+ ...(target.mode === 'stage'
+ ? {
+ environment: JSON.parse(
+ gh(['api', `repos/${RELEASE_REPOSITORY}/environments/npm-release`]),
+ ),
+ }
+ : {}),
+ };
+ const problems = releaseMetadataProblems(metadata, target);
+ assert.equal(problems.length, 0, problems.join('\n'));
+ const cache = join(root, '.cache');
+ await mkdir(cache, { recursive: true });
+ const output = await mkdtemp(join(cache, 'npm-release-'));
+ const directory = join(output, 'artifacts');
+ gh([
+ 'run',
+ 'download',
+ target.runId,
+ '--repo',
+ RELEASE_REPOSITORY,
+ '--dir',
+ directory,
+ ...RELEASE_ARTIFACTS.flatMap((name) => ['--name', name]),
+ ]);
+ const result = await verifyReleaseArtifacts(directory, {
+ ...target,
+ manifest: await json(join(root, 'package.json')),
+ toolchain: await json(join(root, 'toolchain.json')),
+ });
+ const report = join(output, 'review.json');
+ await writeFile(
+ report,
+ `${JSON.stringify({ status: 'verified', ...target, ...result, artifactIds: metadata.artifacts.filter((artifact) => RELEASE_ARTIFACTS.includes(artifact.name)).map(({ name, id }) => ({ name, id })) }, null, 2)}\n`,
+ );
+ if (process.env.GITHUB_OUTPUT)
+ await appendFile(
+ process.env.GITHUB_OUTPUT,
+ `directory=${output}\ntarball=${result.tarball}\ntag=${result.tag}\nreport=${report}\n`,
+ );
+ console.log(
+ JSON.stringify({
+ status: 'verified',
+ ...target,
+ name: result.name,
+ version: result.version,
+ report,
+ }),
+ );
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ main().catch((error) => {
+ console.error(error.message);
+ process.exitCode = 1;
+ });
+}
diff --git a/scripts/prepare-npm-release.test.mjs b/scripts/prepare-npm-release.test.mjs
new file mode 100644
index 00000000..f98c5394
--- /dev/null
+++ b/scripts/prepare-npm-release.test.mjs
@@ -0,0 +1,399 @@
+import { afterEach, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve, sep } from 'node:path';
+import {
+ RELEASE_ARTIFACTS,
+ RELEASE_JOBS,
+ RELEASE_RECEIPTS,
+ releaseMetadataProblems,
+ verifyReleaseArtifacts,
+} from './prepare-npm-release.mjs';
+
+const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const commit = 'a'.repeat(40);
+const target = { runId: '42', commit, digest: 'b'.repeat(64), mode: 'stage' };
+function metadata() {
+ return {
+ run: {
+ id: 42,
+ path: '.github/workflows/ci.yml',
+ head_sha: commit,
+ head_branch: 'main',
+ event: 'push',
+ status: 'completed',
+ conclusion: 'success',
+ repository: { id: 1278326592, full_name: 'instruktlabs/kiln' },
+ head_repository: { id: 1278326592, full_name: 'instruktlabs/kiln' },
+ },
+ jobs: RELEASE_JOBS.map((name) => ({ name, status: 'completed', conclusion: 'success' })),
+ artifacts: RELEASE_ARTIFACTS.map((name, id) => ({
+ id: id + 1,
+ name,
+ expired: false,
+ workflow_run: {
+ id: 42,
+ head_sha: commit,
+ repository_id: 1278326592,
+ head_repository_id: 1278326592,
+ },
+ })),
+ environment: {
+ name: 'npm-release',
+ can_admins_bypass: false,
+ deployment_branch_policy: { protected_branches: true, custom_branch_policies: false },
+ protection_rules: [
+ {
+ type: 'required_reviewers',
+ reviewers: [{ type: 'User', reviewer: { login: 'matthew-kissinger' } }],
+ },
+ ],
+ },
+ };
+}
+
+test('a successful main push and protected stage environment are eligible', () => {
+ expect(releaseMetadataProblems(metadata(), target)).toEqual([]);
+});
+
+test.each([
+ [
+ 'PR event',
+ (data) => {
+ data.run.event = 'pull_request';
+ },
+ ],
+ [
+ 'other branch',
+ (data) => {
+ data.run.head_branch = 'codex/work';
+ },
+ ],
+ [
+ 'different commit',
+ (data) => {
+ data.run.head_sha = 'c'.repeat(40);
+ },
+ ],
+ [
+ 'different run',
+ (data) => {
+ data.run.id = 43;
+ },
+ ],
+ [
+ 'other workflow',
+ (data) => {
+ data.run.path = '.github/workflows/pages.yml';
+ },
+ ],
+ [
+ 'fork identity',
+ (data) => {
+ data.run.head_repository.id = 999;
+ },
+ ],
+ [
+ 'unfinished run',
+ (data) => {
+ data.run.status = 'in_progress';
+ },
+ ],
+ [
+ 'failed run',
+ (data) => {
+ data.run.conclusion = 'failure';
+ },
+ ],
+ [
+ 'missing platform job',
+ (data) => {
+ data.jobs.pop();
+ },
+ ],
+ [
+ 'skipped platform job',
+ (data) => {
+ data.jobs[0].conclusion = 'skipped';
+ },
+ ],
+ [
+ 'duplicate job',
+ (data) => {
+ data.jobs.push(data.jobs[0]);
+ },
+ ],
+ [
+ 'missing artifact',
+ (data) => {
+ data.artifacts.pop();
+ },
+ ],
+ [
+ 'expired artifact',
+ (data) => {
+ data.artifacts[0].expired = true;
+ },
+ ],
+ [
+ 'foreign artifact commit',
+ (data) => {
+ data.artifacts[0].workflow_run.head_sha = 'c'.repeat(40);
+ },
+ ],
+ [
+ 'duplicate artifact',
+ (data) => {
+ data.artifacts.push(data.artifacts[0]);
+ },
+ ],
+ [
+ 'missing release environment',
+ (data) => {
+ data.environment = undefined;
+ },
+ ],
+ [
+ 'no owner reviewer',
+ (data) => {
+ data.environment.protection_rules = [];
+ },
+ ],
+ [
+ 'admin bypass',
+ (data) => {
+ data.environment.can_admins_bypass = true;
+ },
+ ],
+ [
+ 'unrestricted branches',
+ (data) => {
+ data.environment.deployment_branch_policy = null;
+ },
+ ],
+])('release preparation rejects %s', (_name, corrupt) => {
+ const data = metadata();
+ corrupt(data);
+ expect(releaseMetadataProblems(data, target).length).toBeGreaterThan(0);
+});
+
+test('verification does not require publishing access, but an unknown mode is refused', () => {
+ const data = metadata();
+ delete data.environment;
+ expect(releaseMetadataProblems(data, { ...target, mode: 'verify' })).toEqual([]);
+ expect(releaseMetadataProblems(data, { ...target, mode: 'publish' }).length).toBeGreaterThan(0);
+ expect(
+ releaseMetadataProblems(data, { ...target, runId: '../43', mode: 'verify' }).length,
+ ).toBeGreaterThan(0);
+});
+
+test('release workflow defaults to read-only verification and only stages after owner approval', async () => {
+ const workflow = Bun.YAML.parse(
+ await readFile(new URL('../.github/workflows/release.yml', import.meta.url), 'utf8'),
+ );
+ expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch']);
+ expect(workflow.on.workflow_dispatch.inputs.mode).toMatchObject({
+ default: 'verify',
+ options: ['verify', 'stage'],
+ });
+ expect(workflow.permissions).toEqual({ contents: 'read', actions: 'read' });
+ expect(workflow.concurrency['cancel-in-progress']).toBe(false);
+ const { verify, stage } = workflow.jobs;
+ const toolchain = JSON.parse(
+ await readFile(new URL('../toolchain.json', import.meta.url), 'utf8'),
+ );
+ expect(verify.if).toContain("github.ref == 'refs/heads/main'");
+ expect(verify.if).toContain("github.repository == 'instruktlabs/kiln'");
+ expect(stage.needs).toBe('verify');
+ expect(stage.if).toContain("inputs.mode == 'stage'");
+ expect(stage.environment).toBe('npm-release');
+ expect(stage.permissions).toEqual({ contents: 'read', actions: 'read', 'id-token': 'write' });
+ for (const job of [verify, stage]) {
+ expect(job.steps.some((step) => step.run === 'node scripts/prepare-npm-release.mjs')).toBe(
+ true,
+ );
+ for (const step of job.steps) {
+ if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/);
+ if (step.uses?.startsWith('actions/checkout@'))
+ expect(step.with['persist-credentials']).toBe(false);
+ if (step.uses?.startsWith('actions/setup-node@'))
+ expect(step.with['node-version']).toBe(toolchain.node);
+ expect(step.run ?? '').not.toMatch(/npm (publish|stage approve)|npm (ci|pack)/);
+ expect(step.run ?? '').not.toContain('${{ inputs.');
+ }
+ }
+ expect(verify.steps.some((step) => /npm stage/.test(step.run ?? ''))).toBe(false);
+ expect(
+ stage.steps.some(
+ (step) => step.run === `npm install --global npm@${toolchain.npm} --ignore-scripts`,
+ ),
+ ).toBe(true);
+ const publish = stage.steps.find((step) => /npm stage publish/.test(step.run ?? ''));
+ expect(publish.run).toContain('npm stage publish "$TARBALL"');
+ expect(publish.run).toContain('--ignore-scripts --access public --provenance --tag "$TAG"');
+ expect(publish.env.TARBALL).toBe(`\${{ steps.prepare.outputs.tarball }}`);
+ expect(publish.env.TAG).toBe(`\${{ steps.prepare.outputs.tag }}`);
+ expect(JSON.stringify(workflow)).not.toMatch(/NPM_TOKEN|NODE_AUTH_TOKEN/);
+});
+
+test('release receipt requirements stay aligned with the CI platform matrix', async () => {
+ const ci = Bun.YAML.parse(
+ await readFile(new URL('../.github/workflows/ci.yml', import.meta.url), 'utf8'),
+ );
+ const names = Object.values(ci.jobs).flatMap((job) => {
+ const matrix = job.strategy?.matrix;
+ if (!matrix) return [job.name];
+ if (matrix.include)
+ return matrix.include.map((item) => job.name.replace(/\$\{\{ matrix\.arch \}\}/, item.arch));
+ return matrix.node.map((node) => job.name.replace(/\$\{\{ matrix\.node \}\}/, node));
+ });
+ expect([...RELEASE_JOBS].sort()).toEqual(names.sort());
+});
+
+const roots = [];
+afterEach(async () => {
+ for (const root of roots.splice(0)) {
+ if (!resolve(root).startsWith(resolve(tmpdir()) + sep)) throw new Error('Invalid test root');
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+const checks = [
+ 'installed-consumer-documents',
+ 'plain-node-sdk-exports',
+ 'sdk-subprocess-render',
+ 'compiled-evaluator-worker',
+ 'discovery-stability-labels',
+ 'local-plugin-bundle',
+ 'npm-mcp-entry',
+ 'packaged-node-worker',
+ 'community-exporter-textured-subprocess',
+ 'source-reference-edit-images',
+ 'server-restart-persistence',
+ 'exact-source-export',
+];
+async function fixture(version = '1.0.0-rc.1') {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-release-café-'));
+ roots.push(root);
+ const manifest = {
+ name: '@instruktlabs/kiln',
+ version,
+ type: 'module',
+ exports: {
+ '.': { types: './lib/index.d.ts', import: './lib/index.js' },
+ './arena': { types: './lib/arena/index.d.ts', import: './lib/arena/index.js' },
+ },
+ repository: { type: 'git', url: 'git+https://github.com/instruktlabs/kiln.git' },
+ publishConfig: { access: 'public', provenance: true },
+ };
+ const toolchain = { bun: '1.4.2', node: '22.23.3', npm: '12.2.0' };
+ await mkdir(join(root, 'package'));
+ await writeFile(join(root, 'package/package.json'), JSON.stringify(manifest));
+ const candidate = join(root, 'node-package-candidate');
+ await mkdir(candidate);
+ const tarball = join(candidate, `instruktlabs-kiln-${version}.tgz`);
+ execFileSync('tar', ['-czf', tarball, '-C', root, 'package/package.json'], { windowsHide: true });
+ const digest = sha(await readFile(tarball));
+ for (const item of RELEASE_RECEIPTS) {
+ await mkdir(join(root, item.artifact), { recursive: true });
+ await writeFile(
+ join(root, item.artifact, item.file ?? 'package-smoke.json'),
+ JSON.stringify({
+ platform: item.platform,
+ arch: item.arch,
+ node: `v${item.node ?? toolchain.node}`,
+ npm: item.npm ?? toolchain.npm,
+ engineName: manifest.name,
+ engineVersion: version,
+ status: 'passed',
+ tarballSha256: digest,
+ checks: [...checks, ...(item.types ? ['sdk-consumer-types-without-optional-peers'] : [])],
+ sdk: { imports: 2, renderBytes: 64 },
+ compiledWorker: { renderBytes: 64 },
+ sdkTypes: { package: manifest.name, entries: 2, status: 'passed' },
+ }),
+ );
+ }
+ const renderer = join(root, 'linux-software-vulkan/renderer-receipt');
+ await mkdir(renderer, { recursive: true });
+ const views = [];
+ for (const backdrop of ['neutral', 'dark', 'light'])
+ for (const n of [0, 1]) {
+ const name = `${backdrop}-${n}.png`;
+ const bytes = Buffer.from(`fixture ${name}`);
+ await writeFile(join(renderer, name), bytes);
+ views.push({ name, sha256: sha(bytes), red: 30, green: 30 });
+ }
+ await writeFile(
+ join(renderer, 'receipt.json'),
+ JSON.stringify({
+ version: 'kiln.renderer-qualification.v1',
+ status: 'passed',
+ expected: 'software',
+ software: true,
+ backend: 'vulkan',
+ platform: 'linux',
+ arch: 'x64',
+ node: `v${toolchain.node}`,
+ views,
+ }),
+ );
+ await writeFile(
+ join(root, 'linux-software-vulkan/candidate-sha256.txt'),
+ `${digest} /runner/candidate/${manifest.name.slice(1).replace('/', '-')}-${version}.tgz\n`,
+ );
+ return { root, tarball, target: { ...target, digest, manifest, toolchain } };
+}
+
+test('release verification accepts one exact RC archive and every platform receipt', async () => {
+ const data = await fixture();
+ const result = await verifyReleaseArtifacts(data.root, data.target);
+ expect(result).toMatchObject({
+ name: '@instruktlabs/kiln',
+ version: '1.0.0-rc.1',
+ digest: data.target.digest,
+ tag: 'next',
+ });
+ expect(result.tarball).toBe(data.tarball);
+});
+
+test('stable v1 uses latest; unpublished development builds cannot be staged', async () => {
+ const stable = await fixture('1.0.0');
+ expect((await verifyReleaseArtifacts(stable.root, stable.target)).tag).toBe('latest');
+ const dev = await fixture('1.0.0-dev.0');
+ await expect(verifyReleaseArtifacts(dev.root, dev.target)).rejects.toThrow('release version');
+});
+
+test.each(['digest', 'version', 'receipt', 'missing', 'types', 'image'])(
+ 'rejects %s evidence drift',
+ async (kind) => {
+ const data = await fixture();
+ if (kind === 'digest') data.target.digest = 'f'.repeat(64);
+ if (kind === 'version') data.target.manifest.version = '1.0.0-rc.2';
+ if (kind === 'receipt' || kind === 'missing') {
+ const path = join(data.root, 'windows-package/package-smoke.json');
+ if (kind === 'missing') await rm(path);
+ else {
+ const receipt = JSON.parse(await readFile(path, 'utf8'));
+ receipt.tarballSha256 = 'f'.repeat(64);
+ await writeFile(path, JSON.stringify(receipt));
+ }
+ }
+ if (kind === 'types') {
+ const path = join(data.root, 'node-package-candidate/candidate-sdk-receipt.json');
+ const receipt = JSON.parse(await readFile(path, 'utf8'));
+ receipt.checks = receipt.checks.filter(
+ (name) => name !== 'sdk-consumer-types-without-optional-peers',
+ );
+ await writeFile(path, JSON.stringify(receipt));
+ }
+ if (kind === 'image')
+ await writeFile(
+ join(data.root, 'linux-software-vulkan/renderer-receipt/neutral-0.png'),
+ 'tampered',
+ );
+ await expect(verifyReleaseArtifacts(data.root, data.target)).rejects.toThrow();
+ },
+);
diff --git a/scripts/qualify-project-foundation.mjs b/scripts/qualify-project-foundation.mjs
index d1d6a7a0..eed50f6d 100644
--- a/scripts/qualify-project-foundation.mjs
+++ b/scripts/qualify-project-foundation.mjs
@@ -211,7 +211,7 @@ try {
install,
);
receipt.checks.push('fresh-tarball-install-without-model-peers');
- const runtime = join(install, 'node_modules/@kiln/engine');
+ const runtime = join(install, 'node_modules/@instruktlabs/kiln');
receipt.runtime = runtime;
const pkg = JSON.parse(await readFile(join(runtime, 'package.json'), 'utf8'));
receipt.engineVersion = pkg.version;
@@ -264,7 +264,7 @@ try {
const importProbe = join(install, 'source-exports.ts');
await writeFile(
importProbe,
- `import { listMaterialPresets } from '@kiln/engine/material-presets'; import { FileMaterialLibrary } from '@kiln/engine/material-library/node'; import { FileProjectStore } from '@kiln/engine/projects/node'; if(listMaterialPresets().length !== 5 || !FileMaterialLibrary || !FileProjectStore) throw new Error('Source export mismatch'); console.log('source-exports-ok');`,
+ `import { listMaterialPresets } from '@instruktlabs/kiln/material-presets'; import { FileMaterialLibrary } from '@instruktlabs/kiln/material-library/node'; import { FileProjectStore } from '@instruktlabs/kiln/projects/node'; if(listMaterialPresets().length !== 5 || !FileMaterialLibrary || !FileProjectStore) throw new Error('Source export mismatch'); console.log('source-exports-ok');`,
);
await pass([importProbe], install, {}, process.env.BUN_BINARY ?? 'bun');
receipt.checks.push(
diff --git a/scripts/reliability.test.mjs b/scripts/reliability.test.mjs
index 246af62b..346fbec3 100644
--- a/scripts/reliability.test.mjs
+++ b/scripts/reliability.test.mjs
@@ -317,12 +317,10 @@ describe('repository reliability contracts', () => {
}
// And the replacement has to actually point somewhere that is kept current.
const install = await readText('docs/install.md');
- expect(install).toContain('https://github.com/matthew-kissinger/kiln/releases)');
+ expect(install).toContain('https://github.com/instruktlabs/kiln/releases)');
expect(install).toContain('tarball and checksum actually attached');
expect(install).toContain('a source-only release');
expect(install).toContain('does not imply that a built tarball is available');
- expect(install).toContain('0.10.0 is a source and site preview for dogfooding');
- expect(install.toLowerCase()).toContain('package publication is deferred to v1.0');
expect(install).toContain('tools.md');
});
diff --git a/scripts/setup-plugin-workspace.mjs b/scripts/setup-plugin-workspace.mjs
new file mode 100644
index 00000000..e0c774ab
--- /dev/null
+++ b/scripts/setup-plugin-workspace.mjs
@@ -0,0 +1,337 @@
+#!/usr/bin/env node
+// Copied into the local plugin: keep this entry independent of the engine checkout.
+import { spawn } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import {
+ lstat,
+ mkdir,
+ mkdtemp,
+ open,
+ readFile,
+ readdir,
+ realpath,
+ rename,
+ rm,
+ stat,
+ writeFile,
+} from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const packageName = '@instruktlabs/kiln';
+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const exactVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:rc|dev)\.(0|[1-9]\d*))?$/;
+
+function inside(parent, child) {
+ const path = relative(parent, child);
+ return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));
+}
+
+async function exists(path) {
+ try {
+ await lstat(path);
+ return true;
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ return false;
+ }
+}
+
+// Canonicalize future paths too, including Windows junctions and macOS /var aliases.
+async function canonical(path) {
+ const target = resolve(path);
+ let ancestor = target;
+ while (true) {
+ try {
+ return resolve(await realpath(ancestor), relative(ancestor, target));
+ } catch (error) {
+ if (error.code !== 'ENOENT' || dirname(ancestor) === ancestor) throw error;
+ ancestor = dirname(ancestor);
+ }
+ }
+}
+
+function defaultDataDirectory() {
+ if (process.platform === 'win32')
+ return join(process.env.LOCALAPPDATA || join(homedir(), 'AppData/Local'), 'InstruktLabs/Kiln');
+ return join(process.env.XDG_DATA_HOME || join(homedir(), '.local/share'), 'instruktlabs/kiln');
+}
+
+async function npmCli(explicit) {
+ const executable = await realpath(process.execPath);
+ const candidates = explicit
+ ? [explicit]
+ : [
+ process.env.npm_execpath,
+ join(dirname(executable), 'node_modules/npm/bin/npm-cli.js'),
+ resolve(dirname(executable), '../lib/node_modules/npm/bin/npm-cli.js'),
+ ];
+ for (const candidate of candidates.filter(Boolean)) {
+ if (!candidate.endsWith('npm-cli.js')) continue;
+ try {
+ if ((await stat(candidate)).isFile()) return await realpath(candidate);
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ }
+ }
+ throw new Error(
+ 'Cannot locate npm. Install Node with npm, or pass --npm-cli /absolute/path/to/npm-cli.js.',
+ );
+}
+
+function installWithNpm(npm, args, cwd) {
+ return new Promise((done, fail) => {
+ const child = spawn(process.execPath, [npm, ...args], {
+ cwd,
+ shell: false,
+ windowsHide: true,
+ stdio: ['ignore', 'ignore', 'pipe'],
+ });
+ let stderr = '';
+ let timedOut = false;
+ child.stderr.on('data', (data) => {
+ stderr = (stderr + data).slice(-6000);
+ });
+ const timer = setTimeout(() => {
+ timedOut = true;
+ child.kill();
+ }, 300000);
+ child.once('error', (error) => {
+ clearTimeout(timer);
+ fail(error);
+ });
+ child.once('close', (code) => {
+ clearTimeout(timer);
+ if (timedOut)
+ fail(
+ new Error('npm installation exceeded five minutes. Retry after checking network access.'),
+ );
+ else if (code !== 0) fail(new Error(`npm installation failed (${code}):\n${stderr}`));
+ else done();
+ });
+ });
+}
+
+async function readJson(path) {
+ return JSON.parse(await readFile(path, 'utf8'));
+}
+
+async function verifyPackage(root, pin) {
+ const runtime = join(root, 'node_modules/@instruktlabs/kiln');
+ const pkg = await readJson(join(runtime, 'package.json'));
+ if (pkg.name !== pin.name || pkg.version !== pin.version)
+ throw new Error(`Installed package identity does not match ${pin.name}@${pin.version}.`);
+ if (!inside(root, await realpath(runtime)))
+ throw new Error('Installed runtime escapes its version directory.');
+ if (!(await stat(join(runtime, 'scripts/create-workspace.mjs'))).isFile())
+ throw new Error('Installed runtime has no workspace setup entry.');
+ return runtime;
+}
+
+async function verifyRuntime(root, pin, archiveHash) {
+ try {
+ const marker = await readJson(join(root, 'kiln-runtime.json'));
+ if (marker.schemaVersion !== 1 || marker.name !== pin.name || marker.version !== pin.version)
+ throw new Error('Runtime marker identity mismatch.');
+ if (marker.lockSha256 !== hash(await readFile(join(root, 'package-lock.json'))))
+ throw new Error('Runtime lockfile changed.');
+ if (archiveHash && marker.archiveSha256 !== archiveHash)
+ throw new Error(
+ 'Runtime was installed from a different archive. Use a separate --data-dir for this candidate.',
+ );
+ return await verifyPackage(root, pin);
+ } catch (error) {
+ throw new Error(
+ `Cannot reuse runtime at ${root}: ${error.message}. Existing files were left unchanged.`,
+ { cause: error },
+ );
+ }
+}
+
+async function removeStage(stage, runtimes) {
+ const resolvedStage = await realpath(stage);
+ const resolvedRuntimes = await realpath(runtimes);
+ if (!inside(resolvedRuntimes, resolvedStage) || dirname(resolvedStage) !== resolvedRuntimes)
+ throw new Error('Refusing to remove a staging directory outside the runtime store.');
+ await rm(resolvedStage, { recursive: true, force: true });
+}
+
+async function installRuntime(data, pin, archive, archiveHash, options) {
+ const runtimes = join(data, 'runtimes');
+ if (relative(runtimes, await canonical(runtimes)) !== '')
+ throw new Error(
+ 'The runtime store must remain inside its persistent data directory, without a redirected runtimes path.',
+ );
+ const target = join(runtimes, pin.version);
+ if (await exists(target)) return verifyRuntime(target, pin, archiveHash);
+ if (options.mode === 'check')
+ throw new Error(`Pinned runtime ${pin.version} is not installed; check makes no changes.`);
+ const npm = options.run ? options.npmPath : await npmCli(options.npmPath);
+ await mkdir(runtimes, { recursive: true });
+ // Serialize competing setup processes without treating a crashed lock as safe to delete.
+ const lockPath = join(runtimes, `${pin.version}.lock`);
+ let lock;
+ try {
+ lock = await open(lockPath, 'wx');
+ } catch (error) {
+ if (error.code !== 'EEXIST') throw error;
+ throw new Error(
+ `Runtime setup is locked at ${lockPath}. Wait for the other setup, or verify it has stopped before removing its lock.`,
+ );
+ }
+ let stage;
+ try {
+ if (await exists(target)) return await verifyRuntime(target, pin, archiveHash);
+ stage = await mkdtemp(join(runtimes, `${pin.version}.staging-`));
+ await writeFile(
+ join(stage, 'package.json'),
+ JSON.stringify({ name: 'kiln-plugin-runtime', version: '0.0.0', private: true }),
+ );
+ const args = [
+ 'install',
+ archive || `${pin.name}@${pin.version}`,
+ '--save-exact',
+ '--ignore-scripts',
+ '--omit=dev',
+ '--include=optional',
+ '--no-audit',
+ '--no-fund',
+ '--registry=https://registry.npmjs.org',
+ ];
+ if (options.run) await options.run(args, stage);
+ else await installWithNpm(npm, args, stage);
+ await verifyPackage(stage, pin);
+ await writeFile(
+ join(stage, 'kiln-runtime.json'),
+ `${JSON.stringify(
+ {
+ schemaVersion: 1,
+ ...pin,
+ lockSha256: hash(await readFile(join(stage, 'package-lock.json'))),
+ archiveSha256: archiveHash || null,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ if (await exists(target))
+ throw new Error('The runtime destination appeared during setup; no files were replaced.');
+ await rename(stage, target);
+ stage = undefined;
+ return await verifyRuntime(target, pin, archiveHash);
+ } finally {
+ try {
+ if (stage) await removeStage(stage, runtimes);
+ } finally {
+ await lock.close();
+ await rm(lockPath);
+ }
+ }
+}
+
+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))
+ throw new Error('Unknown workspace setup mode.');
+ if (!options.directory) throw new Error('Provide a workspace directory.');
+ if (
+ options.skills &&
+ (mode !== 'create' ||
+ !Array.isArray(options.skills) ||
+ options.skills.some((name) => !['compose', 'batch'].includes(name)))
+ )
+ throw new Error('Optional skills compose,batch apply only to workspace creation.');
+ const plugin = await canonical(
+ options.pluginRoot || resolve(dirname(fileURLToPath(import.meta.url)), '..'),
+ );
+ const pin = await readJson(join(plugin, 'runtime.json'));
+ 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.');
+ const directory = await canonical(options.directory);
+ const data = await canonical(options.dataDirectory || defaultDataDirectory());
+ for (const [a, b] of [
+ [plugin, directory],
+ [plugin, data],
+ [directory, data],
+ ])
+ 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 (!(await lstat(directory)).isDirectory() || (await readdir(directory)).length)
+ throw new Error(
+ 'The workspace destination must be an empty directory; no existing files were changed.',
+ );
+ }
+ const archive = options.archive ? await realpath(resolve(options.archive)) : undefined;
+ const archiveHash = archive ? hash(await readFile(archive)) : undefined;
+ const runtime = await installRuntime(
+ data,
+ { name: pin.name, version: pin.version },
+ archive,
+ archiveHash,
+ { ...options, mode },
+ );
+ const { createWorkspace } = await import(
+ pathToFileURL(join(runtime, 'scripts/create-workspace.mjs')).href
+ );
+ const workspace = await createWorkspace(directory, harness, {
+ installation: runtime,
+ ...(mode === 'create' ? {} : { [mode]: true }),
+ ...(options.skills ? { skills: options.skills } : {}),
+ });
+ return { runtime, workspace };
+}
+
+export function parseSetupArguments(args) {
+ if (args.includes('--help') || args.includes('-h')) return { help: true };
+ const values = [...args];
+ const directory = values.shift();
+ if (!directory || directory.startsWith('--'))
+ throw new Error('Provide a workspace directory. Run with --help for usage.');
+ const result = { directory };
+ const valueFlags = {
+ '--harness': 'harness',
+ '--data-dir': 'dataDirectory',
+ '--archive': 'archive',
+ '--npm-cli': 'npmPath',
+ '--skills': 'skills',
+ };
+ 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.');
+ result.mode = flag.slice(2);
+ } else if (Object.hasOwn(valueFlags, flag)) {
+ const value = values.shift();
+ if (!value || value.startsWith('--')) throw new Error(`Missing value for ${flag}.`);
+ if (Object.hasOwn(result, valueFlags[flag])) throw new Error(`Repeated option ${flag}.`);
+ result[valueFlags[flag]] = flag === '--skills' ? value.split(',') : value;
+ } else throw new Error(`Unknown option ${flag}.`);
+ }
+ return result;
+}
+
+if (
+ process.argv[1] &&
+ (await canonical(process.argv[1])) === (await realpath(fileURLToPath(import.meta.url)))
+) {
+ try {
+ const options = parseSetupArguments(process.argv.slice(2));
+ if (options.help)
+ console.log(
+ 'Usage: node scripts/setup-workspace.mjs <directory> [--harness claude|codex] [--skills compose,batch]\n node scripts/setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>',
+ );
+ else {
+ const result = await setupPluginWorkspace(options);
+ console.log(JSON.stringify(result, null, 2));
+ if (options.mode === 'check' && result.workspace.status !== 'current') process.exitCode = 1;
+ }
+ } catch (error) {
+ console.error(error.message);
+ process.exitCode = 1;
+ }
+}
diff --git a/scripts/setup-plugin-workspace.test.mjs b/scripts/setup-plugin-workspace.test.mjs
new file mode 100644
index 00000000..7c353ebe
--- /dev/null
+++ b/scripts/setup-plugin-workspace.test.mjs
@@ -0,0 +1,313 @@
+import { afterEach, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import {
+ cp,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ realpath,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve, sep } from 'node:path';
+import { parseSetupArguments, setupPluginWorkspace } from './setup-plugin-workspace.mjs';
+
+const roots = [];
+afterEach(async () => {
+ for (const root of roots.splice(0)) {
+ if (!resolve(root).startsWith((await realpath(tmpdir())) + sep))
+ throw new Error('Invalid test root');
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+async function fixture() {
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'kiln-plugin-setup-café-')));
+ roots.push(root);
+ const pluginRoot = join(root, 'plugin-cache');
+ await mkdir(pluginRoot);
+ const pin = { name: '@instruktlabs/kiln', version: '1.0.0-rc.1' };
+ await writeFile(join(pluginRoot, 'runtime.json'), JSON.stringify(pin));
+ const calls = [];
+ const run = async (args, cwd) => {
+ calls.push({ args, cwd });
+ const engine = join(cwd, 'node_modules/@instruktlabs/kiln');
+ await mkdir(join(engine, 'scripts'), { recursive: true });
+ await writeFile(join(engine, 'package.json'), JSON.stringify(pin));
+ await writeFile(join(cwd, 'package-lock.json'), '{"lockfileVersion":3}');
+ // The real engine owns workspace generation and conflict-preserving upgrades.
+ await writeFile(
+ join(engine, 'scripts/create-workspace.mjs'),
+ `
+export async function createWorkspace(root, harness, options) {
+ return {root,harness,options,fixture:true};
+}
+`,
+ );
+ };
+ return {
+ root,
+ pin,
+ calls,
+ options: {
+ pluginRoot,
+ directory: join(root, 'my assets'),
+ dataDirectory: join(root, 'durable data'),
+ harness: 'claude',
+ npmPath: join(root, 'npm-cli.js'),
+ run,
+ },
+ };
+}
+
+test('plugin setup installs an exact package once outside the cache and delegates workspace creation', async () => {
+ const f = await fixture();
+ const result = await setupPluginWorkspace(f.options);
+ expect(f.calls).toHaveLength(1);
+ expect(f.calls[0].args).toContain('@instruktlabs/[email protected]');
+ expect(f.calls[0].args).toContain('--ignore-scripts');
+ expect(f.calls[0].args).toContain('--include=optional');
+ expect(f.calls[0].args).toContain('--registry=https://registry.npmjs.org');
+ expect(f.calls[0].cwd.startsWith(f.options.pluginRoot + sep)).toBe(false);
+ expect(result.workspace).toMatchObject({ root: f.options.directory, harness: 'claude' });
+ expect(result.runtime.startsWith(f.options.dataDirectory + sep)).toBe(true);
+ expect(result.runtime).not.toContain('.staging-');
+ const after = await setupPluginWorkspace({ ...f.options, directory: join(f.root, 'another') });
+ expect(after.runtime).toBe(result.runtime);
+ expect(f.calls).toHaveLength(1);
+});
+
+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) => {
+ const f = await fixture();
+ await writeFile(
+ join(f.options.pluginRoot, 'runtime.json'),
+ JSON.stringify({ ...f.pin, version }),
+ );
+ await expect(setupPluginWorkspace(f.options)).rejects.toThrow('exact');
+ expect(f.calls).toHaveLength(0);
+ await expect(readFile(join(f.options.dataDirectory, 'package.json'))).rejects.toThrow();
+ },
+);
+
+test('rejects another package name and unsupported harnesses before installation', async () => {
+ const f = await fixture();
+ await expect(setupPluginWorkspace({ ...f.options, harness: 'unknown' })).rejects.toThrow(
+ 'harness',
+ );
+ await writeFile(
+ join(f.options.pluginRoot, 'runtime.json'),
+ JSON.stringify({ ...f.pin, name: 'other' }),
+ );
+ await expect(setupPluginWorkspace(f.options)).rejects.toThrow('package');
+ expect(f.calls).toHaveLength(0);
+});
+
+test('refuses runtime or workspace paths inside the disposable plugin cache', async () => {
+ const f = await fixture();
+ for (const change of [
+ { directory: join(f.options.pluginRoot, 'assets') },
+ { dataDirectory: join(f.options.pluginRoot, 'data') },
+ { dataDirectory: f.options.directory },
+ { directory: f.options.dataDirectory },
+ ]) {
+ await expect(setupPluginWorkspace({ ...f.options, ...change })).rejects.toThrow('separate');
+ }
+ expect(f.calls).toHaveLength(0);
+});
+
+test('does not install or touch an existing nonempty directory when creation was requested', async () => {
+ const f = await fixture();
+ await mkdir(f.options.directory);
+ const source = join(f.options.directory, 'my-source.js');
+ await writeFile(source, 'keep me');
+ await expect(setupPluginWorkspace(f.options)).rejects.toThrow('empty');
+ expect(await readFile(source, 'utf8')).toBe('keep me');
+ expect(f.calls).toHaveLength(0);
+});
+
+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(
+ 'not installed',
+ );
+ expect(f.calls).toHaveLength(0);
+ expect(await readdir(f.root)).toEqual(['plugin-cache']);
+});
+
+test('a failed install removes only its staging directory', async () => {
+ const f = await fixture();
+ await mkdir(f.options.dataDirectory);
+ await writeFile(join(f.options.dataDirectory, 'keep.txt'), 'owner data');
+ await expect(
+ setupPluginWorkspace({
+ ...f.options,
+ run: async () => {
+ throw new Error('npm failed');
+ },
+ }),
+ ).rejects.toThrow('npm failed');
+ expect(await readFile(join(f.options.dataDirectory, 'keep.txt'), 'utf8')).toBe('owner data');
+ expect(await readdir(join(f.options.dataDirectory, 'runtimes'))).toEqual([]);
+});
+
+test('an existing unknown runtime is never overwritten or repaired implicitly', async () => {
+ const f = await fixture();
+ const target = join(f.options.dataDirectory, 'runtimes', f.pin.version);
+ await mkdir(target, { recursive: true });
+ await writeFile(join(target, 'private.txt'), 'keep');
+ await expect(setupPluginWorkspace(f.options)).rejects.toThrow('runtime');
+ expect(f.calls).toHaveLength(0);
+ expect(await readFile(join(target, 'private.txt'), 'utf8')).toBe('keep');
+});
+
+test('a package identity mismatch never reaches the engine or publishes an installation', async () => {
+ const f = await fixture();
+ const run = f.options.run;
+ await expect(
+ setupPluginWorkspace({
+ ...f.options,
+ run: async (...args) => {
+ await run(...args);
+ await writeFile(
+ join(args[1], 'node_modules/@instruktlabs/kiln/package.json'),
+ JSON.stringify({ ...f.pin, version: '9.0.0' }),
+ );
+ },
+ }),
+ ).rejects.toThrow('identity');
+ expect(await readdir(join(f.options.dataDirectory, 'runtimes'))).toEqual([]);
+});
+
+test('upgrade and check preserve the engine upgrade protocol rather than rewriting workspace files', async () => {
+ const f = await fixture();
+ const initial = await setupPluginWorkspace(f.options);
+ for (const mode of ['upgrade', 'check']) {
+ const result = await setupPluginWorkspace({ ...f.options, mode });
+ expect(result.runtime).toBe(initial.runtime);
+ expect(result.workspace.options[mode]).toBe(true);
+ expect(result.workspace.options.installation).toBe(initial.runtime);
+ }
+ expect(f.calls).toHaveLength(1);
+});
+
+test('an explicit local qualification archive replaces only the npm spec, not the required identity', async () => {
+ const f = await fixture();
+ const archive = join(f.root, 'candidate.tgz');
+ await writeFile(archive, 'fixture');
+ const result = await setupPluginWorkspace({ ...f.options, archive });
+ expect(f.calls[0].args).toContain(archive);
+ expect(f.calls[0].args).not.toContain('@instruktlabs/[email protected]');
+ expect(
+ JSON.parse(
+ await readFile(join(dirname(dirname(dirname(result.runtime))), 'kiln-runtime.json'), 'utf8'),
+ ),
+ ).toMatchObject({ name: f.pin.name, version: f.pin.version });
+});
+
+test('CLI check returns failure for workspace drift without running an installation', async () => {
+ const f = await fixture();
+ const { runtime } = await setupPluginWorkspace(f.options);
+ await writeFile(
+ join(runtime, 'scripts/create-workspace.mjs'),
+ 'export async function createWorkspace() { return {status:"update-required"}; }',
+ );
+ const script = join(f.options.pluginRoot, 'scripts/setup-workspace.mjs');
+ await mkdir(dirname(script));
+ await cp(new URL('./setup-plugin-workspace.mjs', import.meta.url), script);
+ const result = spawnSync(
+ process.execPath,
+ [script, f.options.directory, '--check', '--data-dir', f.options.dataDirectory],
+ { encoding: 'utf8', timeout: 10000, windowsHide: true },
+ );
+ expect(result.error).toBeUndefined();
+ expect(result.status).toBe(1);
+ expect(JSON.parse(result.stdout).workspace.status).toBe('update-required');
+ expect(f.calls).toHaveLength(1);
+});
+
+test('different candidate bytes cannot silently reuse a runtime with the same version', async () => {
+ const f = await fixture();
+ const archive = join(f.root, 'candidate.tgz');
+ await writeFile(archive, 'first');
+ await setupPluginWorkspace({ ...f.options, archive });
+ await writeFile(archive, 'second');
+ await expect(setupPluginWorkspace({ ...f.options, archive })).rejects.toThrow(
+ 'different archive',
+ );
+ expect(f.calls).toHaveLength(1);
+});
+
+test('changed dependency lock is reported without reinstalling or rewriting it', async () => {
+ const f = await fixture();
+ const { runtime } = await setupPluginWorkspace(f.options);
+ const lock = join(dirname(dirname(dirname(runtime))), 'package-lock.json');
+ await writeFile(lock, 'edited');
+ await expect(setupPluginWorkspace(f.options)).rejects.toThrow('lockfile changed');
+ expect(await readFile(lock, 'utf8')).toBe('edited');
+ expect(f.calls).toHaveLength(1);
+});
+
+test('a path alias cannot place workspace data inside a plugin cache', async () => {
+ const f = await fixture();
+ const alias = join(f.root, 'cache alias');
+ await symlink(f.options.pluginRoot, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ await expect(
+ setupPluginWorkspace({ ...f.options, directory: join(alias, 'assets') }),
+ ).rejects.toThrow('separate');
+ expect(f.calls).toHaveLength(0);
+});
+
+test('setup does not remove another process lock or begin a competing installation', async () => {
+ const f = await fixture();
+ const lock = join(f.options.dataDirectory, 'runtimes', `${f.pin.version}.lock`);
+ await mkdir(dirname(lock), { recursive: true });
+ await writeFile(lock, 'other setup');
+ await expect(setupPluginWorkspace(f.options)).rejects.toThrow('locked');
+ expect(await readFile(lock, 'utf8')).toBe('other setup');
+ expect(f.calls).toHaveLength(0);
+});
+
+test('a redirected runtime store cannot install into the disposable cache', async () => {
+ const f = await fixture();
+ await mkdir(f.options.dataDirectory);
+ await symlink(
+ f.options.pluginRoot,
+ join(f.options.dataDirectory, 'runtimes'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ await expect(setupPluginWorkspace(f.options)).rejects.toThrow('runtime store');
+ expect(f.calls).toHaveLength(0);
+});
+
+test('setup validates CLI values and mutually exclusive maintenance modes', () => {
+ expect(parseSetupArguments(['--help'])).toEqual({ help: true });
+ expect(
+ parseSetupArguments(['my assets', '--harness', 'codex', '--skills', 'compose,batch']),
+ ).toEqual({ directory: 'my assets', harness: 'codex', skills: ['compose', 'batch'] });
+ for (const args of [
+ [],
+ ['--check'],
+ ['assets', '--unknown'],
+ ['assets', '--harness'],
+ ['assets', '--harness', '--check'],
+ ['assets', '--check', '--upgrade'],
+ ['assets', '--data-dir', 'one', '--data-dir', 'two'],
+ ])
+ expect(() => parseSetupArguments(args)).toThrow();
+});
+
+test('invalid mode or skill selection fails before installing an engine', async () => {
+ const f = await fixture();
+ for (const options of [
+ { mode: 'replace' },
+ { skills: ['unknown'] },
+ { mode: 'upgrade', skills: ['compose'] },
+ ])
+ await expect(setupPluginWorkspace({ ...f.options, ...options })).rejects.toThrow();
+ expect(f.calls).toHaveLength(0);
+});
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index cb93b3e7..20ae75da 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -3,14 +3,17 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createHash } from 'node:crypto';
-import { mkdir, mkdtemp, readFile, stat, writeFile } from 'node:fs/promises';
+import { mkdir, mkdtemp, readFile, readdir, realpath, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
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';
const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
-const root = await mkdtemp(join(tmpdir(), 'kiln-package-café-'));
+// macOS exposes /var through /private/var. Match Node's canonical module URLs
+// before asserting that the installed SDK identifies its own package directory.
+const root = await realpath(await mkdtemp(join(tmpdir(), 'kiln-package-café-')));
const receipt = {
root,
platform: process.platform,
@@ -75,7 +78,7 @@ async function npmCli() {
}
async function connect(server, cwd, store) {
- const child = spawn(process.execPath, [server], {
+ const child = spawn(process.execPath, Array.isArray(server) ? server : [server], {
cwd,
windowsHide: true,
env: { ...process.env, KILN_RENDER: 'cpu', KILN_PROGRAM_STORE: store },
@@ -121,9 +124,25 @@ async function connect(server, cwd, store) {
});
child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);
});
- const close = () => {
- child.kill();
- };
+ // EOF also reaches the server when npm is its parent. Killing only the npm
+ // wrapper can leave a running server behind on Windows.
+ const close = () =>
+ new Promise((done, fail) => {
+ if (child.exitCode !== null || child.signalCode !== null) return done();
+ const timer = setTimeout(() => {
+ child.kill();
+ fail(
+ new Error(
+ `MCP process did not exit within 5000 ms after stdin closed: ${JSON.stringify(server)}; exit=${child.exitCode}, signal=${child.signalCode}; stderr: ${stderr}`,
+ ),
+ );
+ }, 5000);
+ child.once('exit', () => {
+ clearTimeout(timer);
+ done();
+ });
+ child.stdin.end();
+ });
child.on('error', (error) => {
for (const resolve of pending.values()) resolve({ error: { message: error.message } });
pending.clear();
@@ -144,7 +163,7 @@ async function connect(server, cwd, store) {
);
return { call, close };
} catch (error) {
- close();
+ await close();
throw error;
}
}
@@ -157,9 +176,10 @@ const textResult = (result) => {
try {
const npm = await npmCli();
receipt.npm = (await command([npm, '--version'], root)).trim();
- const args = process.argv.slice(2);
+ const checkTypes = process.argv.includes('--types');
+ const args = process.argv.slice(2).filter((argument) => argument !== '--types');
if (args.length !== 0 && (args.length !== 2 || args[0] !== '--tarball'))
- throw new Error('Usage: smoke-package.mjs [--tarball /absolute/package.tgz]');
+ throw new Error('Usage: smoke-package.mjs [--tarball /absolute/package.tgz] [--types]');
if (args.length) {
receipt.tarball = resolve(args[1]);
assert((await stat(receipt.tarball)).isFile(), 'Tarball must be a file.');
@@ -196,14 +216,128 @@ try {
[npm, 'install', receipt.tarball, '--omit=dev', '--no-audit', '--no-fund'],
install,
);
- const runtime = join(install, 'node_modules/@kiln/engine');
+ const runtime = join(install, 'node_modules/@instruktlabs/kiln');
const pkg = JSON.parse(await readFile(join(runtime, 'package.json'), 'utf8'));
+ receipt.engineName = pkg.name;
receipt.engineVersion = pkg.version;
+ assert.equal(pkg.name, '@instruktlabs/kiln');
+ assert.equal(pkg.bin['kiln-mcp'], './dist/mcp-server.mjs');
+ const plugin = join(runtime, 'plugins/kiln-engine');
+ const pluginJson = async (path) => JSON.parse(await readFile(join(plugin, path), 'utf8'));
+ const portablePlugin = await pluginJson('plugin.json');
+ assert.equal(
+ portablePlugin.$schema,
+ 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json',
+ );
+ assert.equal(portablePlugin.name, 'kiln-engine');
+ assert.equal(portablePlugin.version, pkg.version);
+ assert.equal((await pluginJson('.claude-plugin/plugin.json')).version, pkg.version);
+ assert.deepEqual(await pluginJson('runtime.json'), { name: pkg.name, version: pkg.version });
+ assert.deepEqual(await readdir(join(plugin, 'skills')), ['kiln-setup-workspace']);
+ const pluginReceipt = await pluginJson('package-provenance.json');
+ assert.equal(pluginReceipt.kind, 'kiln-local-plugin');
+ assert.equal(pluginReceipt.engineVersion, pkg.version);
+ for (const [name, digest] of Object.entries(pluginReceipt.files))
+ assert.equal(
+ `sha256:${sha(await readFile(join(plugin, name)))}`,
+ digest,
+ `Plugin file ${name}`,
+ );
+ for (const catalog of ['.agents/plugins/marketplace.json', '.claude-plugin/marketplace.json']) {
+ const marketplace = JSON.parse(await readFile(join(runtime, catalog), 'utf8'));
+ assert.equal(marketplace.name, 'instruktlabs');
+ assert.equal(marketplace.plugins[0].name, portablePlugin.name);
+ const source = marketplace.plugins[0].source;
+ assert.equal(typeof source === 'string' ? source : source.path, './plugins/kiln-engine');
+ }
+ receipt.checks.push('local-plugin-bundle');
+ // Check the installed tree too: CI consumers receive a prepacked archive,
+ // so checking only this checkout's `npm pack` inventory would miss them.
+ const docs = await readdir(join(runtime, 'docs'), { withFileTypes: true });
+ assert(docs.every((entry) => entry.isFile() && entry.name.endsWith('.md')));
+ assert.deepEqual(
+ docs.map((entry) => `docs/${entry.name}`).sort(),
+ pkg.files.filter((entry) => entry.startsWith('docs/')).sort(),
+ 'Installed documentation must match the explicit consumer allowlist',
+ );
+ for (const entry of docs) {
+ const document = join(runtime, 'docs', entry.name);
+ const body = await readFile(document, 'utf8');
+ for (const [, href] of body.matchAll(/\]\(([^)\s]+)\)/g)) {
+ if (/^(?:[a-z]+:|\/|#)/i.test(href)) continue;
+ const target = fileURLToPath(new URL(href, pathToFileURL(document)));
+ assert(
+ await stat(target).then(
+ () => true,
+ () => false,
+ ),
+ `Broken installed documentation link in ${entry.name}: ${href}`,
+ );
+ }
+ }
+ receipt.checks.push('installed-consumer-documents');
+ const coreExports = Object.keys(pkg.exports).filter(
+ (name) => !['./agent', './composer/agent'].includes(name),
+ );
+ await writeFile(
+ join(install, 'sdk-check.mjs'),
+ `import assert from 'node:assert/strict';
+const name = ${JSON.stringify(pkg.name)};
+const sdk = await import(name);
+for (const subpath of ${JSON.stringify(coreExports)}) {
+ await import(subpath === '.' ? name : name + '/' + subpath.slice(2));
+}
+assert.equal(typeof sdk.validateKilnCode, 'function');
+assert.equal(typeof sdk.createDiscovery, 'function');
+const arena = await import(name + '/arena');
+assert.equal(arena.fitBradleyTerry([{winner:'a',loser:'b'}]).items[0].id, 'a');
+assert.deepEqual(arena.pickNextPair(['a','b'], []), {a:'a',b:'b'});
+const result = await sdk.renderGLB('function build() { return new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0x888888)); }');
+assert.equal(result.glb.subarray(0, 4).toString('utf8'), 'glTF');
+assert.equal(sdk.engineIdentity().installUrl, ${JSON.stringify(pathToFileURL(`${runtime}/`).href)});
+console.log(JSON.stringify({ imports: ${coreExports.length}, renderBytes: result.glb.length }));
+`,
+ );
+ receipt.sdk = JSON.parse(
+ await command([join(install, 'sdk-check.mjs')], install, {
+ KILN_RENDER: 'cpu',
+ KILN_EVALUATOR_MODE: 'subprocess',
+ }),
+ );
+ receipt.checks.push('plain-node-sdk-exports', 'sdk-subprocess-render');
+ // Qualify the compiled worker's native imports and wire protocol. This runs
+ // trusted fixture code without an OS sandbox; provider isolation is a separate gate.
+ await writeFile(
+ join(install, 'compiled-worker-check.mjs'),
+ `import assert from 'node:assert/strict';
+import { renderGLBViaProcessLaunch, sanitizedEvaluatorEnv } from ${JSON.stringify(pathToFileURL(join(runtime, 'lib/evaluator/subprocess.js')).href)};
+const result = await renderGLBViaProcessLaunch(
+ 'function build() { return new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0x888888)); }',
+ {}, {}, {
+ command: process.execPath,
+ args: ['--max-old-space-size=512', ${JSON.stringify(join(runtime, 'lib/evaluator/worker.js'))}],
+ env: sanitizedEvaluatorEnv(),
+ });
+assert.equal(result.glb.subarray(0, 4).toString('utf8'), 'glTF');
+console.log(JSON.stringify({ renderBytes: result.glb.length }));
+`,
+ );
+ receipt.compiledWorker = JSON.parse(
+ await command([join(install, 'compiled-worker-check.mjs')], install),
+ );
+ receipt.checks.push('compiled-evaluator-worker');
+ if (checkTypes) {
+ receipt.sdkTypes = await smokeSdkTypes(runtime);
+ receipt.checks.push('sdk-consumer-types-without-optional-peers');
+ }
for (const required of [
'dist/cli.mjs',
'dist/mcp-server.mjs',
'dist/mcp-engine.mjs',
'dist/evaluator-worker.mjs',
+ 'lib/evaluator/worker.js',
+ 'lib/evaluator/probe-worker.js',
+ 'lib/evaluator/transport-worker.mjs',
'scripts/create-workspace.mjs',
'plugin.json',
'.claude-plugin/plugin.json',
@@ -421,12 +555,42 @@ try {
receipt.checks.push('community-exporter-textured-subprocess');
const server = join(runtime, 'dist/mcp-server.mjs'),
store = join(workspace, '.kiln/programs');
+ const binSession = await connect([npm, 'exec', '--offline', '--', 'kiln-mcp'], install, store);
+ try {
+ const listed = await binSession.call('tools/list', {});
+ assert(listed.tools.some((tool) => tool.name === 'kiln_render'));
+ receipt.checks.push('npm-mcp-entry');
+ } finally {
+ await binSession.close();
+ }
const session = await connect(server, root, store);
let changed;
try {
const listed = await session.call('tools/list', {});
assert(listed.tools.some((tool) => tool.name === 'kiln_source'));
assert(listed.tools.some((tool) => tool.name === 'kiln_render'));
+ for (const [id, stability] of [
+ ['operation:boxGeo', 'stable'],
+ ['operation:implicitSurface', 'experimental'],
+ ['recipe:steerable-wheel-v1', 'experimental'],
+ ]) {
+ const result = await session.call('tools/call', {
+ name: 'kiln_discover',
+ arguments: { query: id, limit: 1 },
+ });
+ assert.notEqual(result.isError, true);
+ assert(
+ result.content.some(
+ (item) => item.type === 'text' && item.text.includes(`${id} [${stability}]`),
+ ),
+ );
+ }
+ const cliDiscovery = await command(
+ [cli, 'discover', '--query', 'recipe:steerable-wheel-v1', '--limit', '1'],
+ root,
+ );
+ assert.match(cliDiscovery, /recipe:steerable-wheel-v1 \[experimental\]/);
+ receipt.checks.push('discovery-stability-labels');
const read = textResult(
await session.call('tools/call', {
name: 'kiln_source',
@@ -447,7 +611,7 @@ try {
assert(result.content.some((item) => item.type === 'image' && item.data.length > 100));
receipt.editResult = { programRef: changed.programRef, parentRef: changed.parentRef };
} finally {
- session.close();
+ await session.close();
}
const restarted = await connect(server, install, store);
try {
@@ -459,7 +623,7 @@ try {
);
assert.match(after.code, /0xaa8844/);
} finally {
- restarted.close();
+ await restarted.close();
}
await command(
[cli, 'source', changed.programRef, '--out', join(workspace, 'revised.kiln.js')],
diff --git a/scripts/smoke-sdk-types.mjs b/scripts/smoke-sdk-types.mjs
new file mode 100644
index 00000000..f22e3498
--- /dev/null
+++ b/scripts/smoke-sdk-types.mjs
@@ -0,0 +1,66 @@
+#!/usr/bin/env node
+import { execFileSync } from 'node:child_process';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+/** Typecheck an installed consumer without resolving optional peers from this repo. */
+export async function smokeSdkTypes(runtime, { includeAgentPeers = false } = {}) {
+ const pkg = JSON.parse(await readFile(join(runtime, 'package.json'), 'utf8'));
+ const entries = Object.keys(pkg.exports).filter(
+ (name) => includeAgentPeers || !['./agent', './composer/agent'].includes(name),
+ );
+ const stage = await mkdtemp(join(runtime, '.sdk-consumer-'));
+ try {
+ const source = join(stage, 'consumer.mts');
+ await writeFile(
+ source,
+ entries
+ .map((name, index) => {
+ const specifier = name === '.' ? pkg.name : `${pkg.name}/${name.slice(2)}`;
+ return `import * as E${index} from ${JSON.stringify(specifier)}; void E${index};`;
+ })
+ .join('\n'),
+ );
+ execFileSync(
+ 'node',
+ [
+ fileURLToPath(new URL('../node_modules/typescript/bin/tsc', import.meta.url)),
+ '--ignoreConfig',
+ '--noEmit',
+ '--strict',
+ '--module',
+ 'NodeNext',
+ '--target',
+ 'ES2022',
+ '--types',
+ 'node',
+ '--typeRoots',
+ fileURLToPath(new URL('../node_modules/@types', import.meta.url)),
+ source,
+ ],
+ { encoding: 'utf8', windowsHide: true },
+ );
+ return { package: pkg.name, entries: entries.length, status: 'passed' };
+ } finally {
+ await rm(stage, { recursive: true, force: true });
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ try {
+ const [runtime, option, ...extra] = process.argv.slice(2);
+ if (!runtime || (option && option !== '--with-agent-peers') || extra.length)
+ throw new Error('Pass the installed package directory and optional --with-agent-peers.');
+ console.log(
+ JSON.stringify(
+ await smokeSdkTypes(resolve(runtime), {
+ includeAgentPeers: option === '--with-agent-peers',
+ }),
+ ),
+ );
+ } catch (error) {
+ console.error(error.stdout || error.message);
+ process.exitCode = 1;
+ }
+}
diff --git a/scripts/smoke-sdk-types.test.mjs b/scripts/smoke-sdk-types.test.mjs
new file mode 100644
index 00000000..7c141261
--- /dev/null
+++ b/scripts/smoke-sdk-types.test.mjs
@@ -0,0 +1,60 @@
+import { expect, test } from 'bun:test';
+import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, sep } from 'node:path';
+import { smokeSdkTypes } from './smoke-sdk-types.mjs';
+
+async function fixture(run) {
+ const temporary = await realpath(tmpdir());
+ const root = await realpath(await mkdtemp(join(temporary, 'kiln-sdk-types-')));
+ if (!root.startsWith(temporary + sep)) throw new Error('Unsafe fixture path');
+ try {
+ await mkdir(join(root, 'lib'));
+ const exports = {};
+ for (const [name, file] of [
+ ['.', 'core'],
+ ['./arena', 'arena'],
+ ['./agent', 'agent'],
+ ['./composer/agent', 'composer'],
+ ]) {
+ exports[name] = { types: `./lib/${file}.d.ts`, import: `./lib/${file}.js` };
+ await writeFile(join(root, `lib/${file}.d.ts`), 'export declare const present: boolean;\n');
+ }
+ await writeFile(
+ join(root, 'package.json'),
+ JSON.stringify({ name: '@instruktlabs/kiln', type: 'module', exports }),
+ );
+ await run(root);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+test('core declarations include arena without requiring optional agent declarations', async () => {
+ await fixture(async (root) => {
+ await writeFile(
+ join(root, 'lib/agent.d.ts'),
+ "export { Missing } from 'missing-optional-peer';\n",
+ );
+ expect(await smokeSdkTypes(root)).toMatchObject({ entries: 2, status: 'passed' });
+ await writeFile(
+ join(root, 'lib/arena.d.ts'),
+ "export { Missing } from 'missing-ranking-type';\n",
+ );
+ await expect(smokeSdkTypes(root)).rejects.toThrow();
+ });
+});
+
+test('full declaration qualification cannot silently skip optional entrypoints', async () => {
+ await fixture(async (root) => {
+ expect(await smokeSdkTypes(root, { includeAgentPeers: true })).toMatchObject({
+ entries: 4,
+ status: 'passed',
+ });
+ await writeFile(
+ join(root, 'lib/composer.d.ts'),
+ "export { Missing } from 'missing-optional-peer';\n",
+ );
+ await expect(smokeSdkTypes(root, { includeAgentPeers: true })).rejects.toThrow();
+ });
+});
diff --git a/scripts/smoke-sdk.mjs b/scripts/smoke-sdk.mjs
new file mode 100644
index 00000000..b257b615
--- /dev/null
+++ b/scripts/smoke-sdk.mjs
@@ -0,0 +1,31 @@
+#!/usr/bin/env node
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+
+const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
+const sdk = await import(pkg.name);
+assert.equal(typeof sdk.renderGLB, 'function');
+assert.equal(typeof sdk.validateKilnCode, 'function');
+assert.equal(typeof sdk.createDiscovery, 'function');
+const imports = [];
+for (const name of Object.keys(pkg.exports)) {
+ await import(name === '.' ? pkg.name : `${pkg.name}/${name.slice(2)}`);
+ imports.push(name);
+}
+const code =
+ 'function build() { return new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({color: 0x888888})); }';
+const result = await sdk.renderGLB(code);
+assert.equal(result.glb.subarray(0, 4).toString('utf8'), 'glTF');
+const evaluator = await import(`${pkg.name}/evaluator`);
+const workerResult = await evaluator.renderGLBViaSubprocess(code);
+assert.equal(workerResult.glb.subarray(0, 4).toString('utf8'), 'glTF');
+assert.equal(sdk.engineIdentity().installUrl, new URL('../', import.meta.url).href);
+console.log(
+ JSON.stringify({
+ node: process.version,
+ package: pkg.name,
+ imports,
+ renderBytes: result.glb.length,
+ workerRenderBytes: workerResult.glb.length,
+ }),
+);
diff --git a/scripts/tier2-dogfood.mjs b/scripts/tier2-dogfood.mjs
index 92ac0fe2..c2a609d0 100644
--- a/scripts/tier2-dogfood.mjs
+++ b/scripts/tier2-dogfood.mjs
@@ -23,7 +23,7 @@ import {
} from './dogfood-gallery.mjs';
import { parseDuration, quoteArg, resolveBin } from './harness.mjs';
-export const PUBLIC_REPOSITORY = 'https://github.com/matthew-kissinger/kiln';
+export const PUBLIC_REPOSITORY = 'https://github.com/instruktlabs/kiln';
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const SUPPORTED_HARNESSES = ['agy', 'claude', 'codex', 'hermes', 'opencode'];
const ARTIFACT_EXCLUDED_SEGMENTS = new Set([
diff --git a/scripts/tier2-dogfood.test.mjs b/scripts/tier2-dogfood.test.mjs
index d75d433c..ea8a65a6 100644
--- a/scripts/tier2-dogfood.test.mjs
+++ b/scripts/tier2-dogfood.test.mjs
@@ -52,7 +52,7 @@ describe('Tier 2 blind dogfood driver', () => {
test('the prompt contains only the public repository and outcome-shaped asset goal', () => {
const prompt = composeBlindPrompt('a tide-powered cliffside signal station');
- expect(prompt).toContain('https://github.com/matthew-kissinger/kiln');
+ expect(prompt).toContain('https://github.com/instruktlabs/kiln');
expect(prompt).toContain('a tide-powered cliffside signal station');
expect(prompt).toContain('launch your own headless coding agent');
expect(prompt).toContain('inside your current run directory');
diff --git a/scripts/verify-package-receipt.mjs b/scripts/verify-package-receipt.mjs
index 83d9e927..dfe8830a 100644
--- a/scripts/verify-package-receipt.mjs
+++ b/scripts/verify-package-receipt.mjs
@@ -23,6 +23,13 @@ import { fileURLToPath } from 'node:url';
/** Checks the smoke run must report, named individually so a silent drop is a failure. */
const REQUIRED_CHECKS = [
+ 'installed-consumer-documents',
+ 'plain-node-sdk-exports',
+ 'sdk-subprocess-render',
+ 'compiled-evaluator-worker',
+ 'discovery-stability-labels',
+ 'local-plugin-bundle',
+ 'npm-mcp-entry',
'packaged-node-worker',
'community-exporter-textured-subprocess',
'source-reference-edit-images',
@@ -50,6 +57,7 @@ export function receiptProblems(receipt, { platform, arch, manifest, toolchain,
mustBe(receipt.node, `v${node ?? toolchain.node}`, 'node');
mustBe(receipt.npm, npm ?? toolchain.npm, 'npm');
mustBe(receipt.engineVersion, manifest.version, 'engineVersion');
+ mustBe(receipt.engineName, manifest.name, 'engineName');
for (const check of REQUIRED_CHECKS) {
if (!receipt.checks?.includes(check)) problems.push(`missing check: ${check}`);
diff --git a/scripts/verify-package-receipt.test.mjs b/scripts/verify-package-receipt.test.mjs
index b0039e83..e92e4dae 100644
--- a/scripts/verify-package-receipt.test.mjs
+++ b/scripts/verify-package-receipt.test.mjs
@@ -6,6 +6,7 @@ import { join } from 'node:path';
import { receiptProblems, verifyReceipt } from './verify-package-receipt.mjs';
const manifest = {
+ name: '@instruktlabs/kiln',
version: '0.7.0',
engines: { node: '^20.15.0 || >=22.2.0' },
};
@@ -19,9 +20,17 @@ const good = () => ({
node: 'v22.23.2',
npm: '12.0.2',
engineVersion: '0.7.0',
+ engineName: '@instruktlabs/kiln',
tarballSha256: 'unchecked-here',
tarball: '/nonexistent.tgz',
checks: [
+ 'installed-consumer-documents',
+ 'plain-node-sdk-exports',
+ 'sdk-subprocess-render',
+ 'compiled-evaluator-worker',
+ 'discovery-stability-labels',
+ 'local-plugin-bundle',
+ 'npm-mcp-entry',
'packaged-node-worker',
'community-exporter-textured-subprocess',
'source-reference-edit-images',
@@ -57,6 +66,7 @@ describe('package receipt verification', () => {
['node', { node: 'v22.22.0' }, 'node'],
['npm', { npm: '11.0.0' }, 'npm'],
['engineVersion', { engineVersion: '0.6.0' }, 'engineVersion'],
+ ['engineName', { engineName: '@kiln/engine' }, 'engineName'],
])('a receipt disagreeing about %s is rejected', (_label, patch, named) => {
const problems = receiptProblems({ ...good(), ...patch }, target);
expect(problems).toHaveLength(1);
@@ -70,7 +80,21 @@ describe('package receipt verification', () => {
});
test('a receipt with no checks at all reports every one of them', () => {
- expect(receiptProblems({ ...good(), checks: undefined }, target)).toHaveLength(5);
+ expect(receiptProblems({ ...good(), checks: undefined }, target)).toHaveLength(12);
+ });
+
+ test.each([
+ 'installed-consumer-documents',
+ 'plain-node-sdk-exports',
+ 'sdk-subprocess-render',
+ 'compiled-evaluator-worker',
+ 'discovery-stability-labels',
+ 'local-plugin-bundle',
+ 'npm-mcp-entry',
+ ])('cannot claim v1 package qualification without %s', (check) => {
+ const receipt = good();
+ receipt.checks = receipt.checks.filter((item) => item !== check);
+ expect(receiptProblems(receipt, target)).toEqual([`missing check: ${check}`]);
});
test('a package missing candidate texture coverage is rejected', () => {
diff --git a/skills/kiln-author-asset/references/export-profiles.md b/skills/kiln-author-asset/references/export-profiles.md
index cbb2c928..2c1116aa 100644
--- a/skills/kiln-author-asset/references/export-profiles.md
+++ b/skills/kiln-author-asset/references/export-profiles.md
@@ -96,7 +96,7 @@ when the client cannot save them. No binary data is put into tool text.
## TypeScript library
```ts
-import { exportAssetGlb } from '@kiln/engine/asset-export';
+import { exportAssetGlb } from '@instruktlabs/kiln/asset-export';
const record = await library.read('project', assetId, revisionId);
const output = await exportAssetGlb(record, {
@@ -212,5 +212,5 @@ of exporter backend qualification and optional geometry/texture compression.
5. Report the files, measured sizes, checks performed and remaining limits. A smaller
GLB does not establish lower draw calls, texture memory or higher frame rate.
-[Qualification results and repeatable local dogfood](https://github.com/matthew-kissinger/kiln/blob/main/docs/evaluation/export-profiles.md)
+[Qualification results and repeatable local dogfood](https://github.com/instruktlabs/kiln/blob/main/docs/evaluation/export-profiles.md)
cover generated source, CLI/MCP/HTTP delivery, native playback and a full Jaeger asset.
diff --git a/skills/kiln-compose-scene/references/composition-api.md b/skills/kiln-compose-scene/references/composition-api.md
index 0da8e00a..6de569aa 100644
--- a/skills/kiln-compose-scene/references/composition-api.md
+++ b/skills/kiln-compose-scene/references/composition-api.md
@@ -1,6 +1,6 @@
# Composition API notes
-Use these through the destination project's TypeScript toolchain. `inspectGlbIntegration` and `composeSceneGLB` are exported from `@kiln/engine/render`; overlap helpers are exported from `@kiln/engine/composer`. Generated Kiln source itself still has no imports.
+Use these through the destination project's TypeScript toolchain. `inspectGlbIntegration` and `composeSceneGLB` are exported from `@instruktlabs/kiln/render`; overlap helpers are exported from `@instruktlabs/kiln/composer`. Generated Kiln source itself still has no imports.
```ts
const composed = await composeSceneGLB([
diff --git a/skills/kiln-qa-asset/references/engine-handoff.md b/skills/kiln-qa-asset/references/engine-handoff.md
index 5d812101..73660f58 100644
--- a/skills/kiln-qa-asset/references/engine-handoff.md
+++ b/skills/kiln-qa-asset/references/engine-handoff.md
@@ -65,7 +65,7 @@ try {
`--render gpu` requires a working GPU renderer and fails if unavailable; it does not accept
a CPU fallback as material evidence. See Kiln's
-[GPU setup](https://github.com/matthew-kissinger/kiln/blob/main/docs/rendering.md#running-the-gpu-renderer).
+[GPU setup](https://github.com/instruktlabs/kiln/blob/main/docs/rendering.md#running-the-gpu-renderer).
In a repository clone, use `node dist/cli.mjs` instead of `node kiln.mjs`, after
`bun install --frozen-lockfile` and `bun run build:runtime`. For an installed distribution,
use the CLI launcher you already use, from a distribution containing this feature.
diff --git a/skills/kiln-qa-asset/references/integration-checks.md b/skills/kiln-qa-asset/references/integration-checks.md
index d31b0dd9..8ed3f685 100644
--- a/skills/kiln-qa-asset/references/integration-checks.md
+++ b/skills/kiln-qa-asset/references/integration-checks.md
@@ -2,7 +2,7 @@
These library APIs run in the destination project's TypeScript toolchain, not inside generated `.kiln.js` source. Use the project's installed Kiln package; do not copy engine implementation into the asset workspace.
-`inspectGlbIntegration(bytes)` from `@kiln/engine/render` reads the actual GLB and returns an integration manifest or `undefined` when no usable scene bounds exist. Check that result before using bounds, axes, ground correction, structural findings, or artifact hash.
+`inspectGlbIntegration(bytes)` from `@instruktlabs/kiln/render` reads the actual GLB and returns an integration manifest or `undefined` when no usable scene bounds exist. Check that result before using bounds, axes, ground correction, structural findings, or artifact hash.
Kiln authors metres, +X forward, +Y up, +Z right. Confirm importer conversion in the destination. Ground correction must be applied in the frame it describes, especially under rotated/scaled parents. Bounds alone cannot prove that feet, wheels, or collision geometry make the intended contact.
diff --git a/skills/kiln-setup-workspace/SKILL.md b/skills/kiln-setup-workspace/SKILL.md
index d675789f..2f0aef1c 100644
--- a/skills/kiln-setup-workspace/SKILL.md
+++ b/skills/kiln-setup-workspace/SKILL.md
@@ -8,7 +8,7 @@ metadata:
# Set up a workspace for asset authoring
-This repository is the engine. Asset authoring happens in a separate workspace, and the two are different tasks with different tools. Establish which one is being asked before running anything.
+Kiln's engine installation and its asset workspaces serve different tasks. Establish whether the user wants asset authoring or engine development before running anything.
Authoring an asset needs a workspace. Changing the engine's own behaviour does not; read `AGENTS.md` at the repository root instead and stay in the checkout.
@@ -18,13 +18,15 @@ Do not author assets inside the engine checkout. The authoring skills assume a w
## Create the workspace
+When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `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.
```bash
node scripts/create-workspace.mjs /absolute/empty-workspace --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. Ask the user which harness they use rather than assuming; the choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+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.
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.
diff --git a/skills/kiln-setup-workspace/references/plugin-install.md b/skills/kiln-setup-workspace/references/plugin-install.md
new file mode 100644
index 00000000..09df1184
--- /dev/null
+++ b/skills/kiln-setup-workspace/references/plugin-install.md
@@ -0,0 +1,66 @@
+# Local plugin setup
+
+The local `kiln-engine` plugin installs Kiln's exact pinned npm version and creates
+an asset workspace. It carries setup guidance and a small installer; the engine,
+source stores and authored assets live outside the plugin cache. It needs a
+supported Node.js installation with npm, network access for first installation,
+and no separate model API key.
+
+Resolve the plugin root from this installed skill's absolute path: it is two
+directories above `skills/kiln-setup-workspace`. Confirm `runtime.json` and
+`scripts/setup-workspace.mjs` exist there. Do not assume plugin path variables are
+available in an ordinary shell, and do not substitute an engine checkout.
+
+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:
+
+```sh
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --harness codex
+```
+
+The installer verifies the package name and exact version from `runtime.json`.
+It uses npm with lifecycle scripts disabled and optional dependencies included.
+The versioned engine stays under `%LOCALAPPDATA%/InstruktLabs/Kiln` on Windows,
+or `$XDG_DATA_HOME/instruktlabs/kiln` on other systems, falling back to
+`~/.local/share/instruktlabs/kiln`. `--data-dir` selects another persistent directory.
+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
+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.
+
+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
+registered twice. An old global plugin/server named `kiln` is a separate
+installation: explain the conflict and surface its removal or disabling before
+continuing; do not silently redirect stores or edit global configuration.
+
+For an existing managed workspace, stop its harness session and run the new
+plugin's helper with `--check`, then `--upgrade` when an update is intended:
+
+```sh
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --check
+node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --upgrade
+```
+
+Check is read-only and reports a missing pinned engine without installing it.
+Upgrade installs that version when needed, then delegates to Kiln's managed
+upgrade. It preserves sources and saved assets and refuses conflicting edits to
+managed files. Resolve those conflicts explicitly rather than overwriting them.
+Use the same `--data-dir` if setup used a custom location. `--repair` corrects
+relocated paths without updating copied skills. Restart the harness afterward.
+
+For release qualification only, `--archive /absolute/candidate.tgz` installs a
+reviewed local archive with the same required identity. Different archive bytes
+at the same version need a separate data directory. An unpublished development
+plugin is not a working registry release; use its reviewed development archive.
+
+If installation fails, report the error. An unknown existing runtime is never
+replaced automatically. A setup lock may belong to another running installer;
+verify that process has stopped before removing a stale lock. If npm cannot be
+located, fix the Node/npm installation or pass `--npm-cli` with its actual
+`npm-cli.js` path. Never request registry credentials for this public package.
diff --git a/src/__tests__/discovery.test.ts b/src/__tests__/discovery.test.ts
index 3c9f16cc..94d6e2e7 100644
--- a/src/__tests__/discovery.test.ts
+++ b/src/__tests__/discovery.test.ts
@@ -9,6 +9,19 @@ const discovery = () =>
type Result = DiscoveryResponse;
describe('progressive capability discovery', () => {
+ it('shows stability in the compact text used by both agent transports', async () => {
+ for (const tools of [createKilnNativeToolRegistry({}, {}), createKilnProgramToolRegistry()]) {
+ const tool = tools.find((entry) => entry.name === 'kiln_discover')!;
+ for (const [id, stability] of [
+ ['operation:boxGeo', 'stable'],
+ ['operation:implicitSurface', 'experimental'],
+ ['recipe:steerable-wheel-v1', 'experimental'],
+ ]) {
+ const output = await tool.run({ query: id, limit: 1 });
+ expect(tool.text!(output)).toContain(`${id} [${stability}]`);
+ }
+ }
+ });
it('reports each selected exporter against actual exported vertex attributes', async () => {
const source = `function build(){const root=createRoot('Attributes');const g=boxGeo(1,1,1);g.setAttribute('color',new THREE.Float32BufferAttribute(new Array(g.getAttribute('position').count).fill([1,0,0]).flat(),3));for(const key of ['uv1','uv2','uv3'])g.setAttribute(key,g.getAttribute('uv').clone());createPart('Body',g,new THREE.MeshStandardMaterial({vertexColors:true}),{parent:root});return root;}`;
for (const exporter of ['legacy', 'three'] as const) {
diff --git a/src/__tests__/installed-runtime-identity.test.ts b/src/__tests__/installed-runtime-identity.test.ts
index 989061b9..91453282 100644
--- a/src/__tests__/installed-runtime-identity.test.ts
+++ b/src/__tests__/installed-runtime-identity.test.ts
@@ -16,7 +16,7 @@ async function fixture(root: string) {
await writeFile(
join(root, 'package.json'),
JSON.stringify({
- name: '@kiln/engine',
+ name: '@instruktlabs/kiln',
version: '1.0.0',
dependencies: { 'geometry-runtime': '^1' },
}),
@@ -195,7 +195,7 @@ it('keeps engine-owned generation peers outside the worker closure', async () =>
await writeFile(
join(root, 'package.json'),
JSON.stringify({
- name: '@kiln/engine',
+ name: '@instruktlabs/kiln',
version: '1.0.0',
dependencies: { 'geometry-runtime': '^1' },
peerDependencies: { 'kiln-fixture-generation': '^1' },
diff --git a/src/__tests__/mcp-startup.test.ts b/src/__tests__/mcp-startup.test.ts
index 83fdae9a..8c917957 100644
--- a/src/__tests__/mcp-startup.test.ts
+++ b/src/__tests__/mcp-startup.test.ts
@@ -17,7 +17,7 @@
* arrive with no engine bundle on disk at all.
*/
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
-import { copyFile, mkdir, mkdtemp, readFile, rm } from 'node:fs/promises';
+import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import {
@@ -69,6 +69,36 @@ afterAll(async () => {
});
describe('contract rule 2: the first answers come before the engine', () => {
+ it('does not warm the engine after a tool-list-only client disconnects', async () => {
+ const directory = join(root, 'closed-before-warmup');
+ await mkdir(directory);
+ const bundle = join(directory, 'mcp-server.mjs');
+ await copyFile(SERVER_BUNDLE, bundle);
+ // A speculative import must not outlive its client. An engine with a live
+ // handle makes that mistake observable instead of depending on disk speed.
+ await writeFile(
+ join(directory, 'mcp-engine.mjs'),
+ `console.error('unexpected-engine-warmup');
+setInterval(() => {}, 1000);
+export function createPackagedKilnHost() { throw new Error('unused engine'); }
+`,
+ );
+ const server = await start({ bundle, cwd: directory });
+ expect((await legacyInit(server)).error).toBeUndefined();
+ server.notify('notifications/initialized');
+ expect((await server.request('tools/list', {})).error).toBeUndefined();
+ const timer = setTimeout(() => server.kill(), 2000);
+ try {
+ const closed = await server.close();
+ expect(server.stderr()).not.toContain('unexpected-engine-warmup');
+ expect(closed.code).toBe(0);
+ expect(closed.signal).toBeNull();
+ } finally {
+ clearTimeout(timer);
+ server.kill();
+ }
+ });
+
it('the entry bundle imports only the protocol library and Node built-ins', async () => {
const source = await readFile(SERVER_BUNDLE, 'utf8');
expect(source.length).toBeLessThan(MAX_ENTRY_BYTES);
diff --git a/src/__tests__/package-contents.test.ts b/src/__tests__/package-contents.test.ts
index 0a670850..0479b462 100644
--- a/src/__tests__/package-contents.test.ts
+++ b/src/__tests__/package-contents.test.ts
@@ -4,20 +4,31 @@ import { resolve } from 'node:path';
it('declares Node commands and the files needed by an installed workspace', async () => {
const pkg = JSON.parse(await readFile(resolve(import.meta.dir, '../../package.json'), 'utf8'));
- expect(pkg.private).toBe(true);
+ expect(pkg.name).toBe('@instruktlabs/kiln');
+ expect(pkg.private).not.toBe(true);
+ expect(pkg.publishConfig).toEqual({ access: 'public', provenance: true });
+ expect(pkg.repository.url).toBe('git+https://github.com/instruktlabs/kiln.git');
+ expect(pkg.bugs.url).toBe('https://github.com/instruktlabs/kiln/issues');
expect(pkg.bin.kiln).toBe('./dist/cli.mjs');
expect(pkg.bin['kiln-init']).toBe('./scripts/create-workspace.mjs');
+ expect(pkg.bin['kiln-mcp']).toBe('./dist/mcp-server.mjs');
for (const path of [
'dist/*.mjs',
'scripts/create-workspace.mjs',
'skills/',
- 'docs/',
+ 'docs/install.md',
+ 'docs/sdk.md',
'src/**/*.mjs',
'plugin.json',
'.claude-plugin/',
+ '.agents/plugins/',
+ 'plugins/kiln-engine/',
]) {
expect(pkg.files).toContain(path);
}
+ expect(pkg.files).not.toContain('docs/');
+ for (const path of pkg.files as string[])
+ expect(path).not.toMatch(/^docs\/(?:plans|reviews|evaluation)(?:\/|$)/);
for (const [name, file] of Object.entries({
'./geometry': './src/geometry.ts',
'./deform': './src/deform.ts',
@@ -28,7 +39,11 @@ it('declares Node commands and the files needed by an installed workspace', asyn
'./cache': './src/build-cache.ts',
'./cache/node': './src/build-cache-node.ts',
})) {
- expect(pkg.exports[name]).toBe(file);
+ const compiled = file.replace('./src/', './lib/').replace(/\.ts$/, '.js');
+ expect(pkg.exports[name]).toEqual({
+ types: compiled.replace(/\.js$/, '.d.ts'),
+ import: compiled,
+ });
expect(
(await readFile(resolve(import.meta.dir, '../..', file), 'utf8')).length,
).toBeGreaterThan(0);
@@ -45,7 +60,7 @@ it('advertises one version everywhere a client or installer can read it', async
const read = async (file: string) =>
JSON.parse(await readFile(resolve(import.meta.dir, '../..', file), 'utf8')).version;
const engine = await read('package.json');
- expect(engine).toMatch(/^\d+\.\d+\.\d+$/);
+ expect(engine).toMatch(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);
for (const manifest of [
'plugin.json',
'.claude-plugin/plugin.json',
diff --git a/src/__tests__/packaged-save-provenance.test.ts b/src/__tests__/packaged-save-provenance.test.ts
index 75f13a80..c349f2d7 100644
--- a/src/__tests__/packaged-save-provenance.test.ts
+++ b/src/__tests__/packaged-save-provenance.test.ts
@@ -22,7 +22,7 @@ beforeAll(async () => {
await writeFile(
join(root, 'package.json'),
JSON.stringify({
- name: '@kiln/engine',
+ name: '@instruktlabs/kiln',
version: pkg.version,
dependencies: { ...pkg.dependencies, 'kiln-provenance-fixture': '1' },
type: 'module',
diff --git a/src/__tests__/persistent-local-cache.test.ts b/src/__tests__/persistent-local-cache.test.ts
index 51fdb5c8..7c999baa 100644
--- a/src/__tests__/persistent-local-cache.test.ts
+++ b/src/__tests__/persistent-local-cache.test.ts
@@ -15,7 +15,7 @@ it('reuses a packaged Node build across fresh CLI host instances and invalidates
await writeFile(
join(root, 'package.json'),
JSON.stringify({
- name: '@kiln/engine',
+ name: '@instruktlabs/kiln',
version: pkg.version,
dependencies: pkg.dependencies,
type: 'module',
diff --git a/src/__tests__/qa-public-surface.test.ts b/src/__tests__/qa-public-surface.test.ts
index acd85205..b6c4de05 100644
--- a/src/__tests__/qa-public-surface.test.ts
+++ b/src/__tests__/qa-public-surface.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from 'bun:test';
-import * as qa from '@kiln/engine/qa';
+import * as qa from '@instruktlabs/kiln/qa';
import { resolveRequirementsContext } from '../requirements-context';
import { BoxGeometry, Group, Mesh, MeshStandardMaterial } from 'three';
diff --git a/src/__tests__/runtime-build-identity.test.ts b/src/__tests__/runtime-build-identity.test.ts
index c0cfed1f..cf668c97 100644
--- a/src/__tests__/runtime-build-identity.test.ts
+++ b/src/__tests__/runtime-build-identity.test.ts
@@ -12,7 +12,11 @@ it('derives reproducible runtime identity from source and lockfile rather than t
await writeFile(join(root, 'render-service/src/server.mjs'), 'export const protocol = 1;');
await writeFile(
join(root, 'package.json'),
- JSON.stringify({ name: '@kiln/engine', version: '1.0.0', packageManager: '[email protected]' }),
+ JSON.stringify({
+ name: '@instruktlabs/kiln',
+ version: '1.0.0',
+ packageManager: '[email protected]',
+ }),
);
await writeFile(join(root, 'bun.lock'), 'dependency-lock');
await writeFile(join(root, 'src/a.ts'), 'export const n = 1;');
diff --git a/src/__tests__/workspace-bootstrap.test.ts b/src/__tests__/workspace-bootstrap.test.ts
index 2d7df2a9..b297e841 100644
--- a/src/__tests__/workspace-bootstrap.test.ts
+++ b/src/__tests__/workspace-bootstrap.test.ts
@@ -119,7 +119,10 @@ it('refuses an otherwise loadable installation without the packaged worker befor
try {
const runtime = join(root, 'runtime');
await mkdir(join(runtime, 'dist'), { recursive: true });
- await writeFile(join(runtime, 'package.json'), '{"name":"@kiln/engine","version":"1.0.0"}');
+ await writeFile(
+ join(runtime, 'package.json'),
+ '{"name":"@instruktlabs/kiln","version":"1.0.0"}',
+ );
await writeFile(join(runtime, 'dist/cli.mjs'), 'export function main() {}');
await writeFile(join(runtime, 'dist/mcp-server.mjs'), '');
await writeFile(join(runtime, 'dist/mcp-engine.mjs'), '');
diff --git a/src/__tests__/workspace-upgrade.test.ts b/src/__tests__/workspace-upgrade.test.ts
index 184d95d7..8edea473 100644
--- a/src/__tests__/workspace-upgrade.test.ts
+++ b/src/__tests__/workspace-upgrade.test.ts
@@ -49,7 +49,7 @@ const invoke = (root: string, runtime: string, options = {}, node = 'node', harn
async function fixture(runtime: string, revision: string) {
await put(
join(runtime, 'package.json'),
- JSON.stringify({ name: '@kiln/engine', version: '1.0.0' }),
+ JSON.stringify({ name: '@instruktlabs/kiln', version: '1.0.0' }),
);
const entries: Record<string, unknown> = {};
for (const [key, file] of [
diff --git a/src/agent/index.ts b/src/agent/index.ts
index e303d983..dc40b292 100644
--- a/src/agent/index.ts
+++ b/src/agent/index.ts
@@ -1,9 +1,9 @@
/**
- * `@kiln/engine/agent` — the agnostic, tool-driven Kiln codegen foundation
+ * `@instruktlabs/kiln/agent` — the agnostic, tool-driven Kiln codegen foundation
* (validated in the pixel-forge kiln-bench harness, folded in 2026-06).
*
* Isolated on its own subpath export so the `@strands-agents/sdk` dependency
- * does not leak into the rest of the engine — import from `@kiln/engine/agent`
+ * does not leak into the rest of the engine — import from `@instruktlabs/kiln/agent`
* only when you want the agent loop.
*
* - {@link runKilnAgent} — drive any Strands Model through the kiln tool loop
diff --git a/src/agent/native-surface.test.ts b/src/agent/native-surface.test.ts
index 0a7d90b0..2dc1d33f 100644
--- a/src/agent/native-surface.test.ts
+++ b/src/agent/native-surface.test.ts
@@ -3,7 +3,7 @@ import { existsSync, readFileSync } from 'node:fs';
import * as skin from './tools';
import * as agent from './index';
import { createKilnNativeToolRegistry } from '../tools/registry';
-import * as publicTools from '@kiln/engine/tools';
+import * as publicTools from '@instruktlabs/kiln/tools';
test('native discovery uses the registry presentation once, preserving long structured detail', async () => {
const def = createKilnNativeToolRegistry({}, {}).find((t) => t.name === 'kiln_discover')!;
@@ -37,7 +37,7 @@ test('the retired category-driven prompt module has no public or source fallback
const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
expect(Object.hasOwn(pkg.exports, './prompt')).toBe(false);
expect(existsSync(new URL('../prompt.ts', import.meta.url))).toBe(false);
- expect(() => import.meta.resolve('@kiln/engine/prompt')).toThrow();
+ expect(() => import.meta.resolve('@instruktlabs/kiln/prompt')).toThrow();
expect(typeof agent.runKilnAgent).toBe('function');
});
diff --git a/src/agent/skill-resources.ts b/src/agent/skill-resources.ts
index 1193bbeb..0fd8e668 100644
--- a/src/agent/skill-resources.ts
+++ b/src/agent/skill-resources.ts
@@ -2,14 +2,8 @@ import { lstat, open, readdir, realpath, stat } from 'node:fs/promises';
import { basename, dirname, extname, join, relative, resolve, sep } from 'node:path';
import { createHash } from 'node:crypto';
import { Skill } from '@strands-agents/sdk/vended-plugins/skills';
-
-export interface SkillResourceRequest {
- skill: string;
- path?: string;
- offset: number;
- limit: number;
-}
-export type SkillResourceReader = (input: SkillResourceRequest) => unknown;
+import type { SkillResourceReader } from '../tools/skill-resource';
+export type { SkillResourceReader, SkillResourceRequest } from '../tools/skill-resource';
const MAX_FILE_BYTES = 256 * 1024;
const MAX_TOTAL_BYTES = 1024 * 1024;
diff --git a/src/asset-cli.ts b/src/asset-cli.ts
index a808bb75..5e590a19 100644
--- a/src/asset-cli.ts
+++ b/src/asset-cli.ts
@@ -309,7 +309,7 @@ export async function assetMain(argv: readonly string[]): Promise<number> {
new FileWorkspace(localWorkspaceRoot()),
record,
);
- const code = new TextDecoder().decode(source);
+ const code = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(source);
const rendered = await context.evaluatorPort!.render(code, {
...renderOptions,
materialResources,
diff --git a/src/asset-rebuild-cli.test.ts b/src/asset-rebuild-cli.test.ts
index 81b90b16..0188710b 100644
--- a/src/asset-rebuild-cli.test.ts
+++ b/src/asset-rebuild-cli.test.ts
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { FileWorkspace } from './workspace-node';
import { FileAssetLibrary } from './assets-node';
+import { FileLiveReview } from './live-review-node';
import { createMaterialPresetDraft } from './material-presets';
import { createMaterialLibraryPayload, createMaterialRecordV1 } from './material-library-node';
import { materialLibraryPortableSpec } from './material-library';
@@ -35,7 +36,7 @@ test('CLI rebuild after project import uses exact saved source/options/materials
createMaterialPresetDraft('warm-brick', { ...preset, seed: 2 }),
);
await source.materials.import([old, newer]);
- const code = `const meta={name:'Brick cube'}; async function build(){const root=createRoot('Root');const material=await compilePortableMaterialSpecV2(${JSON.stringify(materialLibraryPortableSpec(old.manifest))});createPart('Body',boxGeo(1,1,1),material,{parent:root});return root;}`;
+ const code = `\ufeffconst meta={name:'Brick cube'}; async function build(){const root=createRoot('Root');const material=await compilePortableMaterialSpecV2(${JSON.stringify(materialLibraryPortableSpec(old.manifest))});createPart('Body',boxGeo(1,1,1),material,{parent:root});return root;}`;
const result = await renderGLBInProcess(code, {
gltfExporter: 'legacy',
optimize: 'off',
@@ -100,6 +101,7 @@ test('CLI rebuild after project import uses exact saved source/options/materials
KILN_COLLECTIONS: '',
KILN_EVALUATOR_MODE: 'in-process',
KILN_BUILD_CACHE: 'memory',
+ KILN_LIVE_REVIEW: 'on',
KILN_RENDER: 'cpu',
KILN_BAKE_INSTANCE: 'on',
KILN_BAKE_OPTIMIZE: 'full',
@@ -112,6 +114,14 @@ test('CLI rebuild after project import uses exact saved source/options/materials
expect(rebuilt.status, rebuilt.stderr).toBe(0);
expect(JSON.parse(rebuilt.stdout).matchesSavedArtifact).toBe(true);
expect(new Uint8Array(await readFile(output))).toEqual(Uint8Array.from(result.glb));
+ const liveReview = new FileLiveReview(target.root);
+ const operation = (await liveReview.snapshot()).operations.find(
+ (item) => item.tool === 'kiln_asset_rebuild',
+ );
+ expect(operation).toBeDefined();
+ expect(await liveReview.readFile(operation!.operationId, 'source.kiln.js')).toEqual(
+ new TextEncoder().encode(code),
+ );
expect(run().status).toBe(1);
expect(new Uint8Array(await readFile(output))).toEqual(Uint8Array.from(result.glb));
} finally {
diff --git a/src/asset-viewer.ts b/src/asset-viewer.ts
index 67eff5e1..46e9efc4 100644
--- a/src/asset-viewer.ts
+++ b/src/asset-viewer.ts
@@ -34,7 +34,7 @@ export async function startAssetViewer(
) {
const staticDirectory =
options.staticDirectory ??
- (import.meta.url.endsWith('.ts')
+ (!import.meta.url.endsWith('.mjs')
? join(dirname(fileURLToPath(import.meta.url)), '..', 'dist', 'viewer')
: join(dirname(fileURLToPath(import.meta.url)), 'viewer'));
const server = createServer(async (req, res) => {
diff --git a/src/assets-node.ts b/src/assets-node.ts
index 7b1f8ded..2b603749 100644
--- a/src/assets-node.ts
+++ b/src/assets-node.ts
@@ -1,17 +1,7 @@
/** Local durable collections; immutable revisions become visible by directory rename. */
import { createHash, randomUUID } from 'node:crypto';
import { readFileSync, type Dirent } from 'node:fs';
-import {
- link,
- lstat,
- mkdir,
- readFile,
- readdir,
- realpath,
- rename,
- rm,
- writeFile,
-} from 'node:fs/promises';
+import { link, lstat, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
import { homedir, platform } from 'node:os';
import { dirname, join, relative, resolve, sep, win32 } from 'node:path';
import { localWorkspaceRoot } from './workspace-location';
@@ -31,6 +21,9 @@ import {
import type { MaterialLibrary, MaterialRecordV1 } from './material-library';
import { FileMaterialLibrary, createMaterialLibraryPayload } from './material-library-node';
import { dependencyManifests, resolveSavedAssetMaterials } from './asset-materials-node';
+import { renameDirectoryAtomically } from './atomic-directory';
+
+export { resolveSavedAssetMaterials } from './asset-materials-node';
const digest = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
function assertMaterialAllocation(records: AssetRecord[]): void {
@@ -295,7 +288,7 @@ export class FileAssetLibrary implements AssetLibrary {
flag: 'wx',
});
try {
- await rename(stage, dest);
+ await renameDirectoryAtomically(stage, dest);
} catch (error) {
const existing = await this.read(collection, manifest.assetId, manifest.revisionId).catch(
() => undefined,
diff --git a/src/assets-tools.test.ts b/src/assets-tools.test.ts
index 19b0b444..b2336408 100644
--- a/src/assets-tools.test.ts
+++ b/src/assets-tools.test.ts
@@ -22,7 +22,7 @@ test('MCP saves an editable revision, exposes exact downloadable bytes, and rest
});
const programStore = new MemoryProgramStore();
const code =
- "const meta = { name: 'Box', category: 'prop' }; function build() { const root = createRoot('Box'); createPart('Body', boxGeo(1,1,1), gameMaterial(0x88aa66), {parent: root, position: [0,0.5,0]}); return root; }";
+ "\ufeffconst meta = { name: 'Box', category: 'prop' }; function build() { const root = createRoot('Box'); createPart('Body', boxGeo(1,1,1), gameMaterial(0x88aa66), {parent: root, position: [0,0.5,0]}); return root; }";
const programRef = await retainProgram(programStore, code);
const server = createKilnMcpServer(
{
diff --git a/src/atomic-directory.test.ts b/src/atomic-directory.test.ts
new file mode 100644
index 00000000..49c6079d
--- /dev/null
+++ b/src/atomic-directory.test.ts
@@ -0,0 +1,115 @@
+import { afterEach, expect, test } from 'bun:test';
+import { lstat, mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve, sep } from 'node:path';
+import { renameDirectoryAtomically } from './atomic-directory';
+
+const roots: string[] = [];
+afterEach(async () => {
+ for (const root of roots.splice(0)) {
+ if (!resolve(root).startsWith(resolve(tmpdir()) + sep)) throw new Error('Invalid test root');
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+async function fixture() {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-atomic-revision-'));
+ roots.push(root);
+ const stage = join(root, '.write-revision');
+ const destination = join(root, 'r_revision');
+ await mkdir(stage);
+ await writeFile(join(stage, 'source.kiln.js'), 'complete revision');
+ return { stage, destination };
+}
+
+test('transient Windows rename denial preserves the staged revision until atomic publication', async () => {
+ const { stage, destination } = await fixture();
+ const denied = Object.assign(new Error('sharing violation'), { code: 'EPERM' });
+ const delays: number[] = [];
+ let attempts = 0;
+ await renameDirectoryAtomically(stage, destination, {
+ platform: 'win32',
+ renameOperation: async (from, to) => {
+ expect(await readFile(join(stage, 'source.kiln.js'), 'utf8')).toBe('complete revision');
+ if (++attempts < 3) throw denied;
+ await rename(from, to);
+ },
+ pause: async (milliseconds) => {
+ delays.push(milliseconds);
+ expect(await lstat(destination).catch(() => undefined)).toBeUndefined();
+ },
+ });
+ expect(attempts).toBe(3);
+ expect(delays).toEqual([20, 50]);
+ expect(await lstat(stage).catch(() => undefined)).toBeUndefined();
+ expect(await readFile(join(destination, 'source.kiln.js'), 'utf8')).toBe('complete revision');
+});
+
+test('persistent denial has a fixed retry budget and leaves cleanup to the caller', async () => {
+ const { stage, destination } = await fixture();
+ const denied = Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ let attempts = 0;
+ let waited = 0;
+ await expect(
+ renameDirectoryAtomically(stage, destination, {
+ platform: 'win32',
+ renameOperation: async () => {
+ attempts++;
+ throw denied;
+ },
+ pause: async (milliseconds) => {
+ waited += milliseconds;
+ },
+ }),
+ ).rejects.toBe(denied);
+ expect(attempts).toBe(6);
+ expect(waited).toBe(770);
+ expect(await readFile(join(stage, 'source.kiln.js'), 'utf8')).toBe('complete revision');
+});
+
+test('an existing destination is left intact and returns the original collision immediately', async () => {
+ const { stage, destination } = await fixture();
+ await mkdir(destination);
+ await writeFile(join(destination, 'source.kiln.js'), 'existing revision');
+ const collision = Object.assign(new Error('destination exists'), { code: 'EPERM' });
+ let attempts = 0;
+ await expect(
+ renameDirectoryAtomically(stage, destination, {
+ platform: 'win32',
+ renameOperation: async () => {
+ attempts++;
+ throw collision;
+ },
+ pause: async () => {
+ throw new Error('A collision must not wait');
+ },
+ }),
+ ).rejects.toBe(collision);
+ expect(attempts).toBe(1);
+ expect(await readFile(join(destination, 'source.kiln.js'), 'utf8')).toBe('existing revision');
+ expect(await readFile(join(stage, 'source.kiln.js'), 'utf8')).toBe('complete revision');
+});
+
+test.each([
+ ['linux', 'EPERM'],
+ ['darwin', 'EACCES'],
+ ['win32', 'ENOENT'],
+ ['win32', 'EXDEV'],
+] as const)('%s %s failures are not retried', async (platform, code) => {
+ const { stage, destination } = await fixture();
+ const error = Object.assign(new Error('failure'), { code });
+ let attempts = 0;
+ await expect(
+ renameDirectoryAtomically(stage, destination, {
+ platform,
+ renameOperation: async () => {
+ attempts++;
+ throw error;
+ },
+ pause: async () => {
+ throw new Error('Not retryable');
+ },
+ }),
+ ).rejects.toBe(error);
+ expect(attempts).toBe(1);
+});
diff --git a/src/atomic-directory.ts b/src/atomic-directory.ts
new file mode 100644
index 00000000..d10c0ad8
--- /dev/null
+++ b/src/atomic-directory.ts
@@ -0,0 +1,45 @@
+import { lstat, rename } from 'node:fs/promises';
+import { setTimeout as pause } from 'node:timers/promises';
+
+interface RenameControls {
+ platform?: NodeJS.Platform;
+ renameOperation?: typeof rename;
+ pause?: (milliseconds: number) => Promise<unknown>;
+}
+
+/** Publish a complete directory; bounded Windows retries retain the same atomic rename. */
+export async function renameDirectoryAtomically(
+ source: string,
+ destination: string,
+ controls: RenameControls = {},
+): Promise<void> {
+ const renameOperation = controls.renameOperation ?? rename;
+ const platform = controls.platform ?? process.platform;
+ const wait = controls.pause ?? pause;
+ const delays = [20, 50, 100, 200, 400];
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await renameOperation(source, destination);
+ return;
+ } catch (error) {
+ const delay = delays[attempt];
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
+ if (
+ platform !== 'win32' ||
+ delay === undefined ||
+ !['EPERM', 'EACCES', 'EBUSY'].includes(code ?? '')
+ )
+ throw error;
+ // A destination can be a legitimate concurrent/idempotent import. Leave
+ // that decision to the caller; never remove, replace or copy over it.
+ const absent = await lstat(destination).then(
+ () => false,
+ (statError: NodeJS.ErrnoException) => statError.code === 'ENOENT',
+ );
+ if (!absent) throw error;
+ // File scanners can briefly deny renaming a newly written directory.
+ // Persistent permission failures still surface after at most 770 ms.
+ await wait(delay);
+ }
+ }
+}
diff --git a/src/composer/agent/index.ts b/src/composer/agent/index.ts
index 255692de..635c02ac 100644
--- a/src/composer/agent/index.ts
+++ b/src/composer/agent/index.ts
@@ -1,7 +1,7 @@
/**
- * `@kiln/engine/composer/agent` — the Strands-driven scene-composition loop.
+ * `@instruktlabs/kiln/composer/agent` — the Strands-driven scene-composition loop.
*
- * The agent counterpart to the pure `@kiln/engine/composer` core: it exposes the
+ * The agent counterpart to the pure `@instruktlabs/kiln/composer` core: it exposes the
* `scene_*` tool surface over a `PlacementModel` and drives any Strands `Model`
* through it via {@link runKilnComposer}. Isolated on its own subpath so the
* `@strands-agents/sdk` dependency does not leak into the composer core (which is
diff --git a/src/composer/agent/run.ts b/src/composer/agent/run.ts
index cf78324c..e09bc76d 100644
--- a/src/composer/agent/run.ts
+++ b/src/composer/agent/run.ts
@@ -6,7 +6,7 @@
* renders it through the host `SceneRenderPort` to SEE the result, and finalizes.
* Reuses the asset-gen `MetricsCollector` (tool/step/usage + the runaway step cap)
* and `unifiedDiff` (the refine patch artifact). The `@strands-agents/sdk`
- * dependency lives ONLY here on `@kiln/engine/composer/agent` — the composer core
+ * dependency lives ONLY here on `@instruktlabs/kiln/composer/agent` — the composer core
* (model / dsl / overlap / layout / render-port) never imports it.
*
* Never throws: failures come back on `result.error` with whatever the sink
diff --git a/src/composer/index.ts b/src/composer/index.ts
index 733135cb..5d5c40a4 100644
--- a/src/composer/index.ts
+++ b/src/composer/index.ts
@@ -1,5 +1,5 @@
/**
- * `@kiln/engine/composer` — scene-composition primitives: overlap validation,
+ * `@instruktlabs/kiln/composer` — scene-composition primitives: overlap validation,
* a terrain-agnostic hierarchy-aware layout engine, and the ground seam they
* sit on. Pure and deterministic; the composer tool surface and agent build on
* top of these.
diff --git a/src/discovery/service.test.ts b/src/discovery/service.test.ts
index 876dbf95..107046d4 100644
--- a/src/discovery/service.test.ts
+++ b/src/discovery/service.test.ts
@@ -11,6 +11,37 @@ const index = {
const make = () =>
createDiscoveryService(listDiscoveryEntries(), index, async () => ({ host: 'test' }));
+test('compact search and overview retain stability for experimental helpers and recipes', async () => {
+ const run = make();
+ for (const entry of listDiscoveryEntries().filter(
+ (entry) => entry.stability === 'experimental',
+ )) {
+ const result = await run({ query: entry.id, limit: 1 });
+ expect(result.entries[0]?.id).toBe(entry.id);
+ expect(result.text).toContain(`${entry.id} [experimental]`);
+ for (const limitation of entry.limitations) expect(result.text).toContain(limitation);
+ }
+ const stable = await run({ query: 'boxGeo', limit: 1 });
+ expect(stable.text).toContain('operation:boxGeo [stable]');
+ let offset: number | null = 0;
+ while (offset !== null) {
+ const page = await run({ offset });
+ for (const entry of page.entries)
+ expect(page.text).toContain(`${entry.id} [${entry.stability}]`);
+ offset = page.nextOffset;
+ }
+});
+
+test('a deprecated entry is identified without silently removing it', async () => {
+ const catalog = listDiscoveryEntries().map((entry) =>
+ entry.name === 'arrayRadial' ? { ...entry, stability: 'deprecated' as const } : entry,
+ );
+ const run = createDiscoveryService(catalog, index, async () => ({}));
+ const result = await run({ query: 'repeat', limit: 1 });
+ expect(result.text).toContain('operation:arrayRadial [deprecated]');
+ expect(result.entries[0]?.stability).toBe('deprecated');
+});
+
test('search exposes execution mode and the exact-contract next step without full detail', async () => {
const run = make();
for (const [name, execution] of [
diff --git a/src/discovery/service.ts b/src/discovery/service.ts
index acac6e8d..3e2932ed 100644
--- a/src/discovery/service.ts
+++ b/src/discovery/service.ts
@@ -302,7 +302,7 @@ export function createDiscoveryService(
: []),
...page.map(
(entry) =>
- `${entry.id}${entry.execution ? ` (${entry.execution === 'async' ? 'async; await the result' : 'sync'})` : ''}: ${entry.summary}${entry.limitations.length ? ` Limits: ${entry.limitations.join(' ')}` : ''}${formatMatch(entry.match)}`,
+ `${entry.id} [${entry.stability}]${entry.execution ? ` (${entry.execution === 'async' ? 'async; await the result' : 'sync'})` : ''}: ${entry.summary}${entry.limitations.length ? ` Limits: ${entry.limitations.join(' ')}` : ''}${formatMatch(entry.match)}`,
),
...(input.query && !page.length
? [
diff --git a/src/engine-identity.ts b/src/engine-identity.ts
index cbeb5e27..a9c2fa6b 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 = '0.10.0';
+export const ENGINE_VERSION = '1.0.0-rc.1';
/**
* Where this engine was loaded from, as a `file://` URL of the package root.
diff --git a/src/evaluator/isolation.test.ts b/src/evaluator/isolation.test.ts
index 6ec81c1b..714ce302 100644
--- a/src/evaluator/isolation.test.ts
+++ b/src/evaluator/isolation.test.ts
@@ -18,11 +18,11 @@ const PATHS = new Set([
'/usr/bin/setpriv',
'/usr/bin/prlimit',
'/usr/local/bin/node',
- '/app/node_modules/@kiln/engine/src/evaluator/worker.ts',
+ '/app/node_modules/@instruktlabs/kiln/src/evaluator/worker.ts',
]);
function launch() {
- return isolatedEvaluatorLaunch('/app/node_modules/@kiln/engine/src/evaluator/worker.ts', {
+ return isolatedEvaluatorLaunch('/app/node_modules/@instruktlabs/kiln/src/evaluator/worker.ts', {
platform: 'linux',
pathExists: (path) => PATHS.has(path),
});
@@ -129,6 +129,9 @@ describe('isolated evaluator process contract', () => {
]);
expect(spec.args).not.toContain('--bounding-set=-all');
expect(spec.args).toContain('--unshare-all');
+ // --unshare-all implies --unshare-user-try, which does not satisfy
+ // Bubblewrap's --disable-userns precondition (observed with 0.12.0).
+ expect(spec.args).toContain('--unshare-user');
expect(spec.args).not.toContain('--share-net');
expect(spec.args).toContain('--disable-userns');
expect(spec.args).toContain('--cap-drop');
@@ -144,6 +147,21 @@ describe('isolated evaluator process contract', () => {
expect(spec.args).not.toContain('/etc');
});
+ 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, {
+ platform: 'linux',
+ pathExists: (path) => PATHS.has(path) || path === worker,
+ });
+ expect(spec.args.at(-1)).toBe(worker);
+ expect(spec.args).not.toContain('tsx');
+ expect(spec.args).not.toContain('--import');
+ expect(spec.args).toContain('--unshare-all');
+ expect(spec.args).toContain('--clearenv');
+ expect(spec.args).toContain('--cpu=65:65');
+ expect(spec.args).toContain('--max-old-space-size=512');
+ });
+
test('requires every Linux capability set to be present and empty', () => {
const emptyStatus = [
'Name:\tnode',
@@ -168,12 +186,12 @@ describe('isolated evaluator process contract', () => {
test('refuses non-Linux hosts, missing binaries, and workers outside installed dependencies', () => {
for (const invoke of [
() =>
- isolatedEvaluatorLaunch('/app/node_modules/@kiln/engine/src/evaluator/worker.ts', {
+ isolatedEvaluatorLaunch('/app/node_modules/@instruktlabs/kiln/src/evaluator/worker.ts', {
platform: 'win32',
pathExists: () => true,
}),
() =>
- isolatedEvaluatorLaunch('/app/node_modules/@kiln/engine/src/evaluator/worker.ts', {
+ isolatedEvaluatorLaunch('/app/node_modules/@instruktlabs/kiln/src/evaluator/worker.ts', {
platform: 'linux',
pathExists: () => false,
}),
diff --git a/src/evaluator/isolation.ts b/src/evaluator/isolation.ts
index 0bb42823..45457911 100644
--- a/src/evaluator/isolation.ts
+++ b/src/evaluator/isolation.ts
@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { posix } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { isolatedWorkerUrls } from './worker-urls';
import type { RenderGlbOptions, RenderResult } from '../render';
import {
EvaluatorSubprocessError,
@@ -137,7 +138,7 @@ function runtimeMounts(runtimeRoot: string, pathExists: (path: string) => boolea
}
/**
- * Build the exact Linux process boundary used by production AgentCore images.
+ * Build the Linux process boundary; each hosting environment must qualify it.
* The outer image runs as a non-root user. setpriv clears inheritable/ambient
* capabilities and locks no-new-privs before bubblewrap creates fresh user,
* PID, network, mount, IPC, UTS, and cgroup namespaces. bubblewrap drops the
@@ -166,6 +167,8 @@ function isolatedEvaluatorLaunchWithLoader(
const bwrapArgs = [
'--unshare-all',
+ // --unshare-all only tries a user namespace; --disable-userns requires it.
+ '--unshare-user',
'--die-with-parent',
'--new-session',
'--disable-userns',
@@ -232,7 +235,11 @@ export function isolatedEvaluatorLaunch(
workerPath: string,
host: IsolatedEvaluatorHost = {},
): EvaluatorProcessLaunch {
- return isolatedEvaluatorLaunchWithLoader(workerPath, host, 'tsx');
+ return isolatedEvaluatorLaunchWithLoader(
+ workerPath,
+ host,
+ /\.tsx?$/.test(workerPath) ? 'tsx' : 'module',
+ );
}
export async function renderGLBViaIsolatedEvaluator(
@@ -240,7 +247,7 @@ export async function renderGLBViaIsolatedEvaluator(
options: RenderGlbOptions = {},
controls: IsolatedEvaluatorControls = {},
): Promise<RenderResult> {
- const workerPath = fileURLToPath(new URL('./worker.ts', import.meta.url));
+ const workerPath = fileURLToPath(isolatedWorkerUrls(import.meta.url).worker);
const launch = isolatedEvaluatorLaunch(workerPath, controls.host);
const { host: _, ...processControls } = controls;
return renderGLBViaProcessLaunch(code, options, processControls, launch);
@@ -431,8 +438,9 @@ export async function assertIsolatedEvaluatorReady(
if (typeof process.getuid !== 'function' || process.getuid() === 0) {
throw new EvaluatorIsolationReadinessError('invariant-namespace');
}
- const transportPath = fileURLToPath(new URL('./transport-worker.mjs', import.meta.url));
- const probePath = fileURLToPath(new URL('./probe-worker.ts', import.meta.url));
+ const workers = isolatedWorkerUrls(import.meta.url);
+ const transportPath = fileURLToPath(workers.transport);
+ const probePath = fileURLToPath(workers.probe);
let transportLaunch: EvaluatorProcessLaunch;
let probeLaunch: EvaluatorProcessLaunch;
try {
diff --git a/src/evaluator/subprocess.ts b/src/evaluator/subprocess.ts
index 174f1045..3c00c12e 100644
--- a/src/evaluator/subprocess.ts
+++ b/src/evaluator/subprocess.ts
@@ -135,11 +135,12 @@ export async function renderGLBViaProcessLaunch(
}
const sourceModule = import.meta.url.endsWith('.ts');
+ const sdkModule = import.meta.url.endsWith('/subprocess.js');
const workerPath = fileURLToPath(
new URL(
process.versions.bun && sourceModule
? './worker.ts'
- : sourceModule
+ : sourceModule || sdkModule
? '../../dist/evaluator-worker.mjs'
: './evaluator-worker.mjs',
import.meta.url,
diff --git a/src/evaluator/worker-urls.test.ts b/src/evaluator/worker-urls.test.ts
new file mode 100644
index 00000000..922ebab4
--- /dev/null
+++ b/src/evaluator/worker-urls.test.ts
@@ -0,0 +1,20 @@
+import { expect, test } from 'bun:test';
+import { isolatedWorkerUrls } from './worker-urls';
+
+test.each([
+ ['src/evaluator/isolation.ts', 'src/evaluator', 'ts'],
+ ['lib/evaluator/isolation.js', 'lib/evaluator', 'js'],
+ ['dist/mcp-engine.mjs', 'lib/evaluator', 'js'],
+ ['dist/cli.mjs', 'lib/evaluator', 'js'],
+] as const)('%s resolves its complete worker set', (module, directory, extension) => {
+ const root = 'file:///app/node_modules/@instruktlabs/kiln/';
+ const urls = isolatedWorkerUrls(root + module);
+ expect(urls.worker.href).toBe(`${root}${directory}/worker.${extension}`);
+ expect(urls.probe.href).toBe(`${root}${directory}/probe-worker.${extension}`);
+ expect(urls.transport.href).toBe(`${root}${directory}/transport-worker.mjs`);
+});
+
+test('compiled Windows paths keep URL encoding intact', () => {
+ const urls = isolatedWorkerUrls('file:///C:/assets%20caf%C3%A9/lib/evaluator/isolation.js');
+ expect(urls.worker.href).toBe('file:///C:/assets%20caf%C3%A9/lib/evaluator/worker.js');
+});
diff --git a/src/evaluator/worker-urls.ts b/src/evaluator/worker-urls.ts
new file mode 100644
index 00000000..9d1b146f
--- /dev/null
+++ b/src/evaluator/worker-urls.ts
@@ -0,0 +1,16 @@
+/** Resolve workers in source, compiled SDK and installed bundle layouts. */
+export function isolatedWorkerUrls(moduleUrl: string): {
+ worker: URL;
+ probe: URL;
+ transport: URL;
+} {
+ const source = new URL(moduleUrl).pathname.endsWith('.ts');
+ const sdk = new URL(moduleUrl).pathname.endsWith('/isolation.js');
+ const base = new URL(source || sdk ? './' : '../lib/evaluator/', moduleUrl);
+ const extension = source ? 'ts' : 'js';
+ return {
+ worker: new URL(`worker.${extension}`, base),
+ probe: new URL(`probe-worker.${extension}`, base),
+ transport: new URL('transport-worker.mjs', base),
+ };
+}
diff --git a/src/index.ts b/src/index.ts
new file mode 100644
index 00000000..f981268e
--- /dev/null
+++ b/src/index.ts
@@ -0,0 +1,5 @@
+/** Node SDK entry. Import the documented subpaths for the full domain APIs. */
+export { renderGLB, type RenderGlbOptions, type RenderResult } from './render';
+export { validateKilnCode, type ValidationIssue, type ValidationResult } from './validation';
+export { createDiscovery, type DiscoveryRequest, type DiscoveryResponse } from './discovery';
+export { engineIdentity, ENGINE_VERSION, type EngineIdentityV1 } from './engine-identity';
diff --git a/src/mcp-engine.ts b/src/mcp-engine.ts
index bcee8b45..5cce701d 100644
--- a/src/mcp-engine.ts
+++ b/src/mcp-engine.ts
@@ -241,7 +241,9 @@ export function createKilnToolHost(
* as they are.
*/
function resourceText(name: string, bytes: Uint8Array): string {
- const text = new TextDecoder().decode(bytes);
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: name.endsWith('.js') }).decode(
+ bytes,
+ );
if (!name.endsWith('.json')) return text;
try {
return JSON.stringify(JSON.parse(text));
diff --git a/src/mcp-server.ts b/src/mcp-server.ts
index 52dd6513..26ea3dd3 100644
--- a/src/mcp-server.ts
+++ b/src/mcp-server.ts
@@ -90,6 +90,13 @@ if (isDirectEntry(import.meta.url)) {
process.exit(1);
}
const host = packagedEngineHost({ requirements });
+ let warmup: ReturnType<typeof setTimeout> | undefined;
+ const cancelWarmup = () => {
+ if (warmup !== undefined) clearTimeout(warmup);
+ warmup = undefined;
+ };
+ process.stdin.once('end', cancelWarmup);
+ process.stdin.once('close', cancelWarmup);
// stdout is the MCP transport; diagnostics must never touch it.
console.error(`kiln MCP server ${MCP_SERVER_VERSION} on stdio`);
void serveKilnStdio({
@@ -99,7 +106,13 @@ if (isDirectEntry(import.meta.url)) {
// which takes seconds: load the engine meanwhile so the first call is quick.
// A failure here is reported by that call, not here.
afterFirstToolList: () => {
- setTimeout(() => void host().catch(() => {}), 50);
+ if (process.stdin.readableEnded || process.stdin.destroyed) return;
+ warmup = setTimeout(() => {
+ warmup = undefined;
+ if (!process.stdin.readableEnded && !process.stdin.destroyed) void host().catch(() => {});
+ }, 50);
+ // Speculative work must not keep a disconnected stdio process alive.
+ warmup.unref();
},
});
}
diff --git a/src/metrics.ts b/src/metrics.ts
index 42904f97..b24d6fdb 100644
--- a/src/metrics.ts
+++ b/src/metrics.ts
@@ -2,7 +2,7 @@
* Kiln instanceability metrics + grader.
*
* A pure, deterministic, GPU-free static analysis over a baked glTF Document.
- * Lives in @kiln/engine so it can be computed at every natural point with
+ * Lives in @instruktlabs/kiln so it can be computed at every natural point with
* zero deploy coupling:
* - in render.ts -> render.meta for CLI / MCP / batch (never crosses the wire)
* - web-side in Kiln Studio from the persisted GLB
diff --git a/src/palette.ts b/src/palette.ts
index dfb401b5..6d1fd88a 100644
--- a/src/palette.ts
+++ b/src/palette.ts
@@ -5,7 +5,7 @@
*
* PURE DATA + a text helper. NO `three`, NO node, NO gltf-transform imports — so
* it is browser-safe and can be consumed anywhere (the leaf subpath
- * `@kiln/engine/palette`) without dragging runtime code into a bundle.
+ * `@instruktlabs/kiln/palette`) without dragging runtime code into a bundle.
*
* Why it lives in the engine: the palette is the shared contract both the
* authoring prompt (instruct the model to build against these roles) and a later
diff --git a/src/program-store.ts b/src/program-store.ts
index 31137a65..9bfdae28 100644
--- a/src/program-store.ts
+++ b/src/program-store.ts
@@ -56,7 +56,7 @@ export async function programReference(code: string): Promise<string> {
const bytes = new TextEncoder().encode(code);
if (bytes.length > MAX_PROGRAM_BYTES) throw new Error('Program exceeds the 1 MiB source limit.');
// Reject strings that would change when persisted as UTF-8 (unpaired surrogates).
- if (new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes) !== code)
+ if (new TextDecoder('utf-8', { fatal: false, ignoreBOM: true }).decode(bytes) !== code)
throw new Error('Program must be valid Unicode.');
const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
return `sha256:${Array.from(hash, (b) => b.toString(16).padStart(2, '0')).join('')}`;
diff --git a/src/review-tools.test.ts b/src/review-tools.test.ts
index 49662565..9d829e55 100644
--- a/src/review-tools.test.ts
+++ b/src/review-tools.test.ts
@@ -13,7 +13,7 @@ test('review save preserves recorded GLB/source and refuses revision or policy m
const root = await mkdtemp(join(tmpdir(), 'kiln-exact-review-'));
try {
const code =
- "const meta={name:'Reviewed'};function build(){const r=createRoot('Root');createPart('Body',boxGeo(1,1,1),gameMaterial('#887766'),{parent:r});return r;}";
+ "\ufeffconst meta={name:'Reviewed'};function build(){const r=createRoot('Root');createPart('Body',boxGeo(1,1,1),gameMaterial('#887766'),{parent:r});return r;}";
const rendered = await renderGLBInProcess(code, { optimize: 'off' });
const op: LiveOperation = {
version: 'kiln.live.v1',
@@ -84,7 +84,7 @@ test('review save preserves recorded GLB/source and refuses revision or policy m
const saved = (await tool.run(input)) as { asset: { assetId: string; revisionId: string } };
const record = await library.read('project', saved.asset.assetId, saved.asset.revisionId);
expect(record.files['asset.glb']).toEqual(glb);
- expect(new TextDecoder().decode(record.files['source.kiln.js'])).toBe(code);
+ expect(record.files['source.kiln.js']).toEqual(new TextEncoder().encode(code));
expect(record.manifest.build?.options.reviewOperationId).toBe(op.operationId);
expect(record.manifest.build?.options.instance).toBe(rendered.rebuildOptions!.instance);
expect(record.manifest.preview?.backdrop).toBe('dark');
diff --git a/src/runtime-identity.ts b/src/runtime-identity.ts
index b633a5ed..86870aa8 100644
--- a/src/runtime-identity.ts
+++ b/src/runtime-identity.ts
@@ -57,7 +57,7 @@ export async function installedRuntimeIdentity(
};
try {
const pkg = await manifest(root);
- if (pkg.name !== '@kiln/engine') throw new Error('Not a Kiln installation.');
+ if (pkg.name !== '@instruktlabs/kiln') throw new Error('Not a Kiln installation.');
const build = JSON.parse(await readFile(join(root, 'dist', 'build.json'), 'utf8'));
const worker = build.entries?.worker;
if (
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 291dc1e7..ef1d086d 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -177,7 +177,7 @@ export interface KilnToolContext {
/** Resolver configuration for this evaluator only. Read descriptors without resolving bytes. */
approvedTextureResources?: () => import('../material-resources').ApprovedTextureCatalogEntryV1[];
/** Native harness snapshot reader; absent from CLI/MCP and ordinary inline runs. */
- skillResourceReader?: import('../agent/skill-resources').SkillResourceReader;
+ skillResourceReader?: import('./skill-resource').SkillResourceReader;
/** Durable user collections, supplied by the host; never a disposable build cache. */
assetLibrary?: import('../assets').AssetLibrary;
/** Host-owned delivery URLs, for example expiring HTTPS links or a running local viewer. */
@@ -2974,7 +2974,10 @@ export function createKilnAssetDefs(context: KilnToolContext): KilnToolDef[] {
if (!code) throw new Error('Source unavailable: this asset contains only a GLB');
return {
...(await links(input.collection, record.manifest)),
- programRef: await retainProgram(context.programStore!, new TextDecoder().decode(code)),
+ programRef: await retainProgram(
+ context.programStore!,
+ new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(code),
+ ),
requirements: activeRequirements,
savedRequirements: saved,
acceptance: 'reevaluation-required',
diff --git a/src/tools/review.ts b/src/tools/review.ts
index bf11c1f3..30a785b2 100644
--- a/src/tools/review.ts
+++ b/src/tools/review.ts
@@ -206,7 +206,7 @@ export function createKilnReviewDef(context: {
.manifest,
active,
);
- const code = new TextDecoder().decode(source);
+ const code = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(source);
const checkpoint = evaluation.requirements.binding
? createRequirementsCheckpoint(
await programReference(code),
diff --git a/src/tools/skill-resource.ts b/src/tools/skill-resource.ts
new file mode 100644
index 00000000..befed2b1
--- /dev/null
+++ b/src/tools/skill-resource.ts
@@ -0,0 +1,9 @@
+/** Host-provided reference lookup; independent of any agent framework. */
+export interface SkillResourceRequest {
+ skill: string;
+ path?: string;
+ offset: number;
+ limit: number;
+}
+
+export type SkillResourceReader = (input: SkillResourceRequest) => unknown;
diff --git a/src/views/__tests__/renderer-id-package.test.ts b/src/views/__tests__/renderer-id-package.test.ts
index 8a5f028a..fcc1ca5a 100644
--- a/src/views/__tests__/renderer-id-package.test.ts
+++ b/src/views/__tests__/renderer-id-package.test.ts
@@ -16,7 +16,7 @@ it('reads its own package version when bundled rather than the consuming applica
);
await writeFile(
join(pkg, 'package.json'),
- JSON.stringify({ name: '@kiln/engine', version: '1.2.3-test' }),
+ JSON.stringify({ name: '@instruktlabs/kiln', version: '1.2.3-test' }),
);
const target = join(pkg, 'dist/renderer.mjs');
const built = spawnSync(
diff --git a/src/views/renderer-id.ts b/src/views/renderer-id.ts
index 48d50d50..bd1166cd 100644
--- a/src/views/renderer-id.ts
+++ b/src/views/renderer-id.ts
@@ -17,7 +17,7 @@ function engineVersion(): string {
try {
const raw = readFileSync(new URL(path, import.meta.url), 'utf8');
const pkg = JSON.parse(raw) as { name?: unknown; version?: unknown };
- if (pkg.name === '@kiln/engine' && typeof pkg.version === 'string' && pkg.version) {
+ if (pkg.name === '@instruktlabs/kiln' && typeof pkg.version === 'string' && pkg.version) {
return pkg.version;
}
} catch {