Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
Save asset collections and view them in chat (#54)
Matthew Kissingerdd98f8200e73
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonnew file mode 100644index 00000000..1a8a03ad--- /dev/null+++ b/.codex-plugin/plugin.json@@ -0,0 +1,20 @@+{+ "name": "kiln-oss",+ "version": "0.6.0",+ "description": "Create, review, save, and refine procedural 3D assets with portable source and GLB collections.",+ "author": {+ "name": "Matthew Kissinger"+ },+ "skills": "./skills/",+ "interface": {+ "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",+ "category": "Developer Tools",+ "capabilities": ["Read", "Write"],+ "defaultPrompt": ["Create a game prop and save its editable GLB bundle.", "Browse my collection and refine an existing asset."]+ },+ "mcpServers": "./.mcp.json",+ "license": "MIT"+}diff --git a/.gitignore b/.gitignoreindex 3e53af77..9d287dce 100644--- a/.gitignore+++ b/.gitignore@@ -12,6 +12,7 @@ dist/*!dist/build.json!dist/agent-run.mjs!dist/agent-providers.mjs+!dist/viewer/.kiln/coverage/# `kiln render` writes here when no --out is given, so it lands at the repodiff --git a/.mcp.json b/.mcp.jsonnew file mode 100644index 00000000..0bdeca51--- /dev/null+++ b/.mcp.json@@ -0,0 +1,9 @@+{+ "mcpServers": {+ "kiln": {+ "command": "node",+ "args": ["${PLUGIN_ROOT}/dist/mcp-server.mjs"],+ "env": { "KILN_RENDER": "auto" }+ }+ }+}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d1a37d8d..b798dd9b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,22 @@Changes to `@kiln/engine`. Source and installable packages are distributed throughGitHub. The package is not published on the npm registry.+## Collections and chat viewing — 2026-09-06++- Save assets into project or personal collections with immutable revisions,+ hashed provenance, original source, and portable editable ZIP bundles.+- Browse collections and imported GLBs in a local viewer with animation controls,+ revision inspection, and GLB/source/bundle downloads.+- Present saved assets in supporting MCP App clients with `kiln_present`.+ ChatGPT viewing was verified; native GLB/ZIP attachment delivery remains+ unverified. Host-provided download links are supported.+- Package complete skills independently or bind them to a ChatGPT connector.+- Add a canonical-only sitemap and crawler discovery file to the project site.++See [dogfood results and remaining work](docs/collections-dogfood.md) and+[indexing diagnostics](docs/site-indexing.md). Package version remains 0.6.0;+this change does not publish a new npm package or promote dogfood assets.+## Public OSS snapshot — 2026-09-05- Short, immutable source references work across rendering, source reads, edits,diff --git a/README.md b/README.mdindex 22bbc6f4..1f594b85 100644--- a/README.md+++ b/README.md@@ -87,6 +87,33 @@ harnesses and the plugin path.## Revise an asset+Save finished work into a collection with `node kiln.mjs save workbench.kiln.js --name "Workbench"`.+Run `node kiln.mjs view` to browse saved assets, inspect revisions, and download GLBs+or editable ZIP bundles. Project collections and personal libraries use the same+portable folders. See [saved assets and the viewer](docs/collections.md).++## Use Kiln in a chat client++Create and refine assets in ChatGPT through a private MCP connection, then ask to+see a saved revision. `kiln_present` opens an interactive 3D card in supporting+MCP App clients. Orbit the model and inspect its animation without leaving chat.+ChatGPT viewing was verified with real saved assets.++1. Build the runtime and connect its stdio MCP server through an OpenAI Secure+ MCP Tunnel scoped to your workspace.+2. Install the authoring and refinement skills with their reference files using+ ChatGPT's native skill uploader.+3. Ask: “Make a field recorder, review the renders, save it to my project+ collection, and show it with `kiln_present`.”++The [ChatGPT setup guide](docs/chatgpt.md) covers connection, skill packaging, and+host requirements. This currently needs developer setup; it is not a public+one-click ChatGPT app. Local GLB and editable ZIP downloads work through+`kiln view`. ChatGPT-native GLB/ZIP attachments remain unverified; download support+depends on the client or a host-provided delivery link.++## Restore source for another edit+Import an existing program from your asset workspace:```shdiff --git a/docs/chatgpt.md b/docs/chatgpt.mdnew file mode 100644index 00000000..7193d0d4--- /dev/null+++ b/docs/chatgpt.md@@ -0,0 +1,48 @@+# Kiln in ChatGPT++Kiln's local CLI and stdio MCP server share the same collection store and tool registry. ChatGPT web needs a reachable MCP connection: a private Secure MCP Tunnel can carry this existing stdio server without making a public endpoint. The tunnel process must remain running while ChatGPT discovers or calls tools.++## Connect a private development server++1. Build with the supported toolchain: `bun run build:runtime`.+2. Create a tunnel in OpenAI Platform, scoped to the intended ChatGPT workspace. The account needs Tunnels Read and Manage; its runtime API key needs Read and Use. Existing organization roles may already grant these. Do not broaden other permissions.+3. Download a pinned official `openai/tunnel-client` release and verify its release digest. This dogfood used Windows amd64 v0.0.14. Keep credentials in the environment or a supported secret reference, never in the plugin.+4. Configure the tunnel's stdio command to launch `node /absolute/path/dist/mcp-server.mjs` in a dedicated asset workspace. Set `KILN_PROGRAM_STORE` and `KILN_COLLECTIONS` explicitly. The server does not need provider keys. The tunnel control process needs its OpenAI key, which should not be inherited by the MCP child.+5. Run `tunnel-client doctor`, then `tunnel-client run` with the configured profile. In ChatGPT's Plugins page choose Create app, Tunnel, the intended tunnel, and No Auth for the stdio server. Access is still controlled by the private tunnel; this does not create a public unauthenticated service.+6. Verify all thirteen tools appear, including `kiln_present`. Test source submission, actual render-image visibility, save/list, copy, restore/edit, and exact revision export. Refresh connector metadata after changing tools.++Local subprocess evaluation has deadlines and a sanitized environment; it is not the Linux isolated evaluator's OS security boundary. This setup is for an owner-controlled development test. A hosted multi-user deployment needs tenant-scoped storage, authentication, and the isolated evaluator posture.++## Expose the skills++Keep `skills/*/SKILL.md` and their adjacent `references/` directories as the maintained source. Skill descriptions provide discovery; instructions load on selection, and reference files provide modeling detail when needed. Avoid pasting the complete modeling catalog into every tool description or prompt.++The repository now contains `.codex-plugin/plugin.json` and `.mcp.json` for local plugin hosts. Generated project workspaces continue to receive their own explicit skill copies. No global skills are installed.++For ChatGPT, first register the connector and copy its technical `plugin_asdk_app...` ID from the connector page. Then build a separate package:++```sh+node scripts/package-plugin.mjs /output/kiln-chatgpt plugin_asdk_app_ACTUAL_ID+```++The output contains the standard manifest, all skill references, license, a file-hash inventory, and `.app.json` bound to that specific connector. It contains no server executable, credentials, collections, or local filesystem paths. Output must not already exist. Omit the connector ID to produce a skills-only preparation package; that package does not connect a server by itself.++Install through the support available in the host. On the account tested September 6, 2026, ChatGPT web exposes **Plugins → Skills → Create → Upload from your computer**, accepting a ZIP/`.skill` file or `SKILL.md`. For each skill, zip the contents of its directory so `SKILL.md` and `references/` remain together. A bare markdown upload loses the referenced files. This native uploader can install individual skills separately from the MCP connector; the plugin package binds them for distribution across supporting hosts.++A local desktop marketplace is not automatically a web installation. Attaching skill text to a chat can test its guidance, but is not evidence that a native skill was installed. Private workspace distribution and public directory submission are separate actions.++## Downloads and viewing++MCP save/export replies contain `resource_link` entries for exact GLB, source, preview, manifest, and editable ZIP bytes. The full provenance lives in the manifest resource; chat replies carry compact revision summaries. Whether a host renders those links as download buttons is host-dependent and must be tested. A `kiln://` resource URI is not an HTTPS link and should not be presented as one.++`kiln_present` adds an MCP App card for a pinned saved revision. It reuses the local Three.js stage for orbit/zoom, studio lighting, and animation, and offers GLB, editable ZIP, and source downloads through the host's `ui/download-file` bridge. Binary data travels in tool-result `_meta`, separate from model-visible text. The self-contained HTML resource needs no CDN or public asset URL. Chat presentation is bounded to 16 MiB of asset files; larger assets remain available through the local viewer. Host support must be verified: MCP resource links alone do not prove a chat-native download works.++Hosts can inject `KilnToolContext.assetDownloadUrls(collection, assetId, revisionId)` to provide delivery URLs, including expiring links backed by their private artifact store. The local MCP executable accepts `KILN_ASSET_DOWNLOAD_BASE_URL` for a separately running viewer-compatible file service. HTTPS is required except for loopback HTTP. This setting does not start a server, upload files, or publish collections. Loopback links only work on the computer hosting that viewer, and some embedded clients block the handoff.++The card tries the standard download bridge first. When that method is missing, it offers a host-provided URL; otherwise it feature-detects ChatGPT's optional upload/download helpers. It does not bypass a denied download. On September 6, 2026, this ChatGPT web client rendered the interactive 3D card, but returned `Method not found` for `ui/download-file` and `Unsupported file type` for both GLB and ZIP through `window.openai.uploadFile`. Native ChatGPT-stored attachments are therefore **not verified**. An actual file-link download must be proven separately before advertising that path as working in a particular client.++The local viewer (`kiln view`) provides browser downloads, revision selection, collection browsing, animation controls, and source/build records. Both viewers open the exact GLB without executing its source.++The Node and Bun JavaScript runtimes can produce tiny floating-point differences in regenerated GLB JSON. Preserve the original artifact for byte-exact delivery and rebuild with the recorded engine's supported Node toolchain for reproducibility. ZIP import/export preserves original bytes regardless of runtime.++Official references checked September 6, 2026: [Connect ChatGPT](https://developers.openai.com/plugins/deploy/connect-chatgpt), [Secure MCP Tunnels](https://developers.openai.com/api/docs/guides/secure-mcp-tunnels), and [Package plugins](https://developers.openai.com/plugins/build/plugins). Surface availability can change; verify the actual host before claiming installation or download support.diff --git a/docs/collections-dogfood.md b/docs/collections-dogfood.mdnew file mode 100644index 00000000..1194222f--- /dev/null+++ b/docs/collections-dogfood.md@@ -0,0 +1,82 @@+# Collection workflow dogfood — September 6, 2026++The change adds explicit durable asset saves, project/personal collection roots, immutable child revisions, GLB/source/ZIP exports, and a read-only local GLB viewer. Draft rendering remains separate from saved collections. Full provenance travels in a hashed manifest; compact tool replies link to the record.++## Harness evidence++| Harness | Model evidence | Result |+| --- | --- | --- |+| Codex CLI | Reported `gpt-6-astra` | Completed recorder asset, image review, project save, copy to personal, source restore, child revision, and exports. |+| Antigravity CLI | Requested `gemini-3.8-flash-high`; log says resolved via default, so exact model remains unconfirmed | Completed animated orrery, image review, project save, copy to personal, source restore, child revision, and exports. |+| Claude CLI | Reported `claude-sonnet-5` | API-key attempt blocked by credit balance. Subscription attempt blocked by weekly limit. Neither generated an asset. |+| OpenCode CLI | Reported `glm-5.3-flash` | Timed out after ten minutes with no saved revision; transcript contains only the model header. This is not evidence of asset quality. |+| ChatGPT web | Composer reported GPT-5.6 Sol Light | Created the botanical scanner, reviewed actual CPU images, corrected its height, saved/copied/restored source, and saved a child refinement. Both native skills are installed and updated. Interactive MCP App viewing is verified; native attachment downloads are not. |++Runs used isolated asset workspaces containing the project skills and MCP configuration. They were authorized manual live tests, outside CI. No examples were copied into the test workspaces. Raw evidence remains local under `.dogfood/collections/`, including run metadata, transcripts, workspace outputs, and file hashes.++## Independent review++The actual exported GLBs were opened in the new viewer, beyond the models' CPU previews. The recorder's silhouette, twin reels, controls, handle, and protective frame read clearly. Its refined revision has 9,240 triangles, 136 meshes, eight materials, and a 113 KiB GLB: a plausible gallery candidate, with draw-call optimization still worth doing for a game destination. The orrery's gold/blue materials and orbit animation work in the viewer; its refined revision has 7,708 triangles, 45 meshes, six materials, and a 242 KiB GLB. Neither has been promoted to the gallery.++The local viewer delivered the recorder's editable bundle through the browser download event. Both original and child revisions of the recorder, orrery, and ChatGPT scanner were independently exported to ZIP, imported into a fresh library, hash-verified, and rebuilt from restored source. All six regenerated GLBs match the saved artifact hashes under Node 22.23.1. A Bun regeneration differs in last-place floating-point JSON values; cross-runtime byte identity is not claimed.++## Findings addressed++- Real model runs complained about verbose provenance replies. Save/export/restore now return compact revision summaries and separate manifest resources. A focused regression verifies that a 50,000-character integration record does not inflate export replies.+- ChatGPT classified tools without annotations as destructive/open-world. The registry now owns explicit annotations: source/discovery/export/presentation are reads, stateful operations are writes, all operations preserve existing revisions. Transport tests verify the advertised annotations. Refresh is asynchronous: verify the actual metadata afterward. Versioning UI resource URIs was necessary to replace cached viewer HTML during the browser test.+- The initial Platform page briefly reported insufficient tunnel permissions while account data loaded. Reopening it showed existing access. No organization roles were changed.+- ChatGPT web accepted ZIP skills directly, including their reference files. The installed-skill UI and loaded SKILL.md confirmed installation; this was not merely an attachment to a prompt.++## Validation++Supported toolchain check, typecheck, lint, packaged runtime smoke test, plugin packaging checks, and skill/plugin validators passed. The collection implementation passed **1,752 tests, two skipped, zero failed**. The first widget/download-helper coverage run passed **1,755 tests, two skipped, zero failed**, with functions **95.48%** and lines **92.71%**, above the unchanged 92%/91% gates. After adding host-provided delivery URLs and the presentation output schema, the focused 15-test set passed; two full coverage attempts aborted in the previously documented Windows GLib `g_system_thread_free`/invalid `CloseHandle` fault at `examples.test.ts`. Those attempts are not clean gates. No dependency version, thread limit, or coverage threshold was changed to mask the fault. Existing lint warnings remain.++A final non-coverage suite also aborted at `examples.test.ts`, reporting `GetQueuedCompletionStatusEx: (735) ERROR_ABANDONED_WAIT_0`. The latest tree therefore does not have a completed full offline gate. Logs are `.dogfood-widget-final-coverage.log`, `.dogfood-widget-final-coverage-retry.log`, and `.dogfood-widget-final-test.log`; the successful focused/package logs are retained separately.++## ChatGPT integration++The private tunnel and connector are named **Kiln Local**. They use an outbound OpenAI Secure MCP Tunnel and expose only dedicated collection roots, not the user's other project directories. The MCP child does not inherit the tunnel's API key. The native authoring and refinement skills are installed, and a separate distributable plugin package is bound to the registered connector ID. The private assets and connector configuration are excluded from the code publication.++Both native skills were updated with `kiln_present` guidance through the ChatGPT skill editor, preserving their reference files. The authoring detail preview showed the saved new guidance. The refinement detail preview returned a host file-load error, while reopening its editor showed the persisted complete updated source; this preview inconsistency remains a host-side verification limitation.++The scanner asset is `a_eb0228e498f5462b897453d802c1fc30`. Its original is `r_b67dbd53f0364abb8d511fee5cbd4c7b`, copied to personal; its refined child `r_6c4b1ee212b74b9cac78a48cf222e9e0` is in project. The child moves the handle grip outward by 7 mm. It has 840 triangles, 19 meshes, and six materials. The independent replay verified both revisions.++`kiln_present` rendered the scanner and the more detailed WAYFARER recorder inside the actual ChatGPT conversation, using a self-contained MCP App resource and widget-only binary metadata. The recorder was copied from the separate Codex dogfood collection without rebuilding; it was not generated by ChatGPT. Its source attribution is preserved.++Download results must be described separately: ChatGPT returned `Method not found` for standard `ui/download-file`, and its optional `uploadFile` helper rejected GLB and ZIP as unsupported file types. A host-owned delivery URL now provides a fallback and the local endpoint returns exact bytes with attachment headers. ChatGPT displayed its external-link confirmation, but the embedded-browser download handoff did not complete reliably. A native download event was not verified there. A browser media-download attempt navigated the iframe and hit its frame security boundary; that is not a successful download test. No frame or browser security setting was weakened.++The unedited viewer preview is local at `.dogfood/chat-ui/recorder-viewer-downloads-pending.png`. The launch folder was located at `tmp/launch-kit` (including draft posts and gallery grids), but the preview has not been promoted there as a successful download demonstration. A temporary one-hour HTTPS relay for only the recorder GLB and editable ZIP is prepared. Automatic approval review rejected starting/testing the local relay with only `blocked by policy`; specific user approval for the temporary external exposure is pending. Nothing has been exposed publicly by that relay.++See [ChatGPT setup and packaging](chatgpt.md) for the reusable workflow and [collection semantics](collections.md) for the persistence and download contract.++## Closeout and remaining work++The owner authorized documentation, commit, push, and deployment, then asked to+finish with the download experiment documented. The temporary relay is deferred;+no account permission change is needed to publish the code. The automatic tool+review supplied no reason beyond `blocked by policy` for that separate relay action.++- Finish a real ChatGPT GLB and editable-ZIP download test before claiming native+ delivery. A temporary public relay remains a proposal, not a verified solution.+- After successful delivery, capture the actual chat and add it to+ `tmp/launch-kit/G-chat-mcp` with accurate author/model attribution. The existing+ local preview shows viewing only and remains outside launch-ready media.+- Review recorder/orrery candidates with the owner before gallery promotion.+- Recheck the ChatGPT refinement skill detail preview; its editor saved correctly+ but the host preview failed to load.+- Track the unresolved Windows native GLib fault. A fresh isolated examples run+ passed 75 tests and 592 assertions in 33.47 seconds during closeout; this does+ not explain the earlier full-suite crashes. Hosted CI supplies an independent+ full gate for the release candidate.+- Wait for Google's requested revalidation of six old duplicate URLs; see+ [Search Console findings](site-indexing.md).++The release also fixes plugin-check diagnostics contaminating the JSON package+receipt consumed by macOS CI. A regression failed before moving those diagnostics+to stderr and passed afterward. Canonical/sitemap consistency has a focused check.++The closeout package smoke passed on Windows with a parseable JSON receipt;+typecheck, lint, and the site build passed. A further local coverage run aborted+with `ERROR_ABANDONED_WAIT_0` during CLI render-mode tests rather than examples+(`.dogfood-release-coverage.log`). The fault is not confined to the example file.+No speculative runtime mitigation or relaxed gate was introduced.diff --git a/docs/collections.md b/docs/collections.mdnew file mode 100644index 00000000..8e1480ee--- /dev/null+++ b/docs/collections.md@@ -0,0 +1,113 @@+# Saved assets and the local viewer++Save an asset with its editable source, inspect it in a browser, and move a pinned+revision between a game project and a personal library. Everything runs locally;+viewing and exporting make no model calls. Collections are separate from source+snapshots and disposable build caches.++## Start in your asset workspace++```sh+node kiln.mjs save workbench.kiln.js --name "Workbench" --tag furniture+node kiln.mjs assets+node kiln.mjs view+```++Open the printed loopback URL. The viewer shows one card per asset, supports search,+tags, revision selection, animation playback, wireframe, lighting and downloads.+It loads the saved GLB, never executes its JavaScript. Selecting a revision in the+browser remembers that choice in that browser; it does not update other clients.+Multiple branch tips are identified on the asset card.++`kiln view asset.glb` or `kiln view bundle.zip` previews a standalone file without+importing it. The file picker also accepts local GLBs and Kiln ZIP bundles. Opened+files stay in browser memory until the page closes. A GLB without source is labelled+as such. Select several collection assets to download one ZIP, up to 100 revisions+and 64 MiB of uncompressed content.++From the engine checkout, use `node dist/cli.mjs` instead of `node kiln.mjs`.++## Project collections and personal libraries++The default `project` collection lives at `<workspace>/assets/kiln`. Remember another+location with:++```sh+node kiln.mjs collections add personal /absolute/path/to/my-library+node kiln.mjs collections+node kiln.mjs save chair.kiln.js --name "Chair" --collection personal+```++Paths are stored in the workspace's `.kiln/collections.json`. Restart an existing+viewer or MCP process after changing this configuration. `KILN_COLLECTIONS` can+override it with a JSON map, such as `{"project":"/game/assets/kiln","personal":"/my-library"}`.+The configured directories are the only collection roots the server exposes.+The CLI and MCP derive their workspace from the shared `KILN_PROGRAM_STORE` when set.++An asset directory contains `revisions/<revisionId>/manifest.json`, `asset.glb`, and,+when available, `source.kiln.js` and `preview.png`. Copy the whole collection to move it.+Source/manifest files are suitable for Git; decide whether generated binaries belong+in Git, LFS, or ordinary backups. The generated workspace ignores GLB and PNG files+by default. There is no automatic deletion or disk quota for saved collections.++## Agents and refinement++1. Author/review with the existing tools. Draft rendering retains source but does+ not create gallery entries.+2. Call `kiln_save` with `programRef`, `name`, and a collection. Optional fields include+ tags, brief, description and known attribution.+3. Save the returned asset/revision IDs. `kiln_export` returns resource links for the+ GLB, source, preview, manifest and ZIP. MCP clients choose how to show downloads.+4. In a later session, use `kiln_assets` with `action: "restore"`, collection,+ assetId and revisionId. Use the returned programRef with `kiln_source`/`kiln_edit`.+5. Save a child with the same assetId and `parentRevision` equal to the base revision.++`kiln_assets` also lists configured collections, searches/paginates revisions and+retrieves complete build records. `kiln_import` copies one exact revision between+configured collections. Copies preserve identity and never update automatically.++The viewer's **Copy refinement instructions** provides an exact restore/edit/save+instruction for your agent. Library integrators can inject `AssetLibrary` into+`KilnToolContext`; `makeKilnProgramTools` exposes the same registry through Strands+plus a terminal submit tool. Existing generation/buffer surfaces remain compatible.++## Export and import++```sh+node kiln.mjs export ASSET_ID REVISION_ID --out workbench.zip+node kiln.mjs export ASSET_ID REVISION_ID --format glb --out workbench.glb+node kiln.mjs export ASSET_ID REVISION_ID --format source --out workbench.kiln.js+node kiln.mjs import workbench.zip --collection personal+node kiln.mjs asset ASSET_ID REVISION_ID --collection personal --restore+```++Exports refuse to overwrite existing files. ZIPs are ordinary archives containing+one or more complete revisions. Source restore needs no original program store.+Source is capped at 1 MiB; normal evaluator limits can be lower. Bundles are bounded,+filenames are allowlisted and hashes are verified on import/read. GLBs must embed+resources, rather than fetch remote URLs when viewed.++Imports preserve original IDs and parent references, even when an ancestor was not+included. Importing the same revision twice is harmless; a conflicting identity is+rejected. Each revision is committed atomically; a multi-revision import may have+committed earlier revisions if a later filesystem operation fails. Retrying is safe.++## Provenance and rebuilding++The manifest records source/GLB/preview hashes, parent revision, build warnings,+integration/QA information, effective host options and runtime identity when verified.+Source-development or unverified hosts are labelled explicitly. Briefs and model+attribution are supplied context, not authenticated authorship claims.++The source depends on Kiln: preserve the indicated engine installation/version for+rebuilding. Approved packaged textures travel with that engine. A host-only runtime+texture dependency is recorded as `external-dependencies-required`; its bytes are+not silently claimed to be in the ZIP. The GLB itself remains self-contained.+CPU preview fidelity is recorded; use the interactive material rendering to inspect+appearance, and the structural report for geometry checks. GPU pixels are not QA evidence.++The local browser host binds to loopback, serves only configured collections and+bundled viewer files, and rejects cross-origin requests and writes. It has no remote+authentication or public hosting mode. Remote MCP hosts must supply reachable file+delivery; localhost links on a remote machine are not user download URLs. Embedded+chat viewing and each client's download behavior require separate verification.diff --git a/docs/programs.md b/docs/programs.mdindex 7e4ac75b..1d63ecac 100644--- a/docs/programs.md+++ b/docs/programs.md@@ -83,7 +83,7 @@ and set `diffTruncated`; use source reads for the rest.## Library use`createKilnProgramToolRegistry(context)` is exported from `@kiln/engine/tools` and returns the-same eight definitions used by MCP. Inject `context.programStore`, with asynchronous+same twelve definitions used by MCP. Inject `context.programStore`, with asynchronous`put(code)` and `get(programRef)` methods, to share revisions between instances. Withoutit, one registry instance keeps an in-memory store bounded to 64 MiB. Keep that instancefor the run. The legacy registry and internal working-buffer surface remain separate.diff --git a/docs/site-indexing.md b/docs/site-indexing.mdnew file mode 100644index 00000000..c218c059--- /dev/null+++ b/docs/site-indexing.md@@ -0,0 +1,60 @@+# Search indexing — September 6, 2026++The owner reported Search Console's “Duplicate without user-selected canonical”+warning for kilnstudio.tools. The domain property's report was inspected in the+owner's browser. Its six affected URLs were last crawled August 28–September 1,+before the current OSS site snapshot. Google's individual selected canonicals+were not inspected; the current live responses were checked for all six.++| Reported URL | Current first response | Current destination |+| --- | --- | --- |+| `https://www.kilnstudio.tools/` | 301 | Canonical HTTPS apex |+| `http://www.kilnstudio.tools/` | 301 | Canonical HTTPS apex |+| `https://play.kilnstudio.tools/` | 302 | GitHub Pages, then canonical HTTPS apex |+| `https://play.kilnstudio.tools/pocket-settlement` | 302 | Same redirect chain |+| `https://play.kilnstudio.tools/tower-defense` | 302 | Same redirect chain |+| `https://play.kilnstudio.tools/chess-board` | 302 | Same redirect chain |++All six end at a 200 HTML document declaring `https://kilnstudio.tools/` canonical.+Search Console accepted **Validate Fix** and showed **Validation started** on+September 6. This requests a fresh evaluation; it does not mean Google has finished+validation or indexed every duplicate. Analytics configuration was not changed.++## Live checks before this change++- `https://kilnstudio.tools/` returns 200 with exactly one static HTML canonical:+ `https://kilnstudio.tools/`.+- HTTP, `https://www.kilnstudio.tools/`, and the GitHub Pages project address+ redirect to that HTTPS apex URL.+- `/index.html` and a query-string variant return 200 and declare the same+ canonical root. They should consolidate into the root, not be indexed separately.+- `/robots.txt` and `/sitemap.xml` returned 404.++This change adds a crawl-allowing robots file referencing a sitemap that contains+only the canonical root. The existing canonical remains in the original HTML.+The account already had `/sitemap-index.xml` submitted from the old site, with an+error and zero discovered pages. That path is restored as a sitemap index pointing+to the new root sitemap, so Google's existing submission remains usable.+Hash routes such as `#/gallery` are views within one document; they are not listed+as separate crawlable pages or given fragment canonicals. Individually indexed+gallery pages would require real page URLs and distinct page content.++Google treats redirects and canonical links as strong signals and sitemap entries+as a weaker, complementary signal. A missing sitemap alone does not establish+the cause of this warning. Do not block duplicate URLs with robots.txt or add+`noindex` to the main page to try to solve canonical selection.++Reference: [Google's canonicalization guidance](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls).++## Remaining Search Console work++1. Submit `https://kilnstudio.tools/sitemap.xml` after deployment.+2. Allow Google to recrawl. Deployment cannot guarantee indexing or immediately+ clear the report. A duplicate excluded in favor of the intended root is normal.+3. If the report persists after a fresh crawl, inspect Google's selected canonical+ for the remaining examples. The retired `play` host could be simplified to a+ direct permanent redirect at its hosting configuration; that infrastructure+ is not owned by this GitHub Pages repository and was not changed here.++No account permissions were changed. Recheck the submitted sitemap index after+deployment and retain the final deployment/submission receipt locally.diff --git a/docs/tools.md b/docs/tools.mdindex da6f512b..2e2582d2 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -1770,3 +1770,268 @@ Read a saved program revision without changing it. Returns exact source text in```</details>++## kiln_save++Save a completed source revision as a durable asset with its exact GLB, source, preview, and build record. Use programRef returned by render/edit. To revise an existing asset, supply its assetId and parentRevision; previous revisions remain intact. Returns downloadable resources. Draft renders do not populate collections.++<details>+<summary>Input JSON Schema</summary>+++```json+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "programRef": {+ "type": "string"+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "parentRevision": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "tags": {+ "maxItems": 30,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 80+ }+ },+ "brief": {+ "type": "string",+ "maxLength": 8000+ },+ "description": {+ "type": "string",+ "maxLength": 4000+ },+ "attribution": {+ "type": "object",+ "properties": {+ "model": {+ "type": "string",+ "maxLength": 200+ },+ "harness": {+ "type": "string",+ "maxLength": 200+ },+ "author": {+ "type": "string",+ "maxLength": 200+ }+ },+ "additionalProperties": false+ }+ },+ "required": [+ "collection",+ "programRef",+ "name"+ ],+ "additionalProperties": false+}+```++</details>++## kiln_assets++Discover collections; list/search saved asset revisions; get a build record and downloads; or restore exact editable source into the current program store for kiln_source/kiln_edit. List is paginated. Binary-only imports cannot restore source.++<details>+<summary>Input JSON Schema</summary>+++```json+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "default": "list",+ "type": "string",+ "enum": [+ "collections",+ "list",+ "get",+ "restore"+ ]+ },+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "query": {+ "type": "string",+ "maxLength": 200+ },+ "offset": {+ "default": 0,+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "default": 20,+ "type": "integer",+ "minimum": 1,+ "maximum": 50+ }+ },+ "required": [+ "action",+ "collection",+ "offset",+ "limit"+ ],+ "additionalProperties": false+}+```++</details>++## kiln_present++Show a saved asset in an interactive chat viewer with GLB, editable ZIP, and source download buttons. Call after saving or when the user wants to see or download an asset. Other hosts receive portable resource links.++<details>+<summary>Input JSON Schema</summary>+++```json+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "required": [+ "collection",+ "assetId",+ "revisionId"+ ],+ "additionalProperties": false+}+```++</details>++## kiln_export++Get downloadable GLB, source, manifest, and portable ZIP resource links for one exact saved revision. The ZIP contains source when available and does not require the original program store. Use the host resource reader/download UI; no binary bytes are placed in tool text.++<details>+<summary>Input JSON Schema</summary>+++```json+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "required": [+ "collection",+ "assetId",+ "revisionId"+ ],+ "additionalProperties": false+}+```++</details>++## kiln_import++Copy a pinned asset revision between configured project/personal collections, preserving identity and provenance. Copies never track later edits automatically. For a GLB or downloaded ZIP on disk, use kiln import <file> --collection <name> in the CLI.++<details>+<summary>Input JSON Schema</summary>+++```json+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "sourceCollection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "required": [+ "collection",+ "assetId",+ "revisionId",+ "sourceCollection"+ ],+ "additionalProperties": false+}+```++</details>diff --git a/package.json b/package.jsonindex f5bf8cf6..e687cff8 100644--- a/package.json+++ b/package.json@@ -16,7 +16,9 @@"kiln": "./dist/cli.mjs","kiln-init": "./scripts/create-workspace.mjs"},- "exports": {+ "exports": {+ "./assets": "./src/assets.ts",+ "./assets/node": "./src/assets-node.ts",".": "./src/cli.ts","./agent": "./src/agent/index.ts","./tools": "./src/tools/registry.ts",@@ -58,6 +60,7 @@"./world-runtime": "./src/composer/terrain-runtime.ts"},"files": [+ "dist/viewer/","src/**/*.ts","src/**/*.mjs","!src/**/*.test.ts",@@ -66,7 +69,10 @@"dist/build.json","plugin.json",".claude-plugin/",+ ".codex-plugin/",+ ".mcp.json","scripts/create-workspace.mjs",+ "scripts/package-plugin.mjs","skills/","docs/","README.md",@@ -82,12 +88,13 @@"build:mcp": "node scripts/build-runtime.mjs mcp","build:cli": "node scripts/build-runtime.mjs cli","build:worker": "node scripts/build-runtime.mjs worker",- "build:runtime": "node scripts/build-runtime.mjs all",+ "build:runtime": "node scripts/build-viewer.mjs && node scripts/build-runtime.mjs all",+ "build:viewer": "node scripts/build-viewer.mjs","docs:tools": "bun scripts/generate-tool-reference.ts","test": "KILN_SPIKE_LIVE=0 KILN_RENDER=cpu bun test src scripts","test:coverage": "KILN_SPIKE_LIVE=0 KILN_RENDER=cpu bun test src scripts --coverage && bun scripts/check-coverage.mjs","test:live": "KILN_SPIKE_LIVE=1 bun test",- "test:package": "node scripts/smoke-package.mjs",+ "test:package": "node scripts/test-plugin-package.mjs && node scripts/smoke-package.mjs","lint": "biome check .","site:assets": "cd site && bun scripts/build-assets.mjs","site:dev": "bun run --cwd site dev",diff --git a/scripts/build-runtime.mjs b/scripts/build-runtime.mjsindex 7b727236..7ad181bd 100644--- a/scripts/build-runtime.mjs+++ b/scripts/build-runtime.mjs@@ -14,7 +14,7 @@ async function sources(directory, prefix = '') {if (item.name === '__tests__' || item.name.endsWith('.test.ts')) continue;const name = prefix ? `${prefix}/${item.name}` : item.name;if (item.isDirectory()) entries.push(...await sources(join(directory, item.name), name));- else if (/\.(?:ts|mjs)$/.test(item.name)) entries.push([name, sha(await readFile(join(directory, item.name)))]);+ else if (/\.(?:ts|mjs|html|css)$/.test(item.name)) entries.push([name, sha(await readFile(join(directory, item.name)))]);}return entries;}diff --git a/scripts/build-viewer.mjs b/scripts/build-viewer.mjsnew file mode 100644index 00000000..0ad047b6--- /dev/null+++ b/scripts/build-viewer.mjs@@ -0,0 +1,44 @@+import { spawnSync } from "node:child_process";+import { copyFile, mkdir, readFile, writeFile, unlink } from "node:fs/promises";+import { fileURLToPath } from "node:url";+import { dirname, join, resolve } from "node:path";+const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+await mkdir(join(root, "dist/viewer"), { recursive: true });+const result = spawnSync(+ "bun",+ [+ "build",+ "src/viewer/app.ts",+ "--target=browser",+ "--minify",+ "--outfile=dist/viewer/app.js",+ ],+ { cwd: root, stdio: "inherit", windowsHide: true },+);+if (result.status !== 0) process.exit(result.status ?? 1);+for (const file of ["index.html", "style.css"])+ await copyFile(+ join(root, "src/viewer", file),+ join(root, "dist/viewer", file),+ );+const chat = spawnSync(+ "bun",+ [+ "build",+ "src/viewer/chat-app.ts",+ "--target=browser",+ "--minify",+ "--outfile=dist/viewer/chat-app.js",+ ],+ { cwd: root, stdio: "inherit", windowsHide: true },+);+if (chat.status !== 0) process.exit(chat.status ?? 1);+const script = await readFile(join(root, "dist/viewer/chat-app.js"), "utf8");+const html = await readFile(join(root, "src/viewer/chat.html"), "utf8");+await writeFile(+ join(root, "dist/viewer/chat.html"),+ html.replace("/* KILN_CHAT_APP */", () =>+ script.replace(/<\/script/gi, "<\\/script"),+ ),+);+await unlink(join(root, "dist/viewer/chat-app.js"));diff --git a/scripts/create-workspace.mjs b/scripts/create-workspace.mjsindex afd47273..3b03bfab 100644--- a/scripts/create-workspace.mjs+++ b/scripts/create-workspace.mjs@@ -64,6 +64,7 @@ Use the kiln_workspace MCP server configured in this project to author and refin- Use kiln_source with programRef and a literal query to read exact edit anchors. Follow nextOffset for more context.- Use kiln_edit with programRef and edits. It returns a new programRef and renders by default. Use that reference for later views and edits; do not resend the program.- Review the image and diff. Check viewFidelity before judging materials.+- Save completed assets with kiln_save, browse configured collections with kiln_assets, and open node kiln.mjs view to inspect saved GLBs. Keep the exact asset and revision IDs for export or restore. Save refinements as child revisions rather than replacing their parent.- Save with node kiln.mjs source PROGRAM_REF --out revised.kiln.js. Export refuses to overwrite a file.- Export geometry with node kiln.mjs render PROGRAM_REF --out asset.glb --views sheet.png.diff --git a/scripts/dogfood-collections.mjs b/scripts/dogfood-collections.mjsnew file mode 100644index 00000000..ef2fdd6d--- /dev/null+++ b/scripts/dogfood-collections.mjs@@ -0,0 +1,57 @@+#!/usr/bin/env node+// Manual, paid harness dogfood. Never imported by CI or normal validation.+import { mkdir, mkdtemp, readFile, writeFile, readdir, cp } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { tmpdir } from 'node:os';+import { createHash } from 'node:crypto';+import { createWorkspace } from './create-workspace.mjs';+import { HARNESSES, run } from './harness.mjs';++const choices = {+ codex: { model: null, subject: 'A portable field recording machine: two exposed tape reels, a sloped control panel with distinct knobs and VU meters, a sturdy carry handle, rubber feet, and a removable-looking protective frame. Warm ivory panels, dark graphite case, restrained orange details. A coherent finished prop for a stylized exploration game, about 40 cm wide.' },+ claude: { model: 'sonnet', subject: 'A portable field recording machine: two exposed tape reels, a sloped control panel with distinct knobs and VU meters, a sturdy carry handle, rubber feet, and a removable-looking protective frame. Warm ivory panels, dark graphite case, restrained orange details. A coherent finished prop for a stylized exploration game, about 40 cm wide.' },+ opencode: { model: 'opencode-go/glm-5.3-flash', subject: 'A compact botanical research trolley: four rubber wheels touching the ground, a lower tray, two planted specimen containers with distinct broad leaf silhouettes, a small articulated inspection lamp, and a clipped-on instrument panel. Sage green powder-coated frame, terracotta pots, warm ivory instrument. A coherent finished prop for a stylized exploration game, about 90 cm tall.' },+ agy: { model: 'gemini-3.8-flash-high', subject: 'A tabletop mechanical orrery: stepped circular pedestal, a tilted brass orbital ring held by a real bracket, a central sun sphere, and three planets on distinct supported radial arms at different radii. Midnight blue enamel and warm brass. A coherent finished prop for a stylized exploration game, about 45 cm tall. Include a slow looping orbit animation if you can review its intermediate poses.' },+};+const harnessName = process.argv[2]; const choice = choices[harnessName];+if (!choice) throw new Error('Choose claude, codex, opencode, or agy. This command spends model quota.');+const stamp = new Date().toISOString().replaceAll(':','-').replaceAll('.','-');+const output = resolve('.dogfood','collections',`${stamp}-${harnessName}`); await mkdir(output,{recursive:true});+const parent = await mkdtemp(join(tmpdir(),'kiln-collections-dogfood-')); const workspace = join(parent,'workspace');+await createWorkspace(workspace,harnessName);+const base = JSON.parse(await readFile(join(workspace,'.kiln','workspace.json'),'utf8'));+const sourceStore = join(workspace,'.kiln','programs');+const roots = { project: join(workspace,'assets','kiln'), personal: join(workspace,'personal-library') };+await writeFile(join(workspace,'.kiln','collections.json'),JSON.stringify(roots,null,2));+const prompt = [+ 'Read this workspace AGENTS.md and skills/kiln-author-asset/SKILL.md. Use only the configured kiln_workspace server. Do not read the engine source or example collection. Do not install software, publish, or use another agent.',+ `Make this asset: ${choice.subject}`,+ 'Use kiln_list_primitives to learn the needed API. Author, render, look at images when your harness delivers them, and repair visible problems. Do not claim you saw an image if you only received a file path. Check viewFidelity before judging materials.',+ `Save the finished source using kiln_save into project, with a clear name, tags, brief, and attribution ${choice.model ? `model=${choice.model}, ` : ''}harness=${harnessName}. This is supplied attribution; the parent will verify the actual model separately.`,+ 'Then exercise the new workflow: kiln_assets list; kiln_export; kiln_import copying the saved revision from project to personal; kiln_assets restore from personal. Make one small intentional dimension/detail refinement with kiln_edit and save the child into personal with the original assetId and parentRevision. Export the child resource links. Preserve both revisions.',+ 'Write dogfood-result.json with assetId, originalRevisionId, refinedRevisionId, programRefs, review observations, any tool/UX issues, and whether render images were actually visible to you. Use the host Write tool for this report. Finish within 10 minutes. Never spend the whole time polishing; leave time to test save/copy/restore/refine.',+].join(' ');+await writeFile(join(output,'brief.txt'),prompt);+const harness = HARNESSES[harnessName]; const logFile = join(output,'harness.log');+let args = harness.argv({model:choice.model,prompt,timeout:'10m',logFile,sandbox:workspace});+if (harnessName === 'claude') args = ['-p',prompt,'--model',choice.model,'--permission-mode','acceptEdits','--strict-mcp-config','--mcp-config',join(workspace,'.mcp.json'),'--allowedTools','mcp__kiln_workspace__* Read Write Edit Glob Grep','--output-format','stream-json','--verbose'];+if (harnessName === 'agy') args = ['--new-project',...args,'--disable-slash-commands'];+console.log(JSON.stringify({harness:harnessName,requestedModel:choice.model,workspace,output}));+await writeFile(join(output,'run.json'),JSON.stringify({harness:harnessName,requestedModel:choice.model,workspace,output,workspaceSetup:base,startedAt:new Date().toISOString(),authorization:'User requested different harness/model dogfoods after implementing collections.',renderer:'cpu',runtimeBuild:JSON.parse(await readFile('dist/build.json','utf8'))},null,2));+const result = await run(harness.bin,args,{cwd:workspace,timeoutMs:10*60*1000,logFile:harness.needsLogFile?logFile:null,env:{KILN_RENDER:'cpu',KILN_PROGRAM_STORE:sourceStore,KILN_COLLECTIONS:JSON.stringify(roots),...(harness.env?.({model:choice.model}) ?? {})}});+await writeFile(join(output,'transcript.txt'),result.out);+await cp(workspace,join(output,'workspace'),{recursive:true,filter:path=>!path.includes('node_modules')&&!path.includes(`${join('.kiln','cache')}`)});+const manifests = [];+for (const [collection, directory] of Object.entries(roots)) {+ for (const asset of await readdir(directory).catch(()=>[])) {+ for (const revision of await readdir(join(directory,asset,'revisions')).catch(()=>[])) {+ try { const record = JSON.parse(await readFile(join(directory,asset,'revisions',revision,'manifest.json'),'utf8')); manifests.push({collection,record}); } catch {}+ }+ }+}+let actualModel = harness.actualModel?.(result.out) ?? null;+if (harnessName === 'codex') actualModel = /^model:\s*(.+)$/m.exec(result.out)?.[1]?.trim() ?? null;+if (harnessName === 'claude') for (const line of result.out.split('\n')) { try { const item=JSON.parse(line); if(item.type==='system'&&item.subtype==='init') actualModel=item.model; } catch {} }+const summary = {harness:harnessName,requestedModel:choice.model,actualModel,exitCode:result.code,finishedAt:new Date().toISOString(),savedRevisions:manifests.map(({collection,record})=>({collection,name:record.name,assetId:record.assetId,revisionId:record.revisionId,parentRevision:record.parentRevision,artifactHash:record.files['asset.glb'].sha256})),transcriptHash:createHash('sha256').update(result.out).digest('hex'),output};+await writeFile(join(output,'result.json'),JSON.stringify(summary,null,2)); console.log(JSON.stringify(summary));+process.exitCode = result.code === 0 && manifests.length >= 3 ? 0 : 1;diff --git a/scripts/evaluation/conditions.ts b/scripts/evaluation/conditions.tsindex 665e71b8..5bcb35f5 100644--- a/scripts/evaluation/conditions.ts+++ b/scripts/evaluation/conditions.ts@@ -71,7 +71,9 @@ export function createConditionRegistry(condition: Condition, context: KilnToolCevaluatorCacheIdentity: undefined,evaluatorPort: { render: (code,options,controls) => { assertConditionSource(code,condition); return evaluator.render(code,options,controls); } },});- return registry.map((def) => {+ // This frozen authoring experiment predates collections. Keep the same eight+ // verbs in each condition so storage tools cannot change its measured context.+ return registry.filter(def => !['kiln_save','kiln_assets','kiln_export','kiln_import','kiln_present'].includes(def.name)).map((def) => {if (def.name === 'kiln_list_primitives') return conditionDiscovery(def,condition);let schema = def.inputSchema;if (condition === 'A' && schema instanceof z.ZodObject) {diff --git a/scripts/package-plugin.mjs b/scripts/package-plugin.mjsnew file mode 100644index 00000000..e96e3932--- /dev/null+++ b/scripts/package-plugin.mjs@@ -0,0 +1,44 @@+#!/usr/bin/env node+import { createHash } from 'node:crypto';+import { cp, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';+import { basename, dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');+// Package the maintained skills for a registered ChatGPT connector. No credentials,+// local collections, executable server, or machine-specific paths enter this bundle.+export async function packagePlugin(destination, appId) {+ if (appId !== undefined && !/^plugin_asdk_app[_a-zA-Z0-9-]+$/.test(appId))+ throw new Error('Expected a registered plugin_asdk_app connector ID');+ const directory = resolve(destination);+ const name = basename(directory);+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) throw new Error('Use a lowercase hyphenated plugin folder name');+ await mkdir(dirname(directory), { recursive: true });+ await mkdir(directory); // Deliberately refuses an existing output.+ const manifest = JSON.parse(await readFile(join(repo, '.codex-plugin/plugin.json'), 'utf8'));+ manifest.name = name;+ delete manifest.mcpServers;+ if (appId) manifest.apps = './.app.json';+ await mkdir(join(directory, '.codex-plugin'));+ await writeFile(join(directory, '.codex-plugin/plugin.json'), JSON.stringify(manifest, null, 2) + '\n');+ await cp(join(repo, 'skills'), join(directory, 'skills'), { recursive: true });+ await cp(join(repo, 'LICENSE'), join(directory, 'LICENSE'));+ if (appId) await writeFile(join(directory, '.app.json'), JSON.stringify({ apps: { kiln: { id: appId } } }, null, 2) + '\n');+ const files = {};+ async function inventory(path, prefix = '') {+ for (const entry of (await readdir(path, { withFileTypes: true })).sort((a,b) => a.name.localeCompare(b.name))) {+ const relative = prefix + entry.name;+ if (entry.isDirectory()) await inventory(join(path, entry.name), relative + '/');+ else files[relative] = 'sha256:' + createHash('sha256').update(await readFile(join(path, entry.name))).digest('hex');+ }+ }+ await inventory(directory);+ await writeFile(join(directory, 'package-provenance.json'), JSON.stringify({ version: 1, engineVersion: manifest.version, connectorBound: Boolean(appId), files }, null, 2) + '\n');+ return { directory, files: Object.keys(files).length, connectorBound: Boolean(appId) };+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const [destination, appId] = process.argv.slice(2);+ if (!destination) throw new Error('Usage: node scripts/package-plugin.mjs OUTPUT_DIRECTORY [plugin_asdk_app_ID]');+ console.log(JSON.stringify(await packagePlugin(destination, appId), null, 2));+}diff --git a/scripts/plugin-check-output.test.mjs b/scripts/plugin-check-output.test.mjsnew file mode 100644index 00000000..c7b08575--- /dev/null+++ b/scripts/plugin-check-output.test.mjs@@ -0,0 +1,9 @@+import { expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';++test('plugin checks keep stdout available for the package JSON receipt', () => {+ const result = spawnSync('node', ['scripts/test-plugin-package.mjs'], { encoding: 'utf8' });+ expect(result.status).toBe(0);+ expect(result.stdout.trim()).toBe('');+ expect(result.stderr).toContain('Plugin packaging passed');+});diff --git a/scripts/site-indexing.test.mjs b/scripts/site-indexing.test.mjsnew file mode 100644index 00000000..80f597f1--- /dev/null+++ b/scripts/site-indexing.test.mjs@@ -0,0 +1,15 @@+import { expect, test } from 'bun:test';+import { readFile } from 'node:fs/promises';++test('crawler discovery points only to the canonical document, without hash routes', async () => {+ const html = await readFile(new URL('../site/index.html', import.meta.url), 'utf8');+ const sitemap = await readFile(new URL('../site/public/sitemap.xml', import.meta.url), 'utf8');+ const robots = await readFile(new URL('../site/public/robots.txt', import.meta.url), 'utf8');+ expect(html.match(/rel="canonical"/g)).toHaveLength(1);+ expect(html).toContain('<link rel="canonical" href="https://kilnstudio.tools/"');+ expect([...sitemap.matchAll(/<loc>(.*?)<\/loc>/g)].map((match) => match[1])).toEqual(['https://kilnstudio.tools/']);+ expect(robots).toContain('Sitemap: https://kilnstudio.tools/sitemap.xml');+ expect(robots).not.toMatch(/Disallow:\s*\//);+ const index = await readFile(new URL('../site/public/sitemap-index.xml', import.meta.url), 'utf8');+ expect([...index.matchAll(/<loc>(.*?)<\/loc>/g)].map((match) => match[1])).toEqual(['https://kilnstudio.tools/sitemap.xml']);+});diff --git a/scripts/test-plugin-package.mjs b/scripts/test-plugin-package.mjsnew file mode 100644index 00000000..6051dbf0--- /dev/null+++ b/scripts/test-plugin-package.mjs@@ -0,0 +1,23 @@+import { strict as assert } from 'node:assert';+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { packagePlugin } from './package-plugin.mjs';++const root = await mkdtemp(join(tmpdir(), 'kiln-plugin-package-'));+try {+ const result = await packagePlugin(join(root, 'kiln-chatgpt'), 'plugin_asdk_app_test');+ const manifest = JSON.parse(await readFile(join(result.directory, '.codex-plugin/plugin.json')));+ assert.equal(manifest.apps, './.app.json');+ assert.equal(manifest.mcpServers, undefined);+ assert.equal(manifest.name, 'kiln-chatgpt');+ const mapping = JSON.parse(await readFile(join(result.directory, '.app.json')));+ assert.equal(mapping.apps.kiln.id, 'plugin_asdk_app_test');+ assert.match(await readFile(join(result.directory, 'skills/kiln-author-asset/references/program-contract.md'), 'utf8'), /build/);+ await assert.rejects(packagePlugin(result.directory, 'plugin_asdk_app_test'), /exist/i);+ await assert.rejects(packagePlugin(join(root, 'invalid'), 'https://example.com'), /connector ID/);+ assert.ok(result.files > 5);+ console.error('Plugin packaging passed: complete skill references, exact connector binding, no overwrite.');+} finally {+ await rm(root, { recursive: true, force: true });+}diff --git a/site/public/llms.txt b/site/public/llms.txtindex f25e239a..9c61c3d2 100644--- a/site/public/llms.txt+++ b/site/public/llms.txt@@ -8,6 +8,8 @@ Your coding harness supplies the model. The tools do not require a separate mode## Start here- Website and examples: https://kilnstudio.tools/+- ChatGPT connection, interactive chat viewing, skills, and download limits: https://github.com/matthew-kissinger/kiln/blob/main/docs/chatgpt.md+- Saved collections, revisions, local viewer, and editable bundles: https://github.com/matthew-kissinger/kiln/blob/main/docs/collections.md- Repository: https://github.com/matthew-kissinger/kiln- Installation: https://raw.githubusercontent.com/matthew-kissinger/kiln/main/docs/install.md- Project-local setup: https://raw.githubusercontent.com/matthew-kissinger/kiln/main/docs/clean-room.mddiff --git a/site/public/robots.txt b/site/public/robots.txtnew file mode 100644index 00000000..a1994d02--- /dev/null+++ b/site/public/robots.txt@@ -0,0 +1,4 @@+User-agent: *+Allow: /++Sitemap: https://kilnstudio.tools/sitemap.xmldiff --git a/site/public/sitemap-index.xml b/site/public/sitemap-index.xmlnew file mode 100644index 00000000..370fbf0c--- /dev/null+++ b/site/public/sitemap-index.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="UTF-8"?>+<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">+ <sitemap>+ <loc>https://kilnstudio.tools/sitemap.xml</loc>+ </sitemap>+</sitemapindex>diff --git a/site/public/sitemap.xml b/site/public/sitemap.xmlnew file mode 100644index 00000000..3491477b--- /dev/null+++ b/site/public/sitemap.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="UTF-8"?>+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">+ <url>+ <loc>https://kilnstudio.tools/</loc>+ </url>+</urlset>diff --git a/site/src/Home.tsx b/site/src/Home.tsxindex 1d79efab..22ab3085 100644--- a/site/src/Home.tsx+++ b/site/src/Home.tsx@@ -62,6 +62,7 @@ export function Home({ specimens }: { specimens: Specimen[] }) {</a><div><a href="#/gallery">Examples</a>+ <a href="#chat">Chat setup</a><a href={`${DOCS}/install.md`}>Docs</a><a href={REPO}>GitHub ↗</a></div>@@ -95,7 +96,7 @@ export function Home({ specimens }: { specimens: Specimen[] }) {</div></div><div className="capability-strip">- <span>Local CLI + MCP</span>+ <span>CLI + MCP + chat viewer</span><span>Editable JavaScript</span><span>Named parts & materials</span><span>GLB export · MIT</span>@@ -384,6 +385,47 @@ cd ../my-assets</section></div></section>+ <section className="band setup-section" aria-labelledby="chat">+ <div className="section-heading">+ <div>+ <p className="eyebrow">Kiln in your chat client</p>+ <h2 id="chat">Make it. Save it. Turn it around in chat.</h2>+ </div>+ <a href={`${DOCS}/chatgpt.md`}>ChatGPT setup guide →</a>+ </div>+ <div className="setup-grid">+ <section className="setup-card" aria-labelledby="chat-connect">+ <h3 id="chat-connect">Connect once, then ask for an asset</h3>+ <p>+ Connect Kiln's local MCP server to ChatGPT through a private Secure MCP Tunnel.+ Install the authoring and refinement skills with their reference files, then select+ Kiln in your chat. This currently requires developer setup.+ </p>+ <Code>{`Make a field recorder.+Review the renders and save it+to my project collection.+Show it with kiln_present.`}</Code>+ <p>+ Supporting MCP App clients show an interactive 3D card. ChatGPT viewing has been+ verified with real saved assets and orbit controls.+ </p>+ </section>+ <section className="setup-card" aria-labelledby="chat-keep">+ <h3 id="chat-keep">Keep a collection you can refine</h3>+ <p>+ Save the GLB alongside its source, build records, and revision history. Open your+ project collection or personal library in the local viewer to browse, compare+ revisions, and download a GLB or editable ZIP bundle.+ </p>+ <Code>{`node kiln.mjs view`}</Code>+ <p>+ ChatGPT-native GLB and ZIP attachments remain unverified. Downloads in chat depend on+ the client's file support or a host-provided delivery link.+ </p>+ <a href={`${DOCS}/collections.md`}>Collections, downloads, and source provenance →</a>+ </section>+ </div>+ </section><section className="band fit-section"><div><p className="eyebrow">Built for iteration</p>diff --git a/skills/kiln-author-asset/SKILL.md b/skills/kiln-author-asset/SKILL.mdindex 34e7d4de..b7bb7a7c 100644--- a/skills/kiln-author-asset/SKILL.md+++ b/skills/kiln-author-asset/SKILL.md@@ -28,7 +28,11 @@ Inspect the actual images. Check silhouette, proportion, orientation, attachmentRead a bounded source region with `kiln_source({ programRef, query: "dimensionOrPart" })`. Copy an exact anchor into `kiln_edit`, batch related replacements, and continue with its new `programRef`. Rendering is on by default; `capture` can keep the relevant framing. An applied edit can still fail to build, so inspect `render.ok` separately.-Save the final reference without model transcription:+When the collection tools are available, save completed work with `kiln_save({ programRef, name, collection: "project", brief, description })`. Use `kiln_assets({ action: "collections" })` to discover other configured destinations. Record only known model/harness attribution. Saving returns the asset ID, revision ID, and download resources for its exact GLB, source, and ZIP bundle. Return those links to the user using the host's resource/download interface; do not transcribe binary data. The local viewer opens with `node kiln.mjs view`.++If `kiln_present` is available, call it with the saved collection, asset ID, and revision ID to show the interactive viewer. Use returned download URLs when provided; never invent HTTPS URLs or claim that a host supports native attachments without evidence. A `kiln://` resource may require the host's resource reader or local viewer.++Save at meaningful completion points, not after each draft or camera change. Retain source revisions while working. For direct filesystem exports without collection tools:```shnode kiln.mjs source RETURNED_REF --out asset-v1.kiln.jsdiff --git a/skills/kiln-refine-asset/SKILL.md b/skills/kiln-refine-asset/SKILL.mdindex 6ac6ff8b..c694c925 100644--- a/skills/kiln-refine-asset/SKILL.md+++ b/skills/kiln-refine-asset/SKILL.md@@ -8,8 +8,14 @@ license: MITWork from the saved program. A GLB alone does not contain editable Kiln JavaScript. Keep the user's requested change distinct from unrelated redesign.+For a collection asset, first call `kiln_assets` with `action: "restore"`, `collection`, `assetId`, and `revisionId`. This imports its exact source into the current program store and returns a fresh `programRef`. A downloaded ZIP can be imported with `node kiln.mjs import bundle.zip`. A binary-only GLB has no source to restore.++After reviewing the change, use `kiln_save` with the new `programRef`, the original `assetId`, and `parentRevision` set to the revision you started from. Preserve the collection, name, and relevant tags; describe the change. Return the new revision's download resources. Prior revisions remain intact; copying to a different collection does not make a live link.+## Read, change, compare+After saving the reviewed child revision, call `kiln_present` when available with its exact collection, asset ID, and revision ID. This opens an interactive view in supporting chat hosts. Return actual download URLs when supplied; do not invent links or assume `kiln://` resources are native chat attachments.+1. Copy the returned `programRef` exactly, or import a file with `node kiln.mjs source asset.kiln.js`. Built-in stores return short immutable handles such as `p_7c94a132b8e0`; full SHA-256 references also work. Do not shorten a hash yourself. Submit source inline only when introducing a new draft to the store.2. Obtain a before view when it resolves an uncertainty. Use returned exact part paths for targeted framing; the [revision and view recipes](references/revision-and-views.md) show source paging, custom cameras, and animation phases.3. Read relevant text with `kiln_source({ programRef, query: "partOrConstant" })`. Search is literal and offsets count UTF-16 characters. Copy anchors exactly, including whitespace.diff --git a/src/__tests__/mcp-payload.test.ts b/src/__tests__/mcp-payload.test.tsindex 5e6c4183..bf001f94 100644--- a/src/__tests__/mcp-payload.test.ts+++ b/src/__tests__/mcp-payload.test.ts@@ -146,9 +146,10 @@ describe('always-on context cost', () => {it('the tool schemas stay within the context budget', async () => {const chars = schemaChars();- // A budget, not a target: several tools' worth of headroom before anyone- // has to think about it again.- expect(chars).toBeLessThan(24 * 1024);+ // Collections add four explicit verbs without changing cached authoring schemas.+ // Measured full public surface: ~28 KiB, up from ~24 KiB before collections.+ // Keep the expanded surface bounded; this is context cost, not a coverage gate.+ expect(chars).toBeLessThan(30 * 1024);});it('skill discovery stays within the context budget', async () => {diff --git a/src/agent/index.ts b/src/agent/index.tsindex 57bd5ab0..c5203c1f 100644--- a/src/agent/index.ts+++ b/src/agent/index.ts@@ -49,6 +49,7 @@ export type {export {makeKilnTools,+ makeKilnProgramTools,makeKilnEditTools,makeKilnUnifiedTools,KilnDraftBuffer,diff --git a/src/agent/tools.ts b/src/agent/tools.tsindex aa90c060..dd46d263 100644--- a/src/agent/tools.ts+++ b/src/agent/tools.ts@@ -24,6 +24,7 @@ import { ViewEvidenceHistoryStore } from '../views/evidence-history';import {createKilnToolRegistry,+ createKilnProgramToolRegistry,createKilnInspectDef,createKilnRenderViewsDef,createKilnScreenshotAnimationDef,@@ -163,6 +164,13 @@ function toStrandsTool(def: KilnToolDef, context: KilnToolContext = {}): Tool {});}+/** Reference-based authoring and collections, identical to MCP, plus explicit submit. */+export function makeKilnProgramTools(sink: SubmitSink, context: KilnToolContext = {}): Tool[] {+ const definitions = createKilnProgramToolRegistry(context);+ const submit = makeKilnTools(sink, context).find((t) => t.name === KILN_SUBMIT_TOOL_NAME)!;+ return [...definitions.map((def) => toStrandsTool(def, context)), submit];+}+/*** Build the in-process tool list for an agent: the kiln registry tools* (list_primitives / validate / render / screenshot) plus the terminaldiff --git a/src/asset-cli.test.ts b/src/asset-cli.test.tsnew file mode 100644index 00000000..8229f6fb--- /dev/null+++ b/src/asset-cli.test.ts@@ -0,0 +1,50 @@+import { expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { tmpdir } from 'node:os';+import { decodeAssetBundle } from './assets';++test('CLI saves, exports, imports, and restores a revision across independent stores', async () => {+ const root = await mkdtemp(join(tmpdir(), 'kiln-asset-cli-'));+ const cli = resolve('src/cli.ts');+ const run = (workspace: string, args: string[]) =>+ spawnSync(process.execPath, [cli, ...args], {+ cwd: root,+ env: {+ ...process.env,+ KILN_RENDER: 'cpu',+ KILN_EVALUATOR_MODE: 'in-process',+ KILN_PROGRAM_STORE: join(root, workspace, '.kiln', 'programs'),+ KILN_COLLECTIONS: JSON.stringify({ project: join(root, workspace, 'collection') }),+ },+ encoding: 'utf8',+ windowsHide: true,+ });+ try {+ const saved = run('first', [+ 'save',+ resolve('examples/crate.kiln.js'),+ '--name',+ 'Crate',+ '--render',+ 'cpu',+ ]);+ expect(saved.status).toBe(0);+ const asset = JSON.parse(saved.stdout).asset;+ const file = join(root, 'crate.zip');+ expect(run('first', ['export', asset.assetId, asset.revisionId, '--out', file]).status).toBe(0);+ expect(run('first', ['export', asset.assetId, asset.revisionId, '--out', file]).status).toBe(1);+ expect(decodeAssetBundle(new Uint8Array(await readFile(file)))[0]!.manifest.revisionId).toBe(+ asset.revisionId,+ );+ expect(run('second', ['import', file]).status).toBe(0);+ const restored = run('second', ['asset', asset.assetId, asset.revisionId, '--restore']);+ expect(restored.status).toBe(0);+ expect(JSON.parse(restored.stdout).programRef).toMatch(/^p_/);+ expect(run('second', ['import', file]).status).toBe(0);+ expect(JSON.parse(run('second', ['assets']).stdout).assets.length).toBe(1);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+}, 30000);diff --git a/src/asset-cli.ts b/src/asset-cli.tsnew file mode 100644index 00000000..21623752--- /dev/null+++ b/src/asset-cli.ts@@ -0,0 +1,187 @@+import { readFile, writeFile, stat, mkdir, rename } from 'node:fs/promises';+import { basename, resolve, dirname } from 'node:path';+import { randomUUID } from 'node:crypto';+import { localAssetLibrary, collectionConfigPath } from './assets-node';+import { ASSET_LIMIT, assetIdSchema, decodeAssetBundle, encodeAssetBundle } from './assets';+import { localProgramStore } from './program-store-node';+import { programRefPattern, retainProgram } from './program-store';+import { createKilnProgramToolRegistry } from './tools/registry';+import { createPackagedLocalToolContext } from './local-runtime';+import { buildRenderPort, resolveRenderMode } from './cli-render-mode';+import { startAssetViewer } from './asset-viewer';++export const ASSET_USAGE = `+ASSETS & VIEWER+ kiln save <source.js|programRef> --name <name> [--collection project]+ [--asset <id> --parent <revision>] [--description <text>] [--tag <tag>]+ kiln collections list configured collection names+ kiln collections add <name> <directory> remember a project or personal collection+ kiln assets [--collection project] list saved revisions (JSON)+ kiln asset <id> <revision> [--collection project] [--restore]+ kiln export <id> <revision> --out asset.zip [--format bundle|glb|source]+ kiln import <asset.zip|asset.glb> [--collection project] [--name <name>]+ kiln view [collection-directory|asset.glb|asset.zip] [--port 4318]++KILN_COLLECTIONS is an optional JSON map of collection names to absolute folders.+Default: project -> <workspace>/assets/kiln. Existing source/render commands still work.+View prints a local browser URL and remains running until interrupted.+`;+export async function assetMain(argv: readonly string[]): Promise<number> {+ const command = argv[0];+ const positional: string[] = [];+ const flags: Record<string, string> = {};+ const tags: string[] = [];+ const allowed = new Set([+ 'collection',+ 'name',+ 'asset',+ 'parent',+ 'description',+ 'brief',+ 'tag',+ 'out',+ 'format',+ 'port',+ 'render',+ ]);+ for (let i = 1; i < argv.length; i++) {+ const arg = argv[i]!;+ if (arg === '--help' || arg === '-h') {+ console.log(ASSET_USAGE);+ return 0;+ }+ if (arg === '--restore') {+ flags.restore = 'true';+ continue;+ }+ if (arg.startsWith('--')) {+ const key = arg.slice(2);+ const value = argv[++i];+ if (!allowed.has(key) || value === undefined) throw new Error(`Invalid option ${arg}`);+ if (key === 'tag') tags.push(value);+ else flags[key] = value;+ } else positional.push(arg);+ }+ const library = localAssetLibrary();+ const collection = flags.collection ?? 'project';+ const fileBytes = async (path: string) => {+ if ((await stat(path)).size > ASSET_LIMIT) throw new Error('File exceeds 64 MiB');+ return new Uint8Array(await readFile(path));+ };+ if (command === 'collections') {+ if (positional[0] === 'add') {+ if (process.env.KILN_COLLECTIONS)+ throw new Error(+ 'KILN_COLLECTIONS overrides saved configuration. Unset it before changing workspace collections.',+ );+ const [, name, directory] = positional;+ if (!name || !directory) throw new Error('collections add requires name and directory');+ assetIdSchema.parse(name);+ const roots = Object.fromEntries(+ library.collections().map((c) => [c.id, library.directory(c.id)]),+ );+ if (roots[name] && roots[name] !== resolve(directory))+ throw new Error('Collection name already points to another directory');+ roots[name] = resolve(directory);+ const path = collectionConfigPath();+ await mkdir(dirname(path), { recursive: true });+ const temporary = `${path}.${randomUUID()}.tmp`;+ await writeFile(temporary, JSON.stringify(roots, null, 2), { flag: 'wx' });+ await rename(temporary, path);+ console.log(+ `Collection ${name}: ${roots[name]}. Restart running MCP/viewer processes to load it.`,+ );+ } else console.log(JSON.stringify({ collections: library.collections() }, null, 2));+ } else if (command === 'assets')+ console.log(JSON.stringify({ assets: await library.list(collection) }, null, 2));+ else if (command === 'save') {+ const input = positional[0];+ if (!input || !flags.name) throw new Error('save requires source/ref and --name');+ const store = localProgramStore();+ const programRef = programRefPattern.test(input)+ ? input+ : await retainProgram(store, new TextDecoder().decode(await fileBytes(input)));+ const context = await createPackagedLocalToolContext(+ await buildRenderPort(resolveRenderMode(flags.render ?? 'auto'), undefined),+ );+ const def = createKilnProgramToolRegistry({+ ...context,+ assetLibrary: library,+ programStore: store,+ }).find((d) => d.name === 'kiln_save')!;+ console.log(+ JSON.stringify(+ await def.run({+ collection,+ programRef,+ name: flags.name,+ assetId: flags.asset,+ parentRevision: flags.parent,+ description: flags.description,+ brief: flags.brief,+ tags,+ }),+ null,+ 2,+ ),+ );+ } else if (command === 'asset' || command === 'export') {+ const [assetId, revisionId] = positional;+ if (!assetId || !revisionId) throw new Error(`${command} requires asset ID and revision ID`);+ const record = await library.read(collection, assetId, revisionId);+ if (command === 'asset') {+ if (flags.restore) {+ const source = record.files['source.kiln.js'];+ if (!source) throw new Error('Source unavailable');+ console.log(+ JSON.stringify(+ {+ asset: record.manifest,+ programRef: await retainProgram(+ localProgramStore(),+ new TextDecoder().decode(source),+ ),+ },+ null,+ 2,+ ),+ );+ } else console.log(JSON.stringify(record.manifest, null, 2));+ } else {+ if (!flags.out) throw new Error('export requires --out');+ const format = flags.format ?? 'bundle';+ if (!['bundle', 'glb', 'source'].includes(format)) throw new Error('Unknown export format');+ const bytes =+ format === 'bundle'+ ? encodeAssetBundle([record])+ : record.files[format === 'glb' ? 'asset.glb' : 'source.kiln.js'];+ if (!bytes) throw new Error('Source unavailable');+ await writeFile(resolve(flags.out), bytes, { flag: 'wx' });+ console.log(`Saved ${resolve(flags.out)}`);+ }+ } else if (command === 'import') {+ const file = positional[0];+ if (!file) throw new Error('import requires a ZIP or GLB file');+ const bytes = await fileBytes(file);+ const assets = file.toLowerCase().endsWith('.glb')+ ? [await library.save(collection, { name: flags.name ?? basename(file, '.glb'), glb: bytes })]+ : await library.import(collection, decodeAssetBundle(bytes));+ console.log(JSON.stringify({ collection, assets }, null, 2));+ } else if (command === 'view') {+ let target = library;+ let standalone: { name: string; bytes: Uint8Array } | undefined;+ const file = positional[0];+ if (file) {+ if ((await stat(file)).isDirectory()) {+ const { FileAssetLibrary } = await import('./assets-node');+ target = new FileAssetLibrary({ project: resolve(file) });+ } else standalone = { name: basename(file), bytes: await fileBytes(file) };+ }+ const port = flags.port === undefined ? 4318 : Number(flags.port);+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Invalid port');+ const viewer = await startAssetViewer(target, { port, standalone });+ console.log(`${viewer.url}${standalone ? '?open=standalone' : ''}`);+ console.log('Kiln viewer · local files · Ctrl+C to stop');+ }+ return 0;+}diff --git a/src/asset-viewer.test.ts b/src/asset-viewer.test.tsnew file mode 100644index 00000000..6d0b7034--- /dev/null+++ b/src/asset-viewer.test.ts@@ -0,0 +1,26 @@+import { expect, test } from 'bun:test';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { FileAssetLibrary } from './assets-node';+import { startAssetViewer } from './asset-viewer';++test('viewer serves only configured collections and rejects cross-origin writes and unknown files', async () => {+ const root = await mkdtemp(join(tmpdir(), 'kiln-viewer-'));+ const viewer = await startAssetViewer(new FileAssetLibrary({ project: root }), { port: 0 });+ try {+ const response = await fetch(`${viewer.url}api/collections`);+ expect(await response.json()).toEqual({ collections: [{ id: 'project', label: 'project' }] });+ expect((await fetch(`${viewer.url}api/assets?collection=project`)).status).toBe(200);+ expect((await fetch(`${viewer.url}api/assets?collection=unknown`)).status).toBe(400);+ expect((await fetch(`${viewer.url}package.json`)).status).toBe(404);+ expect(+ (await fetch(`${viewer.url}api/collections`, { headers: { Origin: 'https://example.com' } }))+ .status,+ ).toBe(403);+ expect((await fetch(`${viewer.url}api/collections`, { method: 'POST' })).status).toBe(405);+ } finally {+ await viewer.close();+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/src/asset-viewer.ts b/src/asset-viewer.tsnew file mode 100644index 00000000..17237674--- /dev/null+++ b/src/asset-viewer.ts@@ -0,0 +1,116 @@+/** Read-only loopback host. Only configured collection resources are routable. */+import { createServer } from 'node:http';+import { readFile } from 'node:fs/promises';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { encodeAssetBundle, type AssetLibrary } from './assets';+import { readAssetResource } from './assets-resources';++export async function startAssetViewer(+ library: AssetLibrary,+ options: {+ port?: number;+ staticDirectory?: string;+ standalone?: { name: string; bytes: Uint8Array };+ } = {},+) {+ const staticDirectory =+ options.staticDirectory ??+ (import.meta.url.endsWith('.ts')+ ? join(dirname(fileURLToPath(import.meta.url)), '..', 'dist', 'viewer')+ : join(dirname(fileURLToPath(import.meta.url)), 'viewer'));+ const server = createServer(async (req, res) => {+ res.setHeader('X-Content-Type-Options', 'nosniff');+ res.setHeader('Referrer-Policy', 'no-referrer');+ res.setHeader('Cache-Control', 'no-store');+ const address = server.address();+ const origin = `http://127.0.0.1:${typeof address === 'object' && address ? address.port : 0}`;+ if (+ req.headers.host !== origin.slice(7) ||+ (req.headers.origin && req.headers.origin !== origin)+ ) {+ res.writeHead(403);+ res.end('Forbidden origin');+ return;+ }+ if (req.method !== 'GET' && req.method !== 'HEAD') {+ res.writeHead(405);+ res.end('Read-only viewer');+ return;+ }+ const send = (bytes: Uint8Array | string, mime = 'application/json', name?: string) => {+ res.setHeader('Content-Type', mime);+ if (name) res.setHeader('Content-Disposition', `attachment; filename="${name}"`);+ res.end(req.method === 'HEAD' ? undefined : bytes);+ };+ try {+ const url = new URL(req.url ?? '/', origin);+ if (url.pathname === '/api/collections')+ return send(JSON.stringify({ collections: library.collections() }));+ if (url.pathname === '/api/assets')+ return send(+ JSON.stringify({+ assets: await library.list(url.searchParams.get('collection') ?? 'project'),+ }),+ );+ if (url.pathname === '/api/standalone' && options.standalone)+ return send(+ options.standalone.bytes,+ options.standalone.name.endsWith('.zip') ? 'application/zip' : 'model/gltf-binary',+ );+ if (url.pathname === '/api/bundle') {+ const selected = url.searchParams.getAll('revision');+ if (!selected.length || selected.length > 100) throw new Error('Select 1..100 revisions');+ const records = await Promise.all(+ selected.map((value) => {+ const [collection, asset, revision, extra] = value.split('/');+ if (!collection || !asset || !revision || extra) throw new Error('Invalid revision');+ return library.read(collection, asset, revision);+ }),+ );+ return send(encodeAssetBundle(records), 'application/zip', 'kiln-assets.zip');+ }+ if (url.pathname.startsWith('/files/')) {+ const file = await readAssetResource(library, `kiln://assets/${url.pathname.slice(7)}`);+ return send(+ file.bytes,+ file.mimeType,+ url.searchParams.has('download') ? file.name : undefined,+ );+ }+ const staticFiles: Record<string, [string, string]> = {+ '/': ['index.html', 'text/html; charset=utf-8'],+ '/app.js': ['app.js', 'text/javascript'],+ '/style.css': ['style.css', 'text/css'],+ };+ const file = staticFiles[url.pathname];+ if (!file) {+ res.writeHead(404);+ res.end('Not found');+ return;+ }+ res.setHeader(+ 'Content-Security-Policy',+ "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self' blob: data:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",+ );+ return send(await readFile(join(staticDirectory, file[0])), file[1]);+ } catch (error) {+ res.statusCode = 400;+ send(JSON.stringify({ error: error instanceof Error ? error.message : 'Asset unavailable' }));+ }+ });+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(options.port ?? 4318, '127.0.0.1', resolve);+ });+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Viewer did not bind');+ return {+ url: `http://127.0.0.1:${address.port}/`,+ close: () =>+ new Promise<void>((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()));+ server.closeAllConnections();+ }),+ };+}diff --git a/src/asset-widget.ts b/src/asset-widget.tsnew file mode 100644index 00000000..ca0f86f5--- /dev/null+++ b/src/asset-widget.ts@@ -0,0 +1,39 @@+/** MCP-only presentation payload; binary files never enter model-facing tool text. */+import { readFile } from 'node:fs/promises';+import type { AssetLibrary } from './assets';++export async function assetWidgetData(+ library: AssetLibrary,+ selector: {+ collection: string;+ downloadUrls?: Record<string, string>;+ asset: { assetId: string; revisionId: string };+ },+): Promise<Record<string, unknown>> {+ const record = await library.read(+ selector.collection,+ selector.asset.assetId,+ selector.asset.revisionId,+ );+ if (Object.values(record.files).reduce((sum, bytes) => sum + bytes.length, 0) > 16 * 1024 * 1024)+ return {+ kilnAsset: {+ error: 'This asset exceeds the 16 MiB chat preview limit. Open it with kiln view.',+ },+ };+ return {+ kilnAsset: {+ manifest: record.manifest,+ downloadUrls: selector.downloadUrls,+ files: Object.fromEntries(+ Object.entries(record.files).map(([name, bytes]) => [+ name,+ Buffer.from(bytes).toString('base64'),+ ]),+ ),+ },+ };+}+export async function readAssetWidgetHtml(): Promise<string> {+ return readFile(new URL('../dist/viewer/chat.html', import.meta.url), 'utf8');+}diff --git a/src/assets-node.ts b/src/assets-node.tsnew file mode 100644index 00000000..4ef60dcf--- /dev/null+++ b/src/assets-node.ts@@ -0,0 +1,218 @@+/** Local durable collections; immutable revisions become visible by directory rename. */+import { createHash, randomUUID } from 'node:crypto';+import { readFileSync, type Dirent } from 'node:fs';+import { lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';+import { dirname, join, relative, resolve, sep } from 'node:path';+import {+ assetIdSchema,+ assetManifestSchema,+ ASSET_LIMIT,+ validateRecordShape,+ type AssetDraft,+ type AssetLibrary,+ type AssetManifest,+ type AssetRecord,+} from './assets';++const digest = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+export async function verifyAssetRecord(record: AssetRecord): Promise<void> {+ for (const [name, info] of Object.entries(record.manifest.files)) {+ const bytes = record.files[name];+ if (!bytes || bytes.length !== info.bytes || digest(bytes) !== info.sha256)+ throw new Error(`Asset integrity failure: ${name}`);+ }+ validateRecordShape(record);+}+export class FileAssetLibrary implements AssetLibrary {+ private readonly roots: Record<string, string>;+ constructor(roots: Record<string, string>) {+ if (!Object.keys(roots).length) throw new Error('Configure at least one collection');+ this.roots = Object.fromEntries(+ Object.entries(roots).map(([id, path]) => [assetIdSchema.parse(id), resolve(path)]),+ );+ }+ collections() {+ return Object.keys(this.roots).map((id) => ({ id, label: id }));+ }+ directory(collection: string): string {+ const root = this.roots[collection];+ if (!root || !Object.hasOwn(this.roots, collection)) throw new Error('Unknown collection');+ return root;+ }+ private async path(collection: string, ...parts: string[]): Promise<string> {+ const root = this.directory(collection);+ await mkdir(root, { recursive: true });+ const canonical = await realpath(root);+ let path = root;+ for (const part of parts) {+ assetIdSchema.parse(part);+ path = join(path, part);+ try {+ const entry = await lstat(path);+ if (entry.isSymbolicLink()) throw new Error('Collection symlinks are not supported');+ const rel = relative(canonical, await realpath(path));+ if (rel === '..' || rel.startsWith(`..${sep}`))+ throw new Error('Collection path escapes root');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ }+ return path;+ }+ async list(collection: string): Promise<AssetManifest[]> {+ const root = await this.path(collection);+ const records: AssetManifest[] = [];+ for (const asset of await readdir(root, { withFileTypes: true })) {+ if (!asset.isDirectory() || !assetIdSchema.safeParse(asset.name).success) continue;+ const revisions = await this.path(collection, asset.name, 'revisions');+ let entries: Dirent[];+ try {+ entries = await readdir(revisions, { withFileTypes: true });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw error;+ }+ for (const revision of entries) {+ if (!revision.isDirectory() || !revision.name.startsWith('r_')) continue;+ const dir = await this.path(collection, asset.name, 'revisions', revision.name);+ const manifest = assetManifestSchema.parse(+ JSON.parse(new TextDecoder().decode(await this.file(dir, 'manifest.json', 1024 * 1024))),+ );+ if (manifest.assetId !== asset.name || manifest.revisionId !== revision.name)+ throw new Error('Asset identity mismatch');+ records.push(manifest);+ }+ }+ return records.sort(+ (a, b) => b.createdAt.localeCompare(a.createdAt) || a.revisionId.localeCompare(b.revisionId),+ );+ }+ private async file(dir: string, name: string, limit = ASSET_LIMIT): Promise<Uint8Array> {+ const path = join(dir, name);+ const info = await lstat(path);+ if (!info.isFile() || info.isSymbolicLink() || info.size > limit)+ throw new Error('Invalid collection file');+ return new Uint8Array(await readFile(path));+ }+ async read(collection: string, assetId: string, revisionId: string): Promise<AssetRecord> {+ const dir = await this.path(collection, assetId, 'revisions', revisionId);+ const manifest = assetManifestSchema.parse(+ JSON.parse(new TextDecoder().decode(await this.file(dir, 'manifest.json', 1024 * 1024))),+ );+ if (manifest.assetId !== assetId || manifest.revisionId !== revisionId)+ throw new Error('Asset identity mismatch');+ const files: Record<string, Uint8Array> = {};+ for (const name of Object.keys(manifest.files)) {+ if (!['asset.glb', 'source.kiln.js', 'preview.png'].includes(name))+ throw new Error('Invalid collection filename');+ files[name] = await this.file(dir, name);+ }+ const record = { manifest, files };+ await verifyAssetRecord(record);+ return record;+ }+ async save(collection: string, draft: AssetDraft): Promise<AssetManifest> {+ const assetId = draft.assetId ?? `a_${randomUUID().replaceAll('-', '')}`;+ if (draft.parentRevision) await this.read(collection, assetId, draft.parentRevision);+ if (+ draft.assetId &&+ !draft.parentRevision &&+ (await this.list(collection)).some((m) => m.assetId === assetId)+ )+ throw new Error('An existing asset requires parentRevision');+ 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 manifest: AssetManifest = assetManifestSchema.parse({+ version: 'kiln.asset.v1',+ assetId,+ revisionId: `r_${randomUUID().replaceAll('-', '')}`,+ parentRevision: draft.parentRevision,+ name: draft.name,+ tags: draft.tags ?? [],+ createdAt: new Date().toISOString(),+ brief: draft.brief,+ description: draft.description,+ attribution: draft.attribution,+ editable: draft.code !== undefined,+ files: Object.fromEntries(+ Object.entries(files).map(([name, bytes]) => [+ name,+ { sha256: digest(bytes), bytes: bytes.length },+ ]),+ ),+ build: draft.build+ ? { ...draft.build, rebuild: draft.build.rebuild ?? 'engine-required' }+ : undefined,+ preview: draft.previewInfo,+ });+ await this.import(collection, [{ manifest, files }]);+ return manifest;+ }+ async import(collection: string, records: AssetRecord[]): Promise<AssetManifest[]> {+ if (!records.length || records.length > 100)+ throw new Error('Import requires 1..100 revisions');+ // Validate the whole input before writing anything; per-revision commits are atomic.+ for (const record of records) await verifyAssetRecord(record);+ for (const record of records) {+ const { manifest, files } = record;+ const dest = await this.path(collection, manifest.assetId, 'revisions', manifest.revisionId);+ const parent = dirname(dest);+ await mkdir(parent, { recursive: true });+ const stage = join(parent, `.write-${randomUUID()}`);+ await mkdir(stage);+ try {+ for (const [name, bytes] of Object.entries(files))+ await writeFile(join(stage, name), bytes, { flag: 'wx' });+ await writeFile(join(stage, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, {+ flag: 'wx',+ });+ try {+ await rename(stage, dest);+ } catch (error) {+ const existing = await this.read(collection, manifest.assetId, manifest.revisionId).catch(+ () => undefined,+ );+ if (!existing || JSON.stringify(existing.manifest) !== JSON.stringify(manifest))+ throw error;+ }+ } finally {+ await rm(stage, { recursive: true, force: true });+ }+ }+ return records.map((r) => r.manifest);+ }+}+export function collectionConfigPath(+ env: Record<string, string | undefined> = process.env,+): string {+ const workspace = env.KILN_PROGRAM_STORE+ ? dirname(dirname(resolve(env.KILN_PROGRAM_STORE)))+ : process.cwd();+ return join(workspace, '.kiln', 'collections.json');+}+export function localAssetLibrary(+ env: Record<string, string | undefined> = process.env,+): FileAssetLibrary {+ if (env.KILN_COLLECTIONS) {+ const value = JSON.parse(env.KILN_COLLECTIONS);+ if (+ !value ||+ typeof value !== 'object' ||+ Array.isArray(value) ||+ Object.values(value).some((v) => typeof v !== 'string' || !v)+ )+ throw new Error('KILN_COLLECTIONS must map collection names to directories');+ return new FileAssetLibrary(value);+ }+ const config = collectionConfigPath(env);+ try {+ const text = readFileSync(config, 'utf8');+ if (!text.trim()) throw new Error('Collection configuration is empty');+ return localAssetLibrary({ ...env, KILN_COLLECTIONS: text });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ const workspace = dirname(dirname(config));+ return new FileAssetLibrary({ project: join(workspace, 'assets', 'kiln') });+}diff --git a/src/assets-resources.ts b/src/assets-resources.tsnew file mode 100644index 00000000..04abf51e--- /dev/null+++ b/src/assets-resources.ts@@ -0,0 +1,50 @@+import { encodeAssetBundle, type AssetLibrary, type AssetManifest } from './assets';++export interface AssetLink {+ type: 'resource_link';+ name: string;+ uri: string;+ mimeType: string;+}+export function assetLinks(collection: string, manifest: AssetManifest): AssetLink[] {+ return [...Object.keys(manifest.files), 'manifest.json', 'editable.zip'].map((name) => ({+ type: 'resource_link',+ name,+ uri: `kiln://assets/${collection}/${manifest.assetId}/${manifest.revisionId}/${name}`,+ mimeType: assetMime(name),+ }));+}+export function assetMime(name: string): string {+ return name.endsWith('.glb')+ ? 'model/gltf-binary'+ : name.endsWith('.png')+ ? 'image/png'+ : name.endsWith('.zip')+ ? 'application/zip'+ : name.endsWith('.json')+ ? 'application/json'+ : 'text/javascript';+}+export async function readAssetResource(+ library: AssetLibrary,+ uri: string,+): Promise<{ bytes: Uint8Array; mimeType: string; name: string }> {+ const match =+ /^kiln:\/\/assets\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/(asset\.glb|source\.kiln\.js|preview\.png|manifest\.json|editable\.zip)$/.exec(+ uri,+ );+ if (!match) throw new Error('Unknown asset resource');+ const collection = match[1]!;+ const asset = match[2]!;+ const revision = match[3]!;+ const name = match[4]!;+ const record = await library.read(collection, asset, revision);+ const bytes =+ name === 'editable.zip'+ ? encodeAssetBundle([record])+ : name === 'manifest.json'+ ? new TextEncoder().encode(JSON.stringify(record.manifest, null, 2))+ : record.files[name];+ if (!bytes) throw new Error('Asset file unavailable');+ return { bytes, mimeType: assetMime(name), name };+}diff --git a/src/assets-tools.test.ts b/src/assets-tools.test.tsnew file mode 100644index 00000000..d081bfa5--- /dev/null+++ b/src/assets-tools.test.ts@@ -0,0 +1,117 @@+import { expect, test } from 'bun:test';+import { mkdtemp, rm } from 'node:fs/promises';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { Client, InMemoryTransport } from '@modelcontextprotocol/client';+import { createKilnMcpServer } from './mcp-server';+import { FileAssetLibrary } from './assets-node';+import { MemoryProgramStore, retainProgram } from './program-store';+import { createKilnProgramToolRegistry } from './tools/registry';++test('MCP saves an editable revision, exposes exact downloadable bytes, and restores source in a new session', async () => {+ const root = await mkdtemp(join(tmpdir(), 'kiln-asset-tools-'));+ const assetLibrary = new FileAssetLibrary({+ project: root,+ library: join(root, 'personal'),+ });+ 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; }";+ const programRef = await retainProgram(programStore, code);+ const server = createKilnMcpServer({+ programStore,+ assetLibrary,+ assetDownloadUrls: async () => ({ 'asset.glb': 'https://example.com/asset.glb' }),+ });+ const client = new Client({ name: 'asset-test', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await Promise.all([client.connect(ct), server.connect(st)]);+ try {+ const definitions = await client.listTools();+ const presentation = definitions.tools.find((tool) => tool.name === 'kiln_present')!;+ expect(presentation.outputSchema).toBeDefined();+ expect(presentation._meta?.ui).toBeDefined();+ const result = await client.callTool({+ name: 'kiln_save',+ arguments: { programRef, name: 'Box' },+ });+ expect(result.isError).not.toBe(true);+ const content = result.content as {+ type: string;+ text?: string;+ uri?: string;+ }[];+ const data = JSON.parse(content.find((b) => b.type === 'text')!.text!);+ expect(data.asset.editable).toBe(true);+ const present = await client.callTool({+ name: 'kiln_present',+ arguments: {+ collection: 'project',+ assetId: data.asset.assetId,+ revisionId: data.asset.revisionId,+ },+ });+ expect(present.isError).not.toBe(true);+ expect(JSON.stringify(present.content).length).toBeLessThan(6000);+ expect((present.structuredContent as { asset?: unknown })?.asset).toBeDefined();+ const widget = present._meta?.kilnAsset as {+ files?: Record<string, string>;+ downloadUrls?: Record<string, string>;+ };+ expect(widget.downloadUrls?.['asset.glb']).toBe('https://example.com/asset.glb');+ expect(widget.files?.['asset.glb']).toBeDefined();+ expect(JSON.stringify(present.content)).not.toContain(widget.files!['asset.glb']!);+ const sourceLink = content.find((b) => b.uri?.endsWith('/source.kiln.js'))!;+ expect(sourceLink).toBeDefined();+ const source = await client.readResource({ uri: sourceLink.uri! });+ expect('text' in source.contents[0]! ? source.contents[0].text : undefined).toBe(code);+ const fresh = new MemoryProgramStore();+ const defs = createKilnProgramToolRegistry({+ programStore: fresh,+ assetLibrary,+ });+ const restored = (await defs+ .find((d) => d.name === 'kiln_assets')!+ .run({+ action: 'restore',+ collection: 'project',+ assetId: data.asset.assetId,+ revisionId: data.asset.revisionId,+ })) as { programRef: string };+ expect(await fresh.get(restored.programRef)).toBe(code);+ const copy = (await defs+ .find((d) => d.name === 'kiln_import')!+ .run({+ sourceCollection: 'project',+ collection: 'library',+ assetId: data.asset.assetId,+ revisionId: data.asset.revisionId,+ })) as { asset: { revisionId: string } };+ expect(copy.asset.revisionId).toBe(data.asset.revisionId);+ // Large provenance belongs in a downloadable manifest, not every tool reply.+ const record = await assetLibrary.read('project', data.asset.assetId, data.asset.revisionId);+ const verbose = await assetLibrary.save('project', {+ name: 'Verbose',+ code,+ glb: record.files['asset.glb']!,+ build: {+ engine: 'test',+ options: {},+ warnings: [],+ integration: { details: 'x'.repeat(50000) },+ },+ });+ const exported = await defs+ .find((d) => d.name === 'kiln_export')!+ .run({+ collection: 'project',+ assetId: verbose.assetId,+ revisionId: verbose.revisionId,+ });+ expect(JSON.stringify(exported).length).toBeLessThan(6000);+ } finally {+ await client.close();+ await server.close();+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/src/assets.test.ts b/src/assets.test.tsnew file mode 100644index 00000000..b136d619--- /dev/null+++ b/src/assets.test.ts@@ -0,0 +1,114 @@+import { afterEach, expect, test } from 'bun:test';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { FileAssetLibrary, localAssetLibrary, collectionConfigPath } from './assets-node';+import { decodeAssetBundle, encodeAssetBundle } from './assets';+import { renderGLB } from './render';+import { mkdir } from 'node:fs/promises';+import { dirname } from 'node:path';++const roots: string[] = [];+afterEach(async () => {+ for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });+});+async function library() {+ const root = await mkdtemp(join(tmpdir(), 'kiln-assets-'));+ roots.push(root);+ return { root, store: new FileAssetLibrary({ project: root }) };+}+const source =+ "const meta = { name: 'Box', category: 'prop' }; function build() { const root = createRoot('Box'); createPart('Body', boxGeo(1, 1, 1), gameMaterial(0x88aa66), { position: [0, 0.5, 0], parent: root }); return root; }";+async function draft() {+ const rendered = await renderGLB(source);+ return {+ name: 'Box',+ code: source,+ glb: rendered.glb,+ build: { engine: 'test', options: {}, warnings: rendered.warnings },+ };+}++test('project and personal collection locations persist in the workspace configuration', async () => {+ const { root } = await library();+ const env = { KILN_PROGRAM_STORE: join(root, '.kiln', 'programs') };+ const config = collectionConfigPath(env);+ await mkdir(dirname(config), { recursive: true });+ await writeFile(+ config,+ JSON.stringify({ project: join(root, 'game'), personal: join(root, 'library') }),+ );+ expect(+ localAssetLibrary(env)+ .collections()+ .map((c) => c.id),+ ).toEqual(['project', 'personal']);+ expect(localAssetLibrary(env).directory('personal')).toBe(join(root, 'library'));+ expect(+ localAssetLibrary({+ ...env,+ KILN_COLLECTIONS: JSON.stringify({ override: root }),+ }).collections()[0]!.id,+ ).toBe('override');+});+test('a saved revision survives restarts, roundtrips without the source store, and detects tampering', async () => {+ const { root, store } = await library();+ const saved = await store.save('project', await draft());+ const restarted = new FileAssetLibrary({ project: root });+ const record = await restarted.read('project', saved.assetId, saved.revisionId);+ const bundle = decodeAssetBundle(encodeAssetBundle([record]));+ const other = await library();+ const imported = await other.store.import('project', bundle);+ expect(imported[0]!.revisionId).toBe(saved.revisionId);+ expect(+ (await other.store.read('project', saved.assetId, saved.revisionId)).files['source.kiln.js'],+ ).toEqual(new TextEncoder().encode(source));+ await writeFile(join(root, saved.assetId, 'revisions', saved.revisionId, 'asset.glb'), 'corrupt');+ await expect(restarted.read('project', saved.assetId, saved.revisionId)).rejects.toThrow(+ 'integrity',+ );+});+test('concurrent child revisions both survive and list as branches', async () => {+ const { store } = await library();+ const input = await draft();+ const base = await store.save('project', input);+ const children = await Promise.all(+ ['red', 'blue'].map((description) =>+ store.save('project', {+ ...input,+ assetId: base.assetId,+ parentRevision: base.revisionId,+ description,+ }),+ ),+ );+ expect(children[0]!.revisionId).not.toBe(children[1]!.revisionId);+ expect((await store.list('project')).length).toBe(3);+ expect(+ (await store.read('project', base.assetId, base.revisionId)).manifest.parentRevision,+ ).toBeUndefined();+});+test('unknown roots and traversal are rejected; import is idempotent', async () => {+ const { store } = await library();+ const saved = await store.save('project', await draft());+ await expect(store.read('project', '..', saved.revisionId)).rejects.toThrow();+ await expect(store.list('unknown')).rejects.toThrow('collection');+ const record = await store.read('project', saved.assetId, saved.revisionId);+ await store.import('project', [record]);+ expect((await store.list('project')).length).toBe(1);+ const bad = { ...record, files: { ...record.files, '../outside': new Uint8Array([1]) } };+ expect(() => encodeAssetBundle([bad])).toThrow();+});+test('binary imports are collectible but never claim editable source', async () => {+ const { store } = await library();+ const input = await draft();+ const saved = await store.save('project', { name: 'External', glb: input.glb });+ expect(saved.editable).toBe(false);+ expect(saved.build).toBeUndefined();+ expect(Object.keys((await store.read('project', saved.assetId, saved.revisionId)).files)).toEqual(+ ['asset.glb'],+ );+ await expect(+ store.save('project', { name: 'Invalid', glb: new Uint8Array([0]) }),+ ).rejects.toThrow('GLB');+});diff --git a/src/assets.ts b/src/assets.tsnew file mode 100644index 00000000..ef0fde24--- /dev/null+++ b/src/assets.ts@@ -0,0 +1,169 @@+/** Portable asset records. No filesystem, renderer, or server dependencies. */+import { z } from 'zod';+import { zipSync, unzipSync } from 'three/addons/libs/fflate.module.js';++export const ASSET_LIMIT = 64 * 1024 * 1024;+export const assetIdSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);+const hash = z.string().regex(/^sha256:[a-f0-9]{64}$/);+export const assetManifestSchema = z.object({+ version: z.literal('kiln.asset.v1'),+ assetId: assetIdSchema,+ revisionId: assetIdSchema,+ parentRevision: assetIdSchema.optional(),+ name: z.string().min(1).max(200),+ tags: z.array(z.string().max(80)).max(30),+ createdAt: z.string().datetime(),+ description: z.string().max(4000).optional(),+ brief: z.string().max(8000).optional(),+ attribution: z+ .object({+ model: z.string().max(200).optional(),+ harness: z.string().max(200).optional(),+ author: z.string().max(200).optional(),+ })+ .optional(),+ editable: z.boolean(),+ files: z.record(+ z.string(),+ z.object({ sha256: hash, bytes: z.number().int().nonnegative().max(ASSET_LIMIT) }),+ ),+ build: z+ .object({+ engine: z.string(),+ options: z.record(z.string(), z.unknown()),+ warnings: z.array(z.string()),+ integration: z.unknown().optional(),+ qa: z.unknown().optional(),+ dependencies: z.array(z.unknown()).optional(),+ rebuild: z.enum(['engine-required', 'external-dependencies-required']),+ })+ .optional(),+ preview: z.object({ fidelity: z.unknown().optional(), error: z.string().optional() }).optional(),+});+export type AssetManifest = z.infer<typeof assetManifestSchema>;+export interface AssetRecord {+ manifest: AssetManifest;+ files: Record<string, Uint8Array>;+}+export interface AssetDraft {+ name: string;+ tags?: string[];+ assetId?: string;+ parentRevision?: string;+ code?: string;+ glb: Uint8Array;+ preview?: Uint8Array;+ description?: string;+ brief?: string;+ attribution?: AssetManifest['attribution'];+ build?: Omit<NonNullable<AssetManifest['build']>, 'rebuild'> & {+ rebuild?: NonNullable<AssetManifest['build']>['rebuild'];+ };+ previewInfo?: AssetManifest['preview'];+}+export interface AssetLibrary {+ collections(): { id: string; label: string }[];+ list(collection: string): Promise<AssetManifest[]>;+ save(collection: string, draft: AssetDraft): Promise<AssetManifest>;+ read(collection: string, assetId: string, revisionId: string): Promise<AssetRecord>;+ import(collection: string, records: AssetRecord[]): Promise<AssetManifest[]>;+}+const allowedFiles = new Set(['asset.glb', 'source.kiln.js', 'preview.png']);+export function validateRecordShape(record: AssetRecord): void {+ const manifest = assetManifestSchema.parse(record.manifest);+ const names = Object.keys(record.files);+ if (names.length !== Object.keys(manifest.files).length || !names.includes('asset.glb'))+ throw new Error('Asset file inventory mismatch');+ let total = 0;+ for (const name of names) {+ if (+ !allowedFiles.has(name) ||+ !manifest.files[name] ||+ manifest.files[name].bytes !== record.files[name]!.length+ )+ throw new Error('Invalid asset file inventory');+ total += record.files[name]!.length;+ }+ if (total > ASSET_LIMIT || manifest.editable !== names.includes('source.kiln.js'))+ throw new Error('Invalid asset size or source inventory');+ if ((record.files['source.kiln.js']?.length ?? 0) > 1024 * 1024)+ throw new Error('Source exceeds 1 MiB');+ validateAssetGlb(record.files['asset.glb']!);+}+/** A viewer must not fetch external URLs embedded in a purported standalone GLB. */+export function validateAssetGlb(bytes: Uint8Array): void {+ if (bytes.length < 20 || bytes.length > ASSET_LIMIT) throw new Error('Invalid GLB size');+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ if (+ view.getUint32(0, true) !== 0x46546c67 ||+ view.getUint32(4, true) !== 2 ||+ view.getUint32(8, true) !== bytes.length ||+ view.getUint32(16, true) !== 0x4e4f534a+ )+ throw new Error('Invalid GLB header');+ const end = 20 + view.getUint32(12, true);+ if (end > bytes.length) throw new Error('Invalid GLB JSON length');+ const json = JSON.parse(new TextDecoder().decode(bytes.subarray(20, end)));+ for (const resource of [...(json.buffers ?? []), ...(json.images ?? [])]) {+ if (resource.uri && !String(resource.uri).startsWith('data:'))+ throw new Error('GLB must embed its resources');+ }+}+export function encodeAssetBundle(records: AssetRecord[]): Uint8Array {+ if (!records.length || records.length > 100) throw new Error('Bundle requires 1..100 revisions');+ const files: Record<string, Uint8Array> = {};+ let total = 0;+ for (const record of records) {+ validateRecordShape(record);+ const prefix = `${record.manifest.assetId}/${record.manifest.revisionId}/`;+ if (files[`${prefix}manifest.json`]) throw new Error('Duplicate bundle revision');+ files[`${prefix}manifest.json`] = new TextEncoder().encode(+ JSON.stringify(record.manifest, null, 2),+ );+ for (const [name, bytes] of Object.entries(record.files)) files[prefix + name] = bytes;+ }+ for (const bytes of Object.values(files)) total += bytes.length;+ if (total > ASSET_LIMIT) throw new Error('Bundle exceeds 64 MiB');+ return zipSync(files, { level: 0 });+}+export function decodeAssetBundle(bytes: Uint8Array): AssetRecord[] {+ if (bytes.length > ASSET_LIMIT + 1024 * 1024) throw new Error('Bundle exceeds 64 MiB');+ let total = 0;+ let count = 0;+ const files = unzipSync(bytes, {+ filter: (entry) => {+ total += entry.originalSize;+ count++;+ if (+ total > ASSET_LIMIT ||+ count > 400 ||+ !/^[a-z][a-z0-9_-]{0,79}\/[a-z][a-z0-9_-]{0,79}\/(manifest\.json|asset\.glb|source\.kiln\.js|preview\.png)$/.test(+ entry.name,+ )+ )+ throw new Error('Unsafe or oversized asset bundle');+ return true;+ },+ });+ const records: AssetRecord[] = [];+ const used = new Set<string>();+ for (const [path, data] of Object.entries(files)) {+ if (!path.endsWith('/manifest.json')) continue;+ if (data.length > 1024 * 1024) throw new Error('Manifest exceeds 1 MiB');+ const manifest = assetManifestSchema.parse(JSON.parse(new TextDecoder().decode(data)));+ const prefix = `${manifest.assetId}/${manifest.revisionId}/`;+ if (path !== `${prefix}manifest.json`) throw new Error('Bundle identity mismatch');+ const record: AssetRecord = { manifest, files: {} };+ used.add(path);+ for (const name of Object.keys(manifest.files)) {+ if (!files[prefix + name]) throw new Error('Bundle file missing');+ record.files[name] = files[prefix + name]!;+ used.add(prefix + name);+ }+ validateRecordShape(record);+ records.push(record);+ }+ if (!records.length || used.size !== Object.keys(files).length)+ throw new Error('Incomplete asset bundle');+ return records;+}diff --git a/src/cli.ts b/src/cli.tsindex 6139e239..ab108183 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -15,6 +15,7 @@ import { resolveRenderMode, buildRenderPort, describeDrawnBy } from './cli-rendeimport type { RenderMode } from './cli-render-mode';import { localProgramStore } from './program-store-node';import { retainProgram, programRefPattern } from './program-store';+import { ASSET_USAGE } from './asset-cli';const USAGE = `kiln — vision-in-the-loop 3D asset generation@@ -318,6 +319,16 @@ async function cmdSource(args: Args): Promise<number> {}export async function main(argv: readonly string[]): Promise<number> {+ if (+ ['save', 'collections', 'assets', 'asset', 'export', 'import', 'view'].includes(argv[0] ?? '')+ ) {+ try {+ return await (await import('./asset-cli')).assetMain(argv);+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error));+ return 1;+ }+ }let args: Args;try {args = parseArgs(argv);@@ -326,7 +337,7 @@ export async function main(argv: readonly string[]): Promise<number> {return 2;}if (args.help || !args.command) {- console.log(USAGE);+ console.log(USAGE + ASSET_USAGE);return args.help ? 0 : 2;}try {diff --git a/src/local-runtime.ts b/src/local-runtime.tsindex 6cce4ca2..04ae6712 100644--- a/src/local-runtime.ts+++ b/src/local-runtime.ts@@ -116,6 +116,13 @@ export function createLocalToolContext(base.programStore ??new FileProgramStore(resolve(env.KILN_PROGRAM_STORE ?? '.kiln/programs')),evaluatorPort,+ assetBuildOptions: {+ optimize,+ instance,+ geometryPolicy,+ qaMode: env.KILN_QA_MODE ?? 'enforce',+ evaluatorMode: mode,+ },buildCache: new MemoryBuildCache(),evaluatorCacheIdentity: `kiln-local-${process.pid}-${++scope}:${JSON.stringify({ mode, optimize, instance, geometryPolicy, qa: env.KILN_QA_MODE, deadlineMs, heapMb })}`,localExecution,diff --git a/src/mcp-parity.test.ts b/src/mcp-parity.test.tsindex f32d5f15..9385415d 100644--- a/src/mcp-parity.test.ts+++ b/src/mcp-parity.test.ts@@ -11,7 +11,7 @@ import { describe, expect, it } from 'bun:test';import { Client, InMemoryTransport } from '@modelcontextprotocol/client';import { createKilnToolRegistry, createKilnProgramToolRegistry } from './tools/registry';-import { makeKilnTools, KILN_SUBMIT_TOOL_NAME } from './agent/tools';+import { makeKilnTools, makeKilnProgramTools, KILN_SUBMIT_TOOL_NAME } from './agent/tools';import { runTool, kilnMcpToolDefs, createKilnMcpServer } from './mcp-server';/**@@ -23,7 +23,12 @@ import { runTool, kilnMcpToolDefs, createKilnMcpServer } from './mcp-server';* converter would have been a test of the converter, not of the surface.*/async function listToolsOverMcp(): Promise<- { name: string; description?: string; inputSchema: unknown }[]+ {+ name: string;+ description?: string;+ inputSchema: unknown;+ annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean };+ }[]> {const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();const server = createKilnMcpServer();@@ -39,6 +44,19 @@ async function listToolsOverMcp(): Promise<}describe('tool surface parity across transports', () => {+ it('advertises reads and immutable writes without destructive defaults', async () => {+ const tools = await listToolsOverMcp();+ for (const tool of tools) expect(tool.annotations?.destructiveHint).toBe(false);+ for (const name of ['kiln_source', 'kiln_list_primitives', 'kiln_export'])+ expect(tools.find((t) => t.name === name)?.annotations?.readOnlyHint).toBe(true);+ expect(tools.find((t) => t.name === 'kiln_save')?.annotations?.readOnlyHint).toBe(false);+ });+ it('the reference-based Strands skin shares every MCP definition plus terminal submit', () => {+ expect(makeKilnProgramTools({}).map((t) => t.name)).toEqual([+ ...kilnMcpToolDefs().map((d) => d.name),+ KILN_SUBMIT_TOOL_NAME,+ ]);+ });it('the MCP skin advertises its defs verbatim', async () => {const defs = kilnMcpToolDefs();const advertised = await listToolsOverMcp();@@ -82,6 +100,11 @@ describe('tool surface parity across transports', () => {// re-emitting the whole file through kiln_render.'kiln_edit','kiln_source',+ 'kiln_save',+ 'kiln_assets',+ 'kiln_present',+ 'kiln_export',+ 'kiln_import',]);const mcpRender = kilnMcpToolDefs().find((d) => d.name === 'kiln_render')!;@@ -150,16 +173,18 @@ function build() {expect(kinds).toContain('image');expect(kinds).toContain('text');- const image = result.content.find((c) => c.type === 'image') as { data: string };+ const image = result.content.find((c) => c.type === 'image') as {+ data: string;+ };// A PNG, base64-encoded: the agent literally sees the render.expect(Buffer.from(image.data, 'base64').subarray(1, 4).toString('ascii')).toBe('PNG');});it('a failing tool call is an error result, not a thrown transport failure', async () => {const def = kilnMcpToolDefs().find((d) => d.name === 'kiln_render');- const result = await runTool(def!, { code: 'this is not valid kiln source' }).catch(- () => undefined,- );+ const result = await runTool(def!, {+ code: 'this is not valid kiln source',+ }).catch(() => undefined);// Either the def handled it and returned content, or runTool surfaced it — what// must never happen is an unhandled rejection killing the MCP session.expect(result).toBeDefined();diff --git a/src/mcp-server.ts b/src/mcp-server.tsindex 9568adc4..ee89ce89 100644--- a/src/mcp-server.ts+++ b/src/mcp-server.ts@@ -4,12 +4,15 @@* The CLI entry uses a persistent local source store. Embedded callers can inject* their own store and renderer; schemas and image extraction stay in the registry.*/-import { McpServer } from '@modelcontextprotocol/server';+import { McpServer, ResourceTemplate } from '@modelcontextprotocol/server';+import { localAssetLibrary } from './assets-node';+import { readAssetResource, type AssetLink } from './assets-resources';import { serveStdio } from '@modelcontextprotocol/server/stdio';import { AsyncLocalStorage } from 'node:async_hooks';import {createKilnProgramToolRegistry,+ KILN_ASSET_WIDGET_URI,type KilnToolDef,type KilnToolContext,} from './tools/registry';@@ -23,6 +26,7 @@ export const MCP_SERVER_VERSION = '0.6.0';/** One MCP content block. Mirrors the SDK's `CallToolResult['content']` element. */type ContentBlock =+ | AssetLink| { type: 'text'; text: string }| { type: 'image'; data: string; mimeType: string };@@ -42,6 +46,8 @@ type ContentBlock =export type KilnToolResult = {content: ContentBlock[];isError?: boolean;+ structuredContent?: Record<string, unknown>;+ _meta?: Record<string, unknown>;};/** Use the shared program-aware definitions, including standalone validation. */@@ -94,12 +100,76 @@ export async function runTool(def: KilnToolDef, args: unknown): Promise<KilnToolconst asText = def.text?.(output);if (asText !== undefined) return { content: [{ type: 'text', text: asText }] };- return { content: [{ type: 'text', text: JSON.stringify(output, null, 2) }] };+ const resources = (output as { resources?: AssetLink[] } | null)?.resources ?? [];+ const payload = resources.length ? { ...(output as object), resources: undefined } : output;+ return {+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }, ...resources],+ ...(def.ui+ ? {+ structuredContent: output as Record<string, unknown>,+ _meta: await def.ui.data(output),+ }+ : {}),+ };}/** Build the server, registering every def from the registry. */export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {- const server = new McpServer({ name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION });+ const server = new McpServer({+ name: MCP_SERVER_NAME,+ version: MCP_SERVER_VERSION,+ });+ server.registerResource(+ 'kiln-asset-viewer',+ KILN_ASSET_WIDGET_URI,+ {+ description: 'Interactive Kiln asset viewer and downloads',+ mimeType: 'text/html;profile=mcp-app',+ },+ async (uri) => ({+ contents: [+ {+ uri: uri.href,+ mimeType: 'text/html;profile=mcp-app',+ text: await (await import('./asset-widget')).readAssetWidgetHtml(),+ _meta: {+ ui: {+ prefersBorder: true,+ csp: { connectDomains: [], resourceDomains: [] },+ },+ 'openai/widgetDescription':+ 'Inspect the saved 3D asset and download its GLB or editable bundle.',+ 'openai/widgetPrefersBorder': true,+ },+ },+ ],+ }),+ );+ if (context.assetLibrary) {+ server.registerResource(+ 'asset-file',+ new ResourceTemplate('kiln://assets/{collection}/{asset}/{revision}/{file}', {+ list: undefined,+ }),+ {+ description: 'Exact saved GLB, editable source, preview, manifest, or portable bundle.',+ },+ async (uri) => {+ const file = await readAssetResource(context.assetLibrary!, uri.href);+ return {+ contents: [+ {+ uri: uri.href,+ mimeType: file.mimeType,+ ...(file.name.endsWith('.json') || file.name.endsWith('.js')+ ? { text: new TextDecoder().decode(file.bytes) }+ : { blob: Buffer.from(file.bytes).toString('base64') }),+ },+ ],+ };+ },+ );+ }const requests = new AsyncLocalStorage<AbortSignal>();const requestContext: KilnToolContext = {...context,@@ -109,7 +179,9 @@ export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {return {...configured,...(signal- ? { signal: configured.signal ? AbortSignal.any([signal, configured.signal]) : signal }+ ? {+ signal: configured.signal ? AbortSignal.any([signal, configured.signal]) : signal,+ }: {}),};},@@ -120,12 +192,23 @@ export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {def.name,{description: def.description,+ annotations: def.annotations,+ ...(def.ui+ ? {+ _meta: {+ ui: { resourceUri: def.ui.resourceUri },+ 'openai/outputTemplate': def.ui.resourceUri,+ 'openai/widgetAccessible': true,+ },+ }+ : {}),// The registry's zod schema, passed straight through as Standard Schema.// The SDK advertises the derived JSON Schema and validates arguments, so// there is no second copy of the schema anywhere in this file. No cast:// a cast here would silently decouple the advertised schema from the// registry's, which is the one thing this file exists not to do.inputSchema: def.inputSchema,+ ...(def.outputSchema ? { outputSchema: def.outputSchema } : {}),},async (args: unknown, request): Promise<KilnToolResult> => {try {@@ -137,7 +220,10 @@ export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {return {isError: true,content: [- { type: 'text' as const, text: err instanceof Error ? err.message : String(err) },+ {+ type: 'text' as const,+ text: err instanceof Error ? err.message : String(err),+ },],};}@@ -156,6 +242,28 @@ if (import.meta.main) {await buildRenderPort(mode, process.env['KILN_RENDER_PORT_URL']),);context.programStore = localProgramStore();+ context.assetLibrary = localAssetLibrary();+ const deliveryBase = process.env['KILN_ASSET_DOWNLOAD_BASE_URL'];+ if (deliveryBase) {+ const base = new URL(deliveryBase);+ if (+ base.protocol !== 'https:' &&+ !(base.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname))+ )+ throw new Error('Asset download base must use HTTPS or loopback HTTP');+ context.assetDownloadUrls = async (collection, assetId, revisionId) =>+ Object.fromEntries(+ ['asset.glb', 'editable.zip', 'source.kiln.js', 'preview.png', 'manifest.json'].map(+ (file) => [+ file,+ new URL(+ `files/${collection}/${assetId}/${revisionId}/${file}?download`,+ base.href.endsWith('/') ? base.href : `${base.href}/`,+ ).href,+ ],+ ),+ );+ }// stdout is the MCP transport; diagnostics must never touch it.console.error(`kiln MCP server on stdio (${mode})`);void serveStdio(() => createKilnMcpServer(context));diff --git a/src/tools/discovery.ts b/src/tools/discovery.tsindex 51750390..102ef527 100644--- a/src/tools/discovery.ts+++ b/src/tools/discovery.ts@@ -82,6 +82,17 @@ export function createKilnDiscoveryDef(context: KilnToolContext): KilnToolDef {boundedRead: true,atomicEdit: true,},+ assets: {+ available: Boolean(context.assetLibrary),+ collections: context.assetLibrary?.collections() ?? [],+ save: 'kiln_save persists exact GLB, source and provenance; draft renders do not populate collections',+ resume:+ 'kiln_assets action=restore imports a saved revision into the current program store',+ downloads:+ 'kiln_export returns GLB/source/ZIP resource links; client presentation varies',+ viewer:+ 'kiln_present opens a saved revision in supporting chat clients with 3D viewing and downloads; kiln view opens a local collection or standalone GLB/ZIP',+ },geometry: {attributes: ['position', 'normal', 'uv', 'tangent'],indexedTriangles: true,diff --git a/src/tools/registry.ts b/src/tools/registry.tsindex 1ff28fc8..07fe42db 100644--- a/src/tools/registry.ts+++ b/src/tools/registry.ts@@ -10,7 +10,8 @@ import {*/import { z } from 'zod';-import { MemoryProgramStore, type ProgramStore } from '../program-store';+import { assetManifestSchema } from '../assets';+import { MemoryProgramStore, retainProgram, type ProgramStore } from '../program-store';import { createKilnSourceDef, withProgramReferences } from './programs';import { createKilnDiscoveryDef } from './discovery';import { createCachedEvaluatorPort, MemoryBuildCache, type BuildCache } from '../build-cache';@@ -50,7 +51,20 @@ import type { TextureUsage } from '../textures';// Tool definition contract// =============================================================================+export const KILN_ASSET_WIDGET_URI = 'ui://kiln/asset-v3.html';export interface KilnToolDef {+ outputSchema?: z.ZodType;+ /** Optional MCP App presentation; metadata is hidden from the language model. */+ ui?: {+ resourceUri: string;+ data(output: unknown): Promise<Record<string, unknown>>;+ };+ annotations?: {+ readOnlyHint: boolean;+ destructiveHint: boolean;+ idempotentHint: boolean;+ openWorldHint: boolean;+ };/** Stable tool name exposed to the model (in-process and over MCP). */name: string;/** Model-facing description, consistent with the kiln-glb SKILL.md language. */@@ -103,6 +117,16 @@ export interface KilnToolDef {* category field.*/export interface KilnToolContext {+ /** 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. */+ assetDownloadUrls?: (+ collection: string,+ assetId: string,+ revisionId: string,+ ) => Promise<Record<string, string>>;+ /** Effective host defaults, captured for saved build provenance. */+ assetBuildOptions?: Record<string, unknown>;geometryPolicy?: import('../geometry-export').GeometryExportPolicy;localExecution?: import('../local-runtime').LocalExecution;evaluationControls?: () => import('../evaluator/protocol').EvaluatorPortCallControlsV1;@@ -467,20 +491,21 @@ async function renderDerivativeCell(...(input.backfaceCull !== undefined ? { backfaceCull: input.backfaceCull } : {}),...(input.frameBounds ? { frameBounds: input.frameBounds } : {}),});- const flat: import('../views').GlbViewCellResult & { captureCache?: { hit: boolean } } =- context.captureCache- ? await (await import('../views/capture-cache')).captureCpuCell(- context.captureCache,- {- artifactGlbSha256: inputGlbSha256,- rendererId: CPU_RASTER_RENDERER_ID,- camera,- size: input.size,- backfaceCull: input.backfaceCull ?? true,- },- produceFlat,- )- : await produceFlat();+ const flat: import('../views').GlbViewCellResult & {+ captureCache?: { hit: boolean };+ } = context.captureCache+ ? await (await import('../views/capture-cache')).captureCpuCell(+ context.captureCache,+ {+ artifactGlbSha256: inputGlbSha256,+ rendererId: CPU_RASTER_RENDERER_ID,+ camera,+ size: input.size,+ backfaceCull: input.backfaceCull ?? true,+ },+ produceFlat,+ )+ : await produceFlat();if (flat.inputGlbSha256 !== inputGlbSha256) {throw new Error(`derivative GLB fallback hash mismatch (${flat.inputGlbSha256} != ${inputGlbSha256})`,@@ -653,7 +678,10 @@ const cameraShotInput = ztarget: cameraVec3Input.optional(),relativeTo: z.enum(['world', 'asset', 'part', 'local']).optional(),frame: z- .object({ origin: cameraVec3Input.optional(), rotation: cameraVec3Input.optional() })+ .object({+ origin: cameraVec3Input.optional(),+ rotation: cameraVec3Input.optional(),+ }).strict().optional(),framing: z.enum(['explicit', 'bounds']).optional(),@@ -702,7 +730,9 @@ const captureInput = z.union([advancedCaptureInput,- z.strictObject(legacyCaptureInput.unwrap().shape, { error: taggedCaptureError }),+ z.strictObject(legacyCaptureInput.unwrap().shape, {+ error: taggedCaptureError,+ }),],{ error: taggedCaptureError },)@@ -968,7 +998,9 @@ async function runScreenshot(try {const { renderGlbViewGrid } = await import('../views');const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);- const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });+ const warnings = inspectSceneStructure(root, {+ category: trustedCategory(context),+ });// No capture config here on purpose: kiln_screenshot belongs to the frozen// four-tool baseline, whose schemas stay byte-for-byte unchanged.const grid = await renderGlbViewGrid(rendered.glb);@@ -1179,7 +1211,9 @@ async function runRenderViews(renderer: CPU_RASTER_RENDERER_ID,degraded: neededPbr,...(neededPbr- ? { degradedReason: 'material-faithful view render port unavailable' }+ ? {+ degradedReason: 'material-faithful view render port unavailable',+ }: {}),neededPbr,};@@ -1333,7 +1367,9 @@ async function runScreenshotAnimation(try {const { renderClipAnimation } = await import('../views');const { root, clips } = await loadEvaluatedReviewScene(input.code, context);- const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });+ const warnings = inspectSceneStructure(root, {+ category: trustedCategory(context),+ });const r = await renderClipAnimation(root, clips, {clip: input.clip,...(input.shot ? { shot: input.shot } : {}),@@ -1402,7 +1438,10 @@ export function screenshotAnimationMediaMulti(const o = output as KilnScreenshotAnimationResult | undefined;if (!o || !Array.isArray(o.framesBase64) || o.framesBase64.length === 0) return undefined;const { pngBase64: _png, framesBase64: _frames, ...json } = o;- return { pngs: o.framesBase64.map((b) => new Uint8Array(Buffer.from(b, 'base64'))), json };+ return {+ pngs: o.framesBase64.map((b) => new Uint8Array(Buffer.from(b, 'base64'))),+ json,+ };}/**@@ -1501,7 +1540,9 @@ async function runViewInterior(...(nodeName ? { nodeName } : {}),renderDerivativeCell: (cell) => renderDerivativeCell(cell, context),});- const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });+ const warnings = inspectSceneStructure(root, {+ category: trustedCategory(context),+ });if (grid.roofsHidden === 0) {warnings.push(nodeName@@ -1780,7 +1821,10 @@ async function runInspect(...(viewEvidence ? { viewEvidence } : {}),};} catch (err) {- return { ok: false, error: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ error: err instanceof Error ? err.message : String(err),+ };}}@@ -2163,7 +2207,10 @@ async function guardCaptureBudget(}return out;} catch (error) {- return { ok: false, error: error instanceof Error ? error.message : String(error) };+ return {+ ok: false,+ error: error instanceof Error ? error.message : String(error),+ };}}@@ -2178,7 +2225,12 @@ function withCaptureCache(context: KilnToolContext): KilnToolContext {...context,captureCache: cache,...(context.viewRenderPort && context.captureCacheIdentity- ? { viewRenderPort: createCachedRenderPort(context.viewRenderPort, { cache, identity }) }+ ? {+ viewRenderPort: createCachedRenderPort(context.viewRenderPort, {+ cache,+ identity,+ }),+ }: {}),};}@@ -2200,5 +2252,273 @@ export function createKilnProgramToolRegistry(createKilnEditDef(context),].map((def) => withProgramReferences(def, store)),createKilnSourceDef(store),+ ...createKilnAssetDefs({ ...context, programStore: store }),+ ].map((def) => ({+ ...def,+ annotations: {+ readOnlyHint: ['kiln_source', 'kiln_list_primitives', 'kiln_export', 'kiln_present'].includes(+ def.name,+ ),+ destructiveHint: false,+ idempotentHint: def.name !== 'kiln_save',+ openWorldHint: false,+ },+ }));+}++const assetSelector = {+ collection: z+ .string()+ .regex(/^[a-z][a-z0-9_-]{0,79}$/)+ .default('project'),+ assetId: z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),+ revisionId: z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),+};++/** All asset operation schemas live here, alongside the existing tool definitions. */+export function createKilnAssetDefs(context: KilnToolContext): KilnToolDef[] {+ const library = () => {+ if (!context.assetLibrary)+ throw new Error(+ 'No asset library configured. The local CLI/MCP host supplies workspace collections; embedded hosts must inject assetLibrary.',+ );+ return context.assetLibrary;+ };+ const links = async (collection: string, asset: import('../assets').AssetManifest) => ({+ ok: true,+ collection,+ asset: {+ assetId: asset.assetId,+ revisionId: asset.revisionId,+ parentRevision: asset.parentRevision,+ name: asset.name,+ tags: asset.tags,+ createdAt: asset.createdAt,+ editable: asset.editable,+ files: asset.files,+ build: asset.build && {+ engine: asset.build.engine,+ rebuild: asset.build.rebuild,+ warningCount: asset.build.warnings.length,+ warnings: asset.build.warnings.slice(0, 3).map((warning) => warning.slice(0, 200)),+ },+ },+ resources: (await import('../assets-resources')).assetLinks(collection, asset),+ downloadUrls: await context.assetDownloadUrls?.(collection, asset.assetId, asset.revisionId),+ });+ const saveInput = z.object({+ collection: assetSelector.collection,+ programRef: z.string(),+ name: z.string().min(1).max(200),+ assetId: assetSelector.assetId.optional(),+ parentRevision: assetSelector.revisionId.optional(),+ tags: z.array(z.string().max(80)).max(30).optional(),+ brief: z.string().max(8000).optional(),+ description: z.string().max(4000).optional(),+ attribution: z+ .object({+ model: z.string().max(200).optional(),+ harness: z.string().max(200).optional(),+ author: z.string().max(200).optional(),+ })+ .optional(),+ });+ const assetsInput = z.object({+ action: z.enum(['collections', 'list', 'get', 'restore']).default('list'),+ collection: assetSelector.collection,+ assetId: assetSelector.assetId.optional(),+ revisionId: assetSelector.revisionId.optional(),+ query: z.string().max(200).optional(),+ offset: z.number().int().min(0).default(0),+ limit: z.number().int().min(1).max(50).default(20),+ });+ const exportInput = z.object(assetSelector);+ const importInput = z.object({+ ...assetSelector,+ sourceCollection: assetSelector.collection,+ });+ return [+ {+ name: 'kiln_save',+ description:+ 'Save a completed source revision as a durable asset with its exact GLB, source, preview, and build record. Use programRef returned by render/edit. To revise an existing asset, supply its assetId and parentRevision; previous revisions remain intact. Returns downloadable resources. Draft renders do not populate collections.',+ inputSchema: saveInput,+ run: async (raw) => {+ const input = saveInput.parse(raw);+ const target = library();+ const code = await context.programStore!.get(input.programRef);+ const rendered = await evaluateGeneratedSource(code, context);+ let preview: Uint8Array | undefined;+ let previewInfo: import('../assets').AssetManifest['preview'];+ try {+ const result = await runRenderViews({ code } as z.infer<typeof renderViewsInput>, {+ ...context,+ evaluatorPort: { render: async () => rendered },+ });+ if (!result.ok || !result.pngBase64)+ throw new Error(result.error ?? 'Preview unavailable');+ preview = Uint8Array.from(Buffer.from(result.pngBase64, 'base64'));+ previewInfo = { fidelity: result.viewFidelity };+ } catch (error) {+ previewInfo = {+ error: error instanceof Error ? error.message : String(error),+ };+ }+ const dependencies = rendered.materialResourceProvenance ?? [];+ const asset = await target.save(input.collection, {+ ...input,+ code,+ glb: rendered.glb,+ preview,+ previewInfo,+ build: {+ engine: context.localExecution?.runtimeIdentity ?? 'source-development:unverified',+ options: {+ ...context.assetBuildOptions,+ optimize: 'off',+ instance: context.assetBuildOptions?.instance ?? 'unspecified-by-host',+ geometryPolicy: context.geometryPolicy ?? 'warn',+ category: trustedCategory(context),+ intent: context.intent,+ },+ warnings: rendered.warnings,+ integration: rendered.integrationManifest,+ qa: rendered.meta.qaReport,+ dependencies,+ rebuild: dependencies.some((d) => d.delivery === 'runtime')+ ? 'external-dependencies-required'+ : 'engine-required',+ },+ });+ return links(input.collection, asset);+ },+ },+ {+ name: 'kiln_assets',+ description:+ 'Discover collections; list/search saved asset revisions; get a build record and downloads; or restore exact editable source into the current program store for kiln_source/kiln_edit. List is paginated. Binary-only imports cannot restore source.',+ inputSchema: assetsInput,+ run: async (raw) => {+ const input = assetsInput.parse(raw);+ const target = library();+ if (input.action === 'collections') return { collections: target.collections() };+ if (input.action === 'list') {+ const query = input.query?.toLowerCase();+ const all = (await target.list(input.collection)).filter(+ (a) =>+ (!input.assetId || a.assetId === input.assetId) &&+ (!query || `${a.name} ${a.tags.join(' ')}`.toLowerCase().includes(query)),+ );+ return {+ collection: input.collection,+ total: all.length,+ nextOffset: input.offset + input.limit < all.length ? input.offset + input.limit : null,+ assets: all.slice(input.offset, input.offset + input.limit).map((a) => ({+ assetId: a.assetId,+ revisionId: a.revisionId,+ parentRevision: a.parentRevision,+ name: a.name,+ tags: a.tags,+ editable: a.editable,+ createdAt: a.createdAt,+ })),+ };+ }+ if (!input.assetId || !input.revisionId)+ throw new Error('get/restore requires assetId and revisionId');+ const record = await target.read(input.collection, input.assetId, input.revisionId);+ if (input.action === 'get') return links(input.collection, record.manifest);+ const code = record.files['source.kiln.js'];+ 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)),+ };+ },+ },+ {+ name: 'kiln_present',+ description:+ 'Show a saved asset in an interactive chat viewer with GLB, editable ZIP, and source download buttons. Call after saving or when the user wants to see or download an asset. Other hosts receive portable resource links.',+ inputSchema: exportInput,+ outputSchema: z.object({+ ok: z.literal(true),+ collection: z.string(),+ asset: assetManifestSchema+ .pick({+ assetId: true,+ revisionId: true,+ parentRevision: true,+ name: true,+ tags: true,+ createdAt: true,+ editable: true,+ files: true,+ })+ .extend({+ build: z+ .object({+ engine: z.string(),+ rebuild: z.enum(['engine-required', 'external-dependencies-required']),+ warningCount: z.number().int(),+ warnings: z.array(z.string()),+ })+ .optional(),+ }),+ resources: z.array(+ z.object({+ type: z.literal('resource_link'),+ name: z.string(),+ uri: z.string(),+ mimeType: z.string(),+ }),+ ),+ downloadUrls: z.record(z.string(), z.string()).optional(),+ }),+ ui: {+ resourceUri: KILN_ASSET_WIDGET_URI,+ data: async (output) =>+ (await import('../asset-widget')).assetWidgetData(+ library(),+ output as {+ collection: string;+ asset: { assetId: string; revisionId: string };+ },+ ),+ },+ run: async (raw) => {+ const input = exportInput.parse(raw);+ return links(+ input.collection,+ (await library().read(input.collection, input.assetId, input.revisionId)).manifest,+ );+ },+ },+ {+ name: 'kiln_export',+ description:+ 'Get downloadable GLB, source, manifest, and portable ZIP resource links for one exact saved revision. The ZIP contains source when available and does not require the original program store. Use the host resource reader/download UI; no binary bytes are placed in tool text.',+ inputSchema: exportInput,+ run: async (raw) => {+ const input = exportInput.parse(raw);+ return links(+ input.collection,+ (await library().read(input.collection, input.assetId, input.revisionId)).manifest,+ );+ },+ },+ {+ name: 'kiln_import',+ description:+ 'Copy a pinned asset revision between configured project/personal collections, preserving identity and provenance. Copies never track later edits automatically. For a GLB or downloaded ZIP on disk, use kiln import <file> --collection <name> in the CLI.',+ inputSchema: importInput,+ run: async (raw) => {+ const input = importInput.parse(raw);+ const target = library();+ const record = await target.read(input.sourceCollection, input.assetId, input.revisionId);+ await target.import(input.collection, [record]);+ return links(input.collection, record.manifest);+ },+ },];}diff --git a/src/viewer/app.ts b/src/viewer/app.tsnew file mode 100644index 00000000..7bf1adbe--- /dev/null+++ b/src/viewer/app.ts@@ -0,0 +1,464 @@+/// <reference lib="dom" />+import {+ ASSET_LIMIT,+ decodeAssetBundle,+ encodeAssetBundle,+ type AssetManifest,+ type AssetRecord,+} from '../assets';+import { createAssetStage } from './scene';++const el = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id)! as T;+const node = <K extends keyof HTMLElementTagNameMap>(tag: K, text?: string, className?: string) => {+ const element = document.createElement(tag);+ if (text !== undefined) element.textContent = text;+ if (className) element.className = className;+ return element;+};+type Entry = {+ collection: string;+ manifest: AssetManifest;+ local?: AssetRecord;+ loose?: Uint8Array;+};+let collections: { id: string; label: string }[] = [];+let entries: Entry[] = [];+const opened: Entry[] = [];+let currentCollection = '';+let chosen: Entry | undefined;+let stage: ReturnType<typeof createAssetStage> | undefined;+let detailGeneration = 0;+let listGeneration = 0;+let wire = false;+let paused = false;+const selected = new Set<string>();+const urls: string[] = [];+const thumbUrls: string[] = [];+const key = (entry: Entry) =>+ `${entry.collection}/${entry.manifest.assetId}/${entry.manifest.revisionId}`;+const message = (text: string) => {+ el('status').textContent = text;+};+const showError = (error: unknown) =>+ message(error instanceof Error ? error.message : String(error));+const blobUrl = (bytes: Uint8Array, mime: string, targets = urls) => {+ const url = URL.createObjectURL(new Blob([Uint8Array.from(bytes)], { type: mime }));+ targets.push(url);+ return url;+};+async function json(path: string) {+ const res = await fetch(path);+ const body = await res.json();+ if (!res.ok) throw new Error(body.error ?? 'Request failed');+ return body;+}+async function bytes(entry: Entry, file: string) {+ if (entry.local) {+ const value = entry.local.files[file];+ if (!value) throw new Error('File unavailable');+ return value;+ }+ if (entry.loose && file === 'asset.glb') return entry.loose;+ const response = await fetch(`/files/${key(entry)}/${file}`);+ if (!response.ok) throw new Error((await response.json()).error ?? 'File unavailable');+ return new Uint8Array(await response.arrayBuffer());+}+function href(entry: Entry, file: string) {+ if (entry.local) {+ if (file === 'editable.zip')+ return blobUrl(encodeAssetBundle([entry.local]), 'application/zip');+ return blobUrl(+ entry.local.files[file]!,+ file.endsWith('.js') ? 'text/javascript' : 'model/gltf-binary',+ );+ }+ if (entry.loose) return blobUrl(entry.loose, 'model/gltf-binary');+ return `/files/${key(entry)}/${file}?download`;+}+function remember(name: string, value: string) {+ try {+ localStorage.setItem(name, value);+ } catch {+ /* Files remain usable when browser storage is unavailable. */+ }+}+function recalled(name: string) {+ try {+ return localStorage.getItem(name);+ } catch {+ return null;+ }+}+function collectionNav() {+ const nav = el('collections');+ nav.replaceChildren();+ for (const collection of [+ ...collections,+ ...(opened.length ? [{ id: 'opened-files', label: 'Opened files' }] : []),+ ]) {+ const button = node(+ 'button',+ collection.label,+ currentCollection === collection.id ? 'active' : '',+ );+ button.onclick = () => void loadCollection(collection.id).catch(showError);+ nav.append(button);+ }+}+async function loadCollection(id: string) {+ const generation = ++listGeneration;+ currentCollection = id;+ selected.clear();+ collectionNav();+ message('');+ const loaded =+ id === 'opened-files'+ ? opened+ : (await json(`/api/assets?collection=${encodeURIComponent(id)}`)).assets.map(+ (manifest: AssetManifest) => ({ collection: id, manifest }),+ );+ if (generation !== listGeneration) return;+ entries = loaded;+ remember('kiln.collection', id);+ el('collection-title').textContent =+ id === 'opened-files' ? 'Opened files' : (collections.find((c) => c.id === id)?.label ?? id);+ el('collection-caption').textContent =+ id === 'opened-files'+ ? 'Previewed in your browser. Your original files stay untouched.'+ : 'Saved revisions, editable source, and everything ready to use.';+ renderCards();+}+function latestEntries() {+ const groups = new Map<string, Entry[]>();+ for (const entry of entries) {+ const id = entry.manifest.assetId;+ groups.set(id, [...(groups.get(id) ?? []), entry]);+ }+ return [...groups.values()].map((group) => {+ group.sort(+ (a, b) =>+ b.manifest.createdAt.localeCompare(a.manifest.createdAt) ||+ b.manifest.revisionId.localeCompare(a.manifest.revisionId),+ );+ return (+ group.find(+ (e) =>+ e.manifest.revisionId === recalled(`kiln.revision.${e.collection}.${e.manifest.assetId}`),+ ) ?? group[0]!+ );+ });+}+function renderCards() {+ for (const url of thumbUrls.splice(0)) URL.revokeObjectURL(url);+ const cards = el('cards');+ cards.replaceChildren();+ const query = el<HTMLInputElement>('search').value.toLowerCase();+ const shown = latestEntries().filter((e) =>+ `${e.manifest.name} ${e.manifest.tags.join(' ')}`.toLowerCase().includes(query),+ );+ el('count').textContent = `${shown.length} asset${shown.length === 1 ? '' : 's'}`;+ el<HTMLButtonElement>('export-selection').disabled = !selected.size;+ if (!shown.length) {+ const empty = node('div', undefined, 'empty');+ empty.append(+ node('b', query ? 'No matching assets' : 'Your next idea belongs here.'),+ node(+ 'p',+ query+ ? 'Try another name or tag.'+ : 'Save an asset with your agent, or open a GLB or editable bundle.',+ ),+ );+ if (!query) empty.append(node('code', 'kiln save asset.kiln.js --name "My asset"'));+ cards.append(empty);+ return;+ }+ for (const entry of shown) {+ const manifest = entry.manifest;+ const card = node('article', undefined, 'card');+ const button = node('button', undefined, 'card-open');+ button.setAttribute('aria-label', `View ${manifest.name}`);+ button.onclick = () => void openDetail(entry).catch(showError);+ const thumb = node('div', undefined, 'thumb');+ if (manifest.files['preview.png']) {+ const img = node('img');+ img.loading = 'lazy';+ img.alt = manifest.name;+ img.src = entry.local+ ? blobUrl(entry.local.files['preview.png']!, 'image/png', thumbUrls)+ : `/files/${key(entry)}/preview.png`;+ img.onerror = () => {+ img.remove();+ thumb.textContent = '◇';+ };+ thumb.append(img);+ } else thumb.textContent = '◇';+ const content = node('div', undefined, 'card-content');+ content.append(node('span', manifest.name, 'card-title'));+ const revisions = entries.filter((e) => e.manifest.assetId === manifest.assetId);+ const parentIds = new Set(revisions.map((e) => e.manifest.parentRevision));+ const heads = revisions.filter((e) => !parentIds.has(e.manifest.revisionId));+ content.append(+ node(+ 'span',+ `${manifest.editable ? 'Editable source' : 'Source unavailable'} · ${revisions.length} revision${revisions.length === 1 ? '' : 's'}${heads.length > 1 ? ` · ${heads.length} branches` : ''}`,+ 'card-meta',+ ),+ );+ const tags = node('div', undefined, 'tags');+ for (const tag of manifest.tags) tags.append(node('span', tag, 'tag'));+ content.append(tags);+ button.append(thumb, content);+ card.append(button);+ if (!entry.loose) {+ const checkbox = node('input');+ checkbox.type = 'checkbox';+ checkbox.className = 'selection';+ checkbox.checked = selected.has(key(entry));+ checkbox.setAttribute('aria-label', `Select ${manifest.name}`);+ checkbox.onchange = () => {+ if (checkbox.checked) selected.add(key(entry));+ else selected.delete(key(entry));+ el<HTMLButtonElement>('export-selection').disabled = !selected.size;+ };+ card.append(checkbox);+ }+ cards.append(card);+ }+}+async function openDetail(entry: Entry) {+ const generation = ++detailGeneration;+ chosen = entry;+ remember(+ `kiln.revision.${entry.collection}.${entry.manifest.assetId}`,+ entry.manifest.revisionId,+ );+ for (const url of urls.splice(0)) URL.revokeObjectURL(url);+ const dialog = el<HTMLDialogElement>('detail');+ if (!dialog.open) dialog.showModal();+ el('asset-name').textContent = entry.manifest.name;+ const revisions = el<HTMLSelectElement>('revisions');+ revisions.replaceChildren();+ for (const item of entries.filter((e) => e.manifest.assetId === entry.manifest.assetId)) {+ const option = node(+ 'option',+ `${new Date(item.manifest.createdAt).toLocaleString()} · ${item.manifest.description || item.manifest.revisionId.slice(0, 10)}`,+ );+ option.value = item.manifest.revisionId;+ option.selected = item.manifest.revisionId === entry.manifest.revisionId;+ revisions.append(option);+ }+ revisions.onchange = () => {+ const next = entries.find(+ (e) =>+ e.manifest.assetId === entry.manifest.assetId && e.manifest.revisionId === revisions.value,+ );+ if (next) void openDetail(next).catch(showError);+ };+ el('asset-description').textContent =+ entry.manifest.description ??+ entry.manifest.brief ??+ (entry.manifest.editable+ ? 'Source travels with this revision. Download the editable bundle to continue elsewhere.'+ : 'This GLB has no saved Kiln source. You can view and use the model.');+ el('provenance').textContent = entry.loose+ ? 'Standalone GLB. No source or build provenance supplied.'+ : JSON.stringify(entry.manifest, null, 2);+ const downloads = el('downloads');+ downloads.replaceChildren();+ for (const [file, label] of [+ ['asset.glb', 'Download GLB'],+ ...(entry.manifest.editable ? [['source.kiln.js', 'Download source']] : []),+ ...(!entry.loose+ ? [+ [+ 'editable.zip',+ entry.manifest.editable ? 'Download editable bundle' : 'Download asset bundle',+ ],+ ]+ : []),+ ]) {+ const link = node('a', label);+ link.href = href(entry, file!);+ link.download = `${entry.manifest.name.replace(/[^a-z0-9_-]/gi, '-')}${file === 'asset.glb' ? '.glb' : file === 'source.kiln.js' ? '.kiln.js' : '.zip'}`;+ downloads.append(link);+ }+ el<HTMLButtonElement>('refine').disabled = !entry.manifest.editable;+ el('asset-stats').replaceChildren();+ el('stage-status').textContent = 'Loading saved GLB…';+ wire = false;+ paused = false;+ el('wire').setAttribute('aria-pressed', 'false');+ el('play').textContent = 'Pause';+ const animation = el<HTMLSelectElement>('animation');+ animation.replaceChildren(new Option('Rest pose', ''));+ el<HTMLButtonElement>('play').disabled = true;+ try {+ stage ??= createAssetStage(el('stage'));+ const data = await bytes(entry, 'asset.glb');+ if (generation !== detailGeneration) return;+ const info = await stage.load(data);+ if (!info || generation !== detailGeneration) return;+ stage.wire(false);+ stage.lighting(el<HTMLSelectElement>('lighting').value);+ for (const [value, label] of [+ [info.triangles.toLocaleString(), 'triangles'],+ [info.meshes, 'meshes'],+ [info.materials, 'materials'],+ [`${(data.length / 1024).toFixed(0)} KB`, 'GLB'],+ ]) {+ const item = node('div');+ item.append(node('strong', String(value)), node('span', String(label)));+ el('asset-stats').append(item);+ }+ for (let i = 0; i < info.clips.length; i++)+ animation.append(new Option(info.clips[i], String(i)));+ el('stage-status').textContent = '';+ } catch (error) {+ if (generation === detailGeneration) {+ stage?.dispose();+ stage = undefined;+ el('stage-status').textContent =+ `3D preview unavailable: ${error instanceof Error ? error.message : error}. Downloads remain available.`;+ }+ }+}+async function openFiles(files: { name: string; bytes: Uint8Array }[]) {+ for (const file of files) {+ if (file.bytes.length > ASSET_LIMIT) throw new Error('File exceeds 64 MiB');+ if (file.name.toLowerCase().endsWith('.zip')) {+ for (const record of decodeAssetBundle(file.bytes)) {+ for (const [name, data] of Object.entries(record.files)) {+ const digest = Array.from(+ new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(data))),+ )+ .map((v) => v.toString(16).padStart(2, '0'))+ .join('');+ if (`sha256:${digest}` !== record.manifest.files[name]?.sha256)+ throw new Error(`Bundle integrity failure: ${name}`);+ }+ if (+ !opened.some(+ (e) =>+ e.manifest.revisionId === record.manifest.revisionId &&+ e.manifest.assetId === record.manifest.assetId,+ )+ )+ opened.push({ collection: 'opened-files', manifest: record.manifest, local: record });+ }+ } else {+ const id = `a_${crypto.randomUUID().replaceAll('-', '')}`;+ opened.push({+ collection: 'opened-files',+ loose: file.bytes,+ manifest: {+ version: 'kiln.asset.v1',+ assetId: id,+ revisionId: `r_${id}`,+ name: file.name.replace(/\.glb$/i, ''),+ tags: [],+ createdAt: new Date().toISOString(),+ editable: false,+ files: {},+ },+ });+ }+ }+ await loadCollection('opened-files');+}+el<HTMLInputElement>('open').onchange = async (event) => {+ try {+ const files = Array.from((event.target as HTMLInputElement).files ?? []);+ if (files.some((f) => f.size > ASSET_LIMIT)) throw new Error('File exceeds 64 MiB');+ await openFiles(+ await Promise.all(+ files.map(async (file) => ({+ name: file.name,+ bytes: new Uint8Array(await file.arrayBuffer()),+ })),+ ),+ );+ } catch (error) {+ showError(error);+ }+};+el('refresh').onclick = () => void loadCollection(currentCollection).catch(showError);+el('search').oninput = renderCards;+el('close-detail').onclick = () => el<HTMLDialogElement>('detail').close();+el<HTMLDialogElement>('detail').addEventListener('close', () => {+ detailGeneration++;+ stage?.dispose();+ stage = undefined;+ for (const url of urls.splice(0)) URL.revokeObjectURL(url);+ renderCards();+});+el('frame').onclick = () => stage?.reset();+el('wire').onclick = () => {+ wire = !wire;+ stage?.wire(wire);+ el('wire').setAttribute('aria-pressed', String(wire));+};+el<HTMLSelectElement>('lighting').onchange = (event) =>+ stage?.lighting((event.target as HTMLSelectElement).value);+el<HTMLSelectElement>('animation').onchange = (event) => {+ const value = (event.target as HTMLSelectElement).value;+ stage?.clip(value === '' ? -1 : Number(value));+ el<HTMLButtonElement>('play').disabled = value === '';+};+el('play').onclick = () => {+ paused = !paused;+ stage?.pause(paused);+ el('play').textContent = paused ? 'Play' : 'Pause';+};+el('refine').onclick = async () => {+ if (!chosen) return;+ const manifest = chosen.manifest;+ const text = chosen.local+ ? `Import the downloaded editable bundle using kiln import <bundle.zip>. Restore asset ${manifest.assetId}, revision ${manifest.revisionId}, using kiln_assets action=restore. Read its source with kiln_source, refine it with kiln_edit, review the result, and save a child revision with kiln_save. Requested change: `+ : `Use kiln_assets with action=restore, collection=${chosen.collection}, assetId=${manifest.assetId}, revisionId=${manifest.revisionId}. Read the returned programRef with kiln_source, refine it with kiln_edit, review the result, and save with kiln_save using assetId=${manifest.assetId}, parentRevision=${manifest.revisionId}, collection=${chosen.collection}. Requested change: `;+ try {+ await navigator.clipboard.writeText(text);+ el('refine').textContent = 'Instructions copied';+ } catch {+ el('provenance').textContent = text;+ el('provenance').parentElement?.setAttribute('open', '');+ }+};+el('export-selection').onclick = () => {+ try {+ const link = node('a');+ if (currentCollection === 'opened-files')+ link.href = blobUrl(+ encodeAssetBundle(entries.filter((e) => selected.has(key(e))).map((e) => e.local!)),+ 'application/zip',+ );+ else {+ const params = new URLSearchParams();+ for (const id of selected) params.append('revision', id);+ link.href = `/api/bundle?${params}`;+ }+ link.download = 'kiln-assets.zip';+ link.click();+ } catch (error) {+ showError(error);+ }+};+async function start() {+ collections = (await json('/api/collections')).collections;+ const remembered = recalled('kiln.collection');+ await loadCollection(+ collections.find((c) => c.id === remembered)?.id ?? collections[0]?.id ?? 'project',+ );+ if (new URLSearchParams(location.search).has('open')) {+ const response = await fetch('/api/standalone');+ if (!response.ok) throw new Error('File unavailable');+ await openFiles([+ {+ name: response.headers.get('Content-Type')?.includes('zip') ? 'asset.zip' : 'asset.glb',+ bytes: new Uint8Array(await response.arrayBuffer()),+ },+ ]);+ if (opened.length === 1) await openDetail(opened[0]!);+ }+}+void start().catch(showError);diff --git a/src/viewer/chat-app.ts b/src/viewer/chat-app.tsnew file mode 100644index 00000000..5d41b4be--- /dev/null+++ b/src/viewer/chat-app.ts@@ -0,0 +1,199 @@+/// <reference lib="dom" />+import { createAssetStage } from './scene';+import { encodeAssetBundle, type AssetRecord } from '../assets';+import { downloadChatFile, type ChatFileHost } from './chat-download';++declare global {+ interface Window {+ openai?: ChatFileHost & { openExternal?(input: { href: string }): void };+ }+}++const element = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;+const status = element('status');+let record: AssetRecord | undefined;+let downloadUrls: Record<string, string> = {};+let stage: ReturnType<typeof createAssetStage> | undefined;+let sequence = 0;+const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();+function request(method: string, params: unknown): Promise<unknown> {+ const id = ++sequence;+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ pending.delete(id);+ reject(new Error('Chat host did not respond.'));+ }, 20000);+ pending.set(id, {+ resolve(value) {+ clearTimeout(timer);+ resolve(value);+ },+ reject(error) {+ clearTimeout(timer);+ reject(error);+ },+ });+ window.parent.postMessage({ jsonrpc: '2.0', id, method, params }, '*');+ });+}+function notify(method: string, params: unknown = {}) {+ window.parent.postMessage({ jsonrpc: '2.0', method, params }, '*');+}+function decode(value: string) {+ return Uint8Array.from(atob(value), (c) => c.charCodeAt(0));+}+function encode(bytes: Uint8Array) {+ let binary = '';+ for (let i = 0; i < bytes.length; i += 8192)+ binary += String.fromCharCode(...bytes.subarray(i, i + 8192));+ return btoa(binary);+}+async function show(result: {+ isError?: boolean;+ content?: { type: string; text?: string }[];+ _meta?: {+ kilnAsset?: {+ error?: string;+ manifest: AssetRecord['manifest'];+ files: Record<string, string>;+ downloadUrls?: Record<string, string>;+ };+ };+}) {+ if (result.isError) {+ status.textContent =+ result.content?.find((item) => item.type === 'text')?.text ??+ 'This asset could not be opened.';+ return;+ }+ const asset = result._meta?.kilnAsset;+ if (!asset) return;+ if (asset.error) {+ status.textContent = asset.error;+ return;+ }+ record = {+ manifest: asset.manifest,+ files: Object.fromEntries(+ Object.entries(asset.files).map(([name, data]) => [name, decode(data)]),+ ),+ };+ element('name').textContent = record.manifest.name;+ downloadUrls = asset.downloadUrls ?? {};+ element('revision').textContent =+ `${record.manifest.editable ? 'Editable source included' : 'GLB asset'} · ${record.manifest.revisionId.slice(0, 10)}`;+ try {+ stage ??= createAssetStage(element('stage'));+ const stats = await stage.load(record.files['asset.glb']!);+ if (stats) {+ element('stats').textContent =+ `${stats.triangles.toLocaleString()} triangles · ${stats.materials} materials · ${(record.files['asset.glb']!.length / 1024).toFixed(0)} KB`;+ const clips = element<HTMLSelectElement>('clips');+ clips.replaceChildren(+ new Option('Rest pose', '-1'),+ ...stats.clips.map((name, i) => new Option(name, String(i))),+ );+ clips.hidden = !stats.clips.length;+ }+ status.textContent = 'Drag to orbit · Scroll to zoom';+ } catch (error) {+ const preview = record.files['preview.png'];+ if (preview) {+ const image = new Image();+ image.alt = record.manifest.name;+ image.src = `data:image/png;base64,${encode(preview)}`;+ element('stage').replaceChildren(image);+ }+ status.textContent = `3D preview unavailable: ${String(error)}`;+ }+ for (const button of document.querySelectorAll<HTMLButtonElement>('button[data-download]'))+ button.disabled = false;+ element<HTMLButtonElement>('source').hidden = !record.files['source.kiln.js'];+}+window.addEventListener('message', (event) => {+ if (event.source !== window.parent || event.data?.jsonrpc !== '2.0') return;+ const message = event.data;+ if (message.id !== undefined && !message.method) {+ const callback = pending.get(message.id);+ pending.delete(message.id);+ if (message.error)+ callback?.reject(+ Object.assign(new Error(message.error.message), { code: message.error.code }),+ );+ else callback?.resolve(message.result);+ }+ if (message.method === 'ui/notifications/tool-result') void show(message.params);+ if (message.method === 'ui/resource-teardown') {+ stage?.dispose();+ window.parent.postMessage({ jsonrpc: '2.0', id: message.id, result: {} }, '*');+ }+});+element('reset').onclick = () => stage?.reset();+element<HTMLSelectElement>('clips').onchange = (event) =>+ stage?.clip(Number((event.target as HTMLSelectElement).value));+for (const button of document.querySelectorAll<HTMLButtonElement>('button[data-download]')) {+ button.onclick = async () => {+ if (!record) return;+ const kind = button.dataset.download!;+ const filename =+ kind === 'bundle' ? 'editable.zip' : kind === 'source' ? 'source.kiln.js' : 'asset.glb';+ const bytes = kind === 'bundle' ? encodeAssetBundle([record]) : record.files[filename]!;+ const mimeType =+ kind === 'bundle'+ ? 'application/zip'+ : kind === 'source'+ ? 'text/javascript'+ : 'model/gltf-binary';+ const slug = record.manifest.name.replace(/[^a-zA-Z0-9_-]+/g, '-').slice(0, 80);+ button.disabled = true;+ status.textContent = 'Requesting download…';+ try {+ const host =+ typeof window.openai?.uploadFile === 'function' &&+ typeof window.openai?.getFileDownloadUrl === 'function'+ ? window.openai+ : undefined;+ const result = await downloadChatFile(+ bytes,+ `${slug}-${filename}`,+ mimeType,+ request,+ host,+ downloadUrls[filename],+ );+ if (result.downloadUrl) {+ const link = document.createElement('a');+ link.href = result.downloadUrl;+ link.textContent = `Save ${slug}-${filename}`;+ link.style.color = '#d5f4a2';+ link.target = '_blank';+ link.rel = 'noopener noreferrer';+ link.onclick = (event) => {+ if (window.openai?.openExternal) {+ event.preventDefault();+ window.openai.openExternal({ href: result.downloadUrl! });+ }+ };+ status.replaceChildren('Download ready. ', link);+ } else status.textContent = 'Download requested.';+ } catch (error) {+ status.textContent = `Download unavailable in this host: ${(error as Error).message}`;+ } finally {+ button.disabled = false;+ }+ };+}+void request('ui/initialize', {+ appInfo: { name: 'Kiln Asset Viewer', version: '0.6.0' },+ appCapabilities: {},+ protocolVersion: '2026-01-26',+})+ .then(() => {+ notify('ui/notifications/initialized');+ notify('ui/notifications/size-changed', {+ height: document.documentElement.scrollHeight,+ });+ })+ .catch((error) => {+ status.textContent = error.message;+ });diff --git a/src/viewer/chat-download.test.ts b/src/viewer/chat-download.test.tsnew file mode 100644index 00000000..d1fa7961--- /dev/null+++ b/src/viewer/chat-download.test.ts@@ -0,0 +1,60 @@+import { expect, test } from 'bun:test';+import { downloadChatFile } from './chat-download';+test('uses a host-provided URL without uploading files when the standard bridge is unsupported', async () => {+ const result = await downloadChatFile(+ new Uint8Array([1]),+ 'asset.glb',+ 'model/gltf-binary',+ async () => {+ throw Object.assign(new Error('Method not found'), { code: -32601 });+ },+ undefined,+ 'http://127.0.0.1:4321/asset.glb',+ );+ expect(result.downloadUrl).toBe('http://127.0.0.1:4321/asset.glb');+});++test('uses the standard download bridge without uploading a duplicate', async () => {+ const calls: string[] = [];+ await downloadChatFile(+ new Uint8Array([1, 2]),+ 'asset.glb',+ 'model/gltf-binary',+ async (method) => {+ calls.push(method);+ return {};+ },+ );+ expect(calls).toEqual(['ui/download-file']);+});+test('uses ChatGPT file storage when the standard method is unsupported', async () => {+ let uploaded: File | undefined;+ const result = await downloadChatFile(+ new Uint8Array([1, 2]),+ 'asset.glb',+ 'model/gltf-binary',+ async () => {+ throw Object.assign(new Error('Method not found'), { code: -32601 });+ },+ {+ uploadFile: async (file) => {+ uploaded = file;+ return { fileId: 'file-test' };+ },+ getFileDownloadUrl: async ({ fileId }) => {+ expect(fileId).toBe('file-test');+ return { downloadUrl: 'https://example.com/download' };+ },+ },+ );+ expect(uploaded?.name).toBe('asset.glb');+ expect(Array.from(new Uint8Array(await uploaded!.arrayBuffer()))).toEqual([1, 2]);+ expect(result.downloadUrl).toBe('https://example.com/download');+});+test('does not upload after a denied download', async () => {+ await expect(+ downloadChatFile(new Uint8Array([1]), 'x.glb', 'model/gltf-binary', async () => {+ throw new Error('Permission denied');+ }),+ ).rejects.toThrow('Permission denied');+});diff --git a/src/viewer/chat-download.ts b/src/viewer/chat-download.tsnew file mode 100644index 00000000..3d6da608--- /dev/null+++ b/src/viewer/chat-download.ts@@ -0,0 +1,51 @@+/// <reference lib="dom" />+export interface ChatFileHost {+ uploadFile(file: File): Promise<{ fileId: string }>;+ getFileDownloadUrl(input: { fileId: string }): Promise<{ downloadUrl: string }>;+}+export async function downloadChatFile(+ bytes: Uint8Array,+ filename: string,+ mimeType: string,+ request: (method: string, params: unknown) => Promise<unknown>,+ chatHost?: ChatFileHost,+ deliveryUrl?: string,+): Promise<{ downloadUrl?: string }> {+ let binary = '';+ for (let i = 0; i < bytes.length; i += 8192)+ binary += String.fromCharCode(...bytes.subarray(i, i + 8192));+ try {+ const result = (await request('ui/download-file', {+ contents: [+ {+ type: 'resource',+ resource: {+ uri: `file:///${filename}`,+ mimeType,+ blob: btoa(binary),+ },+ },+ ],+ })) as { isError?: boolean };+ if (result?.isError) throw new Error('The chat host could not download this file.');+ return {};+ } catch (error) {+ if ((error as { code?: number }).code !== -32601) throw error;+ if (deliveryUrl) {+ const url = new URL(deliveryUrl);+ if (+ url.protocol !== 'https:' &&+ !(url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))+ )+ throw new Error('Invalid host download URL');+ return { downloadUrl: url.href };+ }+ if (!chatHost) throw error;+ // Only runs after the user chooses a specific download. No automatic library save.+ const file = new File([Uint8Array.from(bytes)], filename, { type: mimeType });+ const { fileId } = await chatHost.uploadFile(file);+ const { downloadUrl } = await chatHost.getFileDownloadUrl({ fileId });+ if (new URL(downloadUrl).protocol !== 'https:') throw new Error('Invalid host download URL');+ return { downloadUrl };+ }+}diff --git a/src/viewer/chat.html b/src/viewer/chat.htmlnew file mode 100644index 00000000..83658d7a--- /dev/null+++ b/src/viewer/chat.html@@ -0,0 +1,122 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Kiln Asset</title>+ <style>+ * {+ box-sizing: border-box;+ }+ body {+ margin: 0;+ font:+ 14px system-ui,+ sans-serif;+ background: #151a12;+ color: #f1f2e7;+ }+ header {+ padding: 18px 20px 12px;+ display: flex;+ justify-content: space-between;+ align-items: center;+ }+ h1 {+ font-size: 19px;+ margin: 5px 0;+ }+ small,+ #revision,+ #stats,+ #status {+ color: #b6bfaa;+ font-size: 12px;+ }+ small {+ letter-spacing: 2px;+ font-weight: 700;+ }+ #stage {+ height: 320px;+ width: 100%;+ position: relative;+ }+ #stage canvas {+ display: block;+ width: 100%;+ height: 100%;+ }+ #stage img {+ width: 100%;+ height: 100%;+ object-fit: contain;+ }+ .bar {+ padding: 10px 20px;+ display: flex;+ gap: 8px;+ align-items: center;+ flex-wrap: wrap;+ }+ button,+ select {+ font: inherit;+ background: #2b3424;+ border: 1px solid #4b5840;+ color: #f1f2e7;+ border-radius: 8px;+ padding: 9px 12px;+ cursor: pointer;+ }+ button:hover {+ background: #3b4930;+ }+ button:disabled {+ opacity: 0.45;+ cursor: wait;+ }+ button.primary {+ background: #d5f4a2;+ color: #20300f;+ border-color: #d5f4a2;+ font-weight: 650;+ }+ #status {+ padding: 4px 20px 16px;+ min-height: 35px;+ margin: 0;+ }+ #stats {+ margin-right: auto;+ }+ [hidden] {+ display: none !important;+ }+ </style>+ </head>+ <body>+ <header>+ <div>+ <small>KILN</small>+ <h1 id="name">Your 3D asset</h1>+ <div id="revision">Saved with provenance</div>+ </div>+ <button id="reset" aria-label="Reset camera">Reset view</button>+ </header>+ <div id="stage" aria-label="Interactive 3D asset viewer"></div>+ <div class="bar">+ <span id="stats"></span+ ><select id="clips" aria-label="Animation" hidden></select>+ </div>+ <div class="bar">+ <button class="primary" data-download="glb" disabled>Download GLB</button+ ><button data-download="bundle" disabled>Editable bundle</button+ ><button id="source" data-download="source" disabled>Source code</button>+ </div>+ <p id="status" role="status">Loading asset from Kiln…</p>+ <script type="module">+ /* KILN_CHAT_APP */+ </script>+ </body>+</html>diff --git a/src/viewer/index.html b/src/viewer/index.htmlnew file mode 100644index 00000000..02b25cae--- /dev/null+++ b/src/viewer/index.html@@ -0,0 +1,11 @@+<!doctype html>+<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kiln · Your assets</title><link rel="stylesheet" href="/style.css"></head>+<body><header><a class="brand" href="/">K<span>ILN</span><small>ASSET LIBRARY</small></a><div class="header-actions"><span class="local">LOCAL · YOUR FILES</span><label class="button secondary">Open GLB or bundle<input id="open" type="file" accept=".glb,.zip" multiple hidden></label></div></header>+<main><aside><div class="section-label">YOUR COLLECTIONS</div><nav id="collections" aria-label="Collections"></nav><div class="aside-note">Saved assets stay with their source.<br>Open any revision. Keep building.</div></aside>+<section class="library"><div class="heading"><div><div class="eyebrow">MADE WITH KILN</div><h1 id="collection-title">Your assets</h1><p id="collection-caption">A place for what you’re building.</p></div><button id="refresh" class="secondary">Refresh</button></div>+<div class="toolbar"><input id="search" type="search" placeholder="Find an asset or tag…" aria-label="Search assets"><span id="count"></span><button id="export-selection" class="secondary" disabled>Export selected</button></div>+<div id="status" role="status" aria-live="polite"></div><div id="cards" class="cards"></div></section></main>+<dialog id="detail" aria-labelledby="asset-name"><div class="detail-top"><div><span class="eyebrow">ASSET / REVISION</span><h2 id="asset-name"></h2></div><button id="close-detail" class="secondary">Close</button></div>+<div class="detail-layout"><div class="stage-wrap"><div id="stage"></div><p id="stage-status" role="status"></p><div class="stage-controls"><button id="frame">Reset view</button><button id="wire" aria-pressed="false">Wireframe</button><select id="lighting" aria-label="Lighting"><option value="studio">Studio</option><option value="soft">Soft</option><option value="bright">Bright</option></select><select id="animation" aria-label="Animation"><option value="">Rest pose</option></select><button id="play" disabled>Pause</button></div><p class="gesture">Drag to orbit · Scroll to zoom · Right-drag to pan</p></div>+<section class="details"><label class="field">Revision<select id="revisions"></select></label><div id="asset-stats" class="stats"></div><p id="asset-description"></p><div id="downloads" class="downloads"></div><button id="refine" class="secondary">Copy refinement instructions</button><details><summary>Source & build record</summary><pre id="provenance"></pre></details></section></div></dialog>+<script type="module" src="/app.js"></script></body></html>diff --git a/src/viewer/scene.ts b/src/viewer/scene.tsnew file mode 100644index 00000000..af74a7a7--- /dev/null+++ b/src/viewer/scene.ts@@ -0,0 +1,173 @@+/// <reference lib="dom" />+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { validateAssetGlb } from '../assets';++/** The gallery's local studio lighting, orbit controls, and framing in a small standalone surface. */+export function createAssetStage(container: HTMLElement) {+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));+ renderer.setClearColor(0x151a12);+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.15;+ container.replaceChildren(renderer.domElement);+ const scene = new THREE.Scene();+ const camera = new THREE.PerspectiveCamera(40, 1, 0.01, 1000);+ const controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ const pmrem = new THREE.PMREMGenerator(renderer);+ const room = new RoomEnvironment();+ const environment = pmrem.fromScene(room, 0.04);+ scene.environment = environment.texture;+ room.dispose();+ pmrem.dispose();+ const sun = new THREE.DirectionalLight(0xfff1d7, 2.4);+ sun.position.set(4, 8, 5);+ scene.add(sun);+ scene.add(new THREE.HemisphereLight(0xe1edda, 0x4d493d, 1.7));+ let root: THREE.Group | undefined;+ let mixer: THREE.AnimationMixer | undefined;+ let clips: THREE.AnimationClip[] = [];+ let running = true;+ let last = performance.now();+ let frame = 0;+ let generation = 0;+ let disposed = false;+ const disposeModel = (model: THREE.Object3D) => {+ const geometries = new Set<THREE.BufferGeometry>();+ const materials = new Set<THREE.Material>();+ const textures = new Set<THREE.Texture>();+ model.traverse((object) => {+ const mesh = object as THREE.Mesh;+ if (!mesh.isMesh) return;+ geometries.add(mesh.geometry);+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {+ materials.add(material);+ for (const value of Object.values(material))+ if (value instanceof THREE.Texture) textures.add(value);+ }+ });+ for (const value of [...geometries, ...materials, ...textures]) value.dispose();+ };+ const reset = () => {+ if (!root) return;+ const box = new THREE.Box3().setFromObject(root, true);+ const center = box.getCenter(new THREE.Vector3());+ const size = box.getSize(new THREE.Vector3());+ const radius = Math.max(size.length() / 2, 0.01);+ const fov = Math.min(+ (camera.fov * Math.PI) / 180,+ 2 * Math.atan(Math.tan((camera.fov * Math.PI) / 360) * camera.aspect),+ );+ const distance = (radius / Math.sin(fov / 2)) * 1.12;+ controls.target.copy(center);+ camera.position+ .copy(center)+ .add(new THREE.Vector3(1, 0.65, 1.25).normalize().multiplyScalar(distance));+ camera.near = Math.max(radius / 1000, 0.0001);+ camera.far = distance + radius * 100;+ controls.minDistance = radius * 0.1;+ controls.maxDistance = radius * 80;+ camera.updateProjectionMatrix();+ controls.update();+ };+ const resize = new ResizeObserver(() => {+ const width = container.clientWidth;+ const height = container.clientHeight;+ if (!width || !height) return;+ renderer.setSize(width, height);+ camera.aspect = width / height;+ camera.updateProjectionMatrix();+ });+ resize.observe(container);+ const animate = (now: number) => {+ if (disposed) return;+ const dt = Math.min((now - last) / 1000, 0.1);+ last = now;+ if (running) mixer?.update(dt);+ controls.update();+ renderer.render(scene, camera);+ frame = requestAnimationFrame(animate);+ };+ frame = requestAnimationFrame(animate);+ return {+ async load(bytes: Uint8Array) {+ const current = ++generation;+ validateAssetGlb(bytes);+ const manager = new THREE.LoadingManager();+ manager.setURLModifier((url) => {+ if (!url.startsWith('blob:') && !url.startsWith('data:'))+ throw new Error('External model resources are not loaded');+ return url;+ });+ const gltf = await new GLTFLoader(manager).parseAsync(Uint8Array.from(bytes).buffer, '');+ if (disposed || current !== generation) {+ disposeModel(gltf.scene);+ return undefined;+ }+ if (root) {+ mixer?.stopAllAction();+ mixer?.uncacheRoot(root);+ scene.remove(root);+ disposeModel(root);+ }+ root = gltf.scene;+ scene.add(root);+ clips = gltf.animations;+ mixer = new THREE.AnimationMixer(root);+ running = true;+ const width = container.clientWidth,+ height = container.clientHeight;+ renderer.setSize(width, height);+ camera.aspect = width / height;+ reset();+ let triangles = 0,+ meshes = 0;+ const materials = new Set<THREE.Material>();+ root.traverse((o) => {+ const mesh = o as THREE.Mesh;+ if (!mesh.isMesh) return;+ meshes++;+ triangles +=+ ((mesh.geometry.index?.count ?? mesh.geometry.attributes.position?.count ?? 0) / 3) *+ ((mesh as THREE.InstancedMesh).isInstancedMesh ? (mesh as THREE.InstancedMesh).count : 1);+ for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material])+ materials.add(m);+ });+ return { triangles, meshes, materials: materials.size, clips: clips.map((c) => c.name) };+ },+ reset,+ wire(value: boolean) {+ root?.traverse((o) => {+ const mesh = o as THREE.Mesh;+ if (mesh.isMesh)+ for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material])+ if ('wireframe' in m) m.wireframe = value;+ });+ },+ lighting(value: string) {+ renderer.toneMappingExposure = value === 'bright' ? 1.65 : value === 'soft' ? 0.85 : 1.15;+ sun.intensity = value === 'soft' ? 0.8 : 2.4;+ },+ clip(index: number) {+ mixer?.stopAllAction();+ if (clips[index]) mixer?.clipAction(clips[index]!).play();+ },+ pause(value: boolean) {+ running = !value;+ },+ dispose() {+ disposed = true;+ generation++;+ cancelAnimationFrame(frame);+ resize.disconnect();+ controls.dispose();+ if (root) disposeModel(root);+ environment.dispose();+ renderer.dispose();+ container.replaceChildren();+ },+ };+}diff --git a/src/viewer/style.css b/src/viewer/style.cssnew file mode 100644index 00000000..6965a945--- /dev/null+++ b/src/viewer/style.css@@ -0,0 +1,2 @@++:root{font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#e7e2da;background:#111210;font-synthesis:none;color-scheme:dark;--dim:#9b9e92;--line:#30352c;--accent:#d6ed9e}*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button,.button,select{border:1px solid var(--line);border-radius:6px;background:#262d20;color:#e7e2da;padding:10px 14px;cursor:pointer;text-decoration:none}button:hover,.button:hover{border-color:#91a56c;background:#303e26}button:disabled{opacity:.4;cursor:default}.secondary{background:transparent}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--accent);outline-offset:3px}header{height:90px;padding:0 40px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand{font-size:32px;font-weight:850;color:var(--accent);text-decoration:none;letter-spacing:-2px;display:flex;align-items:center;gap:0}.brand span{color:#e7e2da}.brand small{font-size:10px;letter-spacing:2px;font-weight:500;margin-left:22px;color:var(--dim)}.header-actions{display:flex;align-items:center;gap:25px}.local{font-size:10px;letter-spacing:1.6px;color:var(--dim)}main{display:grid;grid-template-columns:230px 1fr;min-height:calc(100vh - 90px)}aside{padding:36px 20px;border-right:1px solid var(--line);display:flex;flex-direction:column}.section-label,.eyebrow{font-size:10px;letter-spacing:2px;color:var(--dim)}.section-label{padding:0 12px 18px}nav{display:grid;gap:8px}nav button{text-align:left;border-color:transparent;background:transparent;color:var(--dim)}nav button.active{background:#252d1c;color:var(--accent);border-color:#3a482a}.aside-note{margin-top:auto;padding:60px 12px 0;font-size:12px;color:#767b6e;line-height:1.8}.library{padding:44px 46px;min-width:0}.heading{display:flex;align-items:center;justify-content:space-between}h1{font-size:38px;letter-spacing:-1.6px;font-weight:500;margin:12px 0}h2{font-size:24px;font-weight:500;margin:8px 0 0}p{color:var(--dim);line-height:1.6}.heading p{font-size:14px;margin:0}.toolbar{display:flex;align-items:center;gap:18px;margin:32px 0 22px}.toolbar input{background:#191c16;color:#e7e2da;padding:12px 15px;border:1px solid var(--line);border-radius:6px;max-width:360px;width:100%}#count{margin-right:auto;color:var(--dim);font-size:12px;white-space:nowrap}.cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(245px,1fr));gap:22px}.card{border:1px solid var(--line);border-radius:10px;background:#191c17;overflow:hidden;position:relative}.card:hover{border-color:#6e7e57}.card-open{display:block;width:100%;border:0;padding:0;border-radius:0;background:transparent;text-align:left}.card-open:hover{background:transparent}.thumb{height:185px;display:flex;align-items:center;justify-content:center;background:radial-gradient(ellipse at 50% 70%,#30372a,#181c15);color:#5f6b50;font-size:36px}.thumb img{width:100%;height:100%;object-fit:contain}.card-content{padding:17px 19px 20px}.card-title{font-size:16px;font-weight:550;display:block;margin-bottom:8px}.card-meta{font-size:11px;color:var(--dim)}.tags{display:flex;gap:6px;flex-wrap:wrap;margin-top:13px}.tag{font-size:10px;color:#b4c397;background:#2a3223;padding:4px 8px;border-radius:4px}.selection{position:absolute;top:12px;right:12px;width:18px;height:18px;accent-color:var(--accent)}.empty{padding:70px 24px;text-align:center;grid-column:1/-1;border:1px dashed #39412f;border-radius:10px;color:var(--dim)}.empty b{display:block;color:#e7e2da;font-weight:500;font-size:20px;margin-bottom:12px}.empty code{display:block;margin-top:24px;font-size:12px;color:var(--accent)}#status{font-size:13px;color:#e1bd89;margin-bottom:15px}dialog{background:#141712;color:#e7e2da;border:1px solid #465239;border-radius:12px;padding:0;width:min(1250px,96vw);max-height:94vh}dialog::backdrop{background:#030502c9;backdrop-filter:blur(7px)}.detail-top{display:flex;justify-content:space-between;align-items:center;padding:22px 28px;border-bottom:1px solid var(--line)}.detail-layout{display:grid;grid-template-columns:minmax(0,1fr) 330px}.stage-wrap{position:relative;background:#151a12;min-width:0}#stage{height:clamp(280px,55vh,530px);width:100%}#stage canvas{display:block;width:100%;height:100%}#stage-status{position:absolute;left:20px;top:8px;font-size:12px;max-width:80%;pointer-events:none}.stage-controls{display:flex;justify-content:center;flex-wrap:wrap;gap:7px;padding:14px}.stage-controls button,.stage-controls select{font-size:11px;padding:9px}.stage-controls [aria-pressed=true]{color:var(--accent);border-color:#9bac80}.gesture{text-align:center;font-size:10px;letter-spacing:.5px;padding-bottom:14px}.details{padding:24px;border-left:1px solid var(--line);overflow-wrap:anywhere}.field{display:grid;gap:8px;font-size:11px;color:var(--dim);letter-spacing:1px}.field select{width:100%;font-size:12px;letter-spacing:0}.stats{display:grid;grid-template-columns:1fr 1fr;gap:15px;margin:24px 0;font-size:12px}.stats strong{display:block;font-size:18px;font-weight:500;color:#e7e2da;margin-bottom:5px}.stats span{font-size:10px;color:var(--dim)}.details p{font-size:12px}.downloads{display:grid;gap:9px;margin:22px 0 12px}.downloads a{display:block;text-decoration:none;text-align:center;color:#e7e2da;background:#28341f;padding:11px;border:1px solid #485d35;border-radius:6px;font-size:12px}.downloads a:first-child{color:#14200a;background:var(--accent);border-color:var(--accent)}#refine{font-size:11px;width:100%}.details details{margin-top:24px;border-top:1px solid var(--line);padding-top:17px;font-size:11px;color:var(--dim)}summary{cursor:pointer}pre{white-space:pre-wrap;font-size:10px;line-height:1.6;max-height:260px;overflow:auto;color:#9da98e}@media(max-width:800px){header{height:75px;padding:0 18px}.brand small,.local{display:none}.header-actions{gap:8px;font-size:11px}main{display:block}aside{border-right:0;border-bottom:1px solid var(--line);padding:15px}nav{display:flex;overflow:auto}.section-label,.aside-note{display:none}.library{padding:28px 18px}.toolbar{flex-wrap:wrap;gap:10px}.toolbar input{max-width:100%}.cards{grid-template-columns:repeat(auto-fill,minmax(210px,1fr))}.detail-layout{display:block}.details{border-left:0;border-top:1px solid var(--line)}#stage{height:380px}.detail-top{padding:18px}.heading h1{font-size:30px}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto}}