Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(vscode): ship the three.ws 3D extension that previews and generates GLBs in the editor

nirholas2898d7e939dd
diff --git a/docs/vscode.md b/docs/vscode.md
new file mode 100644
index 000000000..439425f08
--- /dev/null
+++ b/docs/vscode.md
@@ -0,0 +1,146 @@
+# three.ws in VS Code
+
+Two extensions put the platform inside the editor. **three.ws 3D** makes model
+files and 3D generation native to VS Code. **three.ws x402** does the same for
+paid endpoints. This page covers the first; see [x402](./x402.md#open-source-packages) for
+the second.
+
+| | |
+|---|---|
+| **Extension** | three.ws 3D (`threews.vscode-3d`) |
+| **Source** | [`packages/vscode-3d`](../packages/vscode-3d) |
+| **Requires** | VS Code 1.85 or newer |
+| **Auth** | None. Generation runs on the free lane. |
+
+## What it does
+
+VS Code has no idea what a `.glb` is. Every 3D asset in a repository is an opaque
+binary you have to leave the editor to look at: upload it somewhere, open a
+browser viewer, come back. This extension closes that loop.
+
+**Model files render in an editor tab.** Double-click any `.glb` or `.gltf` and
+it opens in a three.js viewer instead of the "binary file not shown" screen.
+Orbit with the left mouse button, pan with the right, zoom with the wheel.
+Animation clips get a picker, a play/pause button, and a scrub bar. There are
+toggles for a wireframe, the skeleton, the ground grid, and a slow auto-orbit,
+plus a **Snapshot** button that writes the current camera view as a PNG next to
+the model.
+
+Draco, KTX2/Basis, and meshopt assets decode locally: the decoders ship inside
+the extension rather than loading from a CDN, so a meshopt-compressed three.ws
+avatar (which is most of them) renders on a plane with no connection.
+
+**Every model carries a report.** The panel behind the **Report** button lists
+triangles, vertices, meshes, materials, textures and their weight, animations,
+rig size, and the glTF extensions in use, followed by optimization notes:
+oversized textures, non-indexed primitives, a mesh that would benefit from
+compression. It is the same inspector that powers the
+[`/validation`](https://three.ws/validation) page, running in the extension host,
+so your model is never uploaded anywhere to be measured.
+
+**Models can be generated in place.** `3D: Generate a Model from Text` describes
+an object; `3D: Generate an Avatar from Text` describes a character. Both call
+the free [3D Studio](./mcp-studio.md) lane, save the finished GLB into your
+workspace, and open it in the viewer. `3D: Rig a Model for Animation` sends a
+static model to the auto-rigger and brings back one with a humanoid skeleton.
+
+**The embed snippet is generated correctly.** `3D: Insert <agent-3d> Embed
+Snippet` reads the live release manifest, pins the current library version, adds
+its subresource-integrity hash, and writes the whole thing at your cursor:
+
+```html
+<script
+ type="module"
+ src="https://three.ws/agent-3d/1.5.2/agent-3d.js"
+ integrity="sha384-…"
+ crossorigin="anonymous"
+></script>
+
+<agent-3d
+ body="https://three.ws/cdn/creations/…/mesh.glb"
+ style="width: 400px; height: 500px; display: block;"
+></agent-3d>
+```
+
+That is the snippet [Embedding](./embedding.md) documents, with the pin already
+resolved. Set `threews3d.embedChannel` to `latest`, `1`, or `1.5` if you would
+rather follow a moving channel than pin exact bytes.
+
+**The sidebar has both halves of your library.** The three.ws icon in the
+activity bar lists every model in the workspace (grouped by folder, with file
+sizes) and, below it, recent public creations from the forge. Preview any of
+those in the viewer, and import the ones you want with one click.
+
+## Install
+
+The extension is not on the Marketplace yet. Build and install it from the
+repository:
+
+```bash
+cd packages/vscode-3d
+npm install
+npm run package
+code --install-extension vscode-3d-0.1.0.vsix
+```
+
+For development, open `packages/vscode-3d` in VS Code and press <kbd>F5</kbd> to
+launch an Extension Development Host with the extension loaded, or run
+`npm run watch` to rebuild on every change.
+
+## Commands
+
+| Command | What it does |
+|---|---|
+| `3D: Generate a Model from Text` | Free text to 3D. Saves the GLB and opens it. |
+| `3D: Generate an Avatar from Text` | Same, tuned for characters. |
+| `3D: Rig a Model for Animation` | Adds a humanoid skeleton to a static model. |
+| `3D: Insert <agent-3d> Embed Snippet` | Writes a pinned, SRI-checked embed at the cursor. |
+| `3D: Preview a Model URL` | Opens any hosted `.glb` in the viewer. |
+| `3D: Open in the three.ws Viewer` | Opens the model in the browser viewer. |
+| `3D: Copy the Model's three.ws URL` | Copies the hosted URL to the clipboard. |
+| `3D: Save a PNG Snapshot of the View` | Writes the current view beside the model. |
+
+## Settings
+
+| Setting | Default | Purpose |
+|---|---|---|
+| `threews3d.origin` | `https://three.ws` | Host of the studio API and the gallery. |
+| `threews3d.downloadFolder` | `models` | Workspace folder generated models are saved into. |
+| `threews3d.tier` | `draft` | Detail level for text to 3D: `draft`, `standard`, or `high`. All free. |
+| `threews3d.environment` | `studio` | Image-based lighting: `studio`, `neutral`, or `none`. |
+| `threews3d.showGrid` | `true` | Show the ground grid when a model opens. |
+| `threews3d.autoRotate` | `false` | Orbit the camera automatically when a model opens. |
+| `threews3d.embedChannel` | `pinned` | `pinned` resolves the current release plus its SRI hash; or name a channel. |
+
+## What talks to the network, and what does not
+
+Three public, unauthenticated endpoints, and nothing else:
+
+| Call | Endpoint | When |
+|---|---|---|
+| Generate, rig | `POST /api/mcp-studio` | Only when you run a generate or rig command. |
+| Gallery feed | `GET /api/forge-gallery` | The first time you expand the gallery view. |
+| Release pin | `GET /agent-3d/versions.json` | When you insert an embed snippet. |
+
+The viewer itself is local. Its webview runs under a content security policy that
+allows a single nonce-gated script and no remote origin, so the only thing that
+crosses the network while you look at a model is the model file. Opening,
+inspecting, animating, and snapshotting a `.glb` makes no requests at all.
+
+## Embedding or rigging a local file
+
+Both need a URL that a browser or the rigger can fetch. Models the extension
+generated or imported remember where they came from, so those commands work
+without asking. For a `.glb` that has only ever existed on your disk, the
+extension asks for the https URL where it is hosted rather than handing you a
+snippet that renders nothing. Upload it (any static host works, or generate it
+through the extension in the first place) and paste the URL.
+
+## Related
+
+- [Embedding](./embedding.md) documents every `<agent-3d>` attribute.
+- [3D Studio MCP](./mcp-studio.md) is the free generation lane the extension
+ calls, and the same tools are available to any MCP client.
+- [x402](./x402.md) covers the sibling extension for paid endpoints.
+- [The 3D asset pipeline](./3d-asset-pipeline.md) explains what the optimization
+ notes in the report are asking for.
diff --git a/packages/vscode-3d/.gitignore b/packages/vscode-3d/.gitignore
new file mode 100644
index 000000000..37f37efe8
--- /dev/null
+++ b/packages/vscode-3d/.gitignore
@@ -0,0 +1,6 @@
+dist/
+node_modules/
+media/viewer.js
+media/viewer.js.map
+media/vendor/
+*.vsix
diff --git a/packages/vscode-3d/.vscodeignore b/packages/vscode-3d/.vscodeignore
new file mode 100644
index 000000000..59078ac7a
--- /dev/null
+++ b/packages/vscode-3d/.vscodeignore
@@ -0,0 +1,9 @@
+.vscode/**
+src/**
+webview/**
+test/**
+build.mjs
+.gitignore
+**/*.map
+**/tsconfig.json
+node_modules/**
diff --git a/packages/vscode-3d/CHANGELOG.md b/packages/vscode-3d/CHANGELOG.md
new file mode 100644
index 000000000..f7c381d1f
--- /dev/null
+++ b/packages/vscode-3d/CHANGELOG.md
@@ -0,0 +1,24 @@
+# Changelog
+
+## 0.1.0
+
+First release.
+
+- **3D viewer for `.glb` and `.gltf`.** Opens as the default editor for model
+ files: orbit, animation playback with a clip picker and scrub bar, wireframe,
+ skeleton overlay, ground grid, auto-orbit, and a PNG snapshot saved next to the
+ model. Draco, KTX2, and meshopt assets decode locally, so a compressed three.ws
+ avatar renders with no network round trip.
+- **Model report.** Triangles, vertices, meshes, materials, textures and their
+ weight, animations, rig size, extensions, and optimization notes, produced by
+ the same inspector behind the three.ws `/validation` page. The file never
+ leaves the machine.
+- **Generate from a prompt.** `3D: Generate a Model from Text` and
+ `3D: Generate an Avatar from Text` call the free three.ws studio lane, save the
+ GLB into the workspace, and open it in the viewer.
+- **Rig for animation.** Sends a static model to the three.ws auto-rigger and
+ saves the rigged result next to it.
+- **Insert an `<agent-3d>` embed.** Resolves the current library release and its
+ SRI hash from the live manifest, then writes the snippet at the cursor.
+- **Forge gallery.** Recent public creations from three.ws, previewable in the
+ viewer and importable into the workspace in one click.
diff --git a/packages/vscode-3d/LICENSE b/packages/vscode-3d/LICENSE
new file mode 100644
index 000000000..b5ae2a4e1
--- /dev/null
+++ b/packages/vscode-3d/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/packages/vscode-3d/README.md b/packages/vscode-3d/README.md
new file mode 100644
index 000000000..b42c4dbcb
--- /dev/null
+++ b/packages/vscode-3d/README.md
@@ -0,0 +1,156 @@
+# three.ws 3D for VS Code
+
+Preview 3D models where you already are. This extension makes `.glb` and `.gltf`
+files first-class in VS Code: double-click one and it renders, animates, and
+reports on itself in an editor tab, next to the code that ships it. When you need
+a model that does not exist yet, generate it from a text prompt on the free
+[three.ws](https://three.ws) lane without leaving the window.
+
+Nothing here is a preview stub. The viewer is three.js with the same lighting and
+decoders the three.ws site uses, the report is the platform's own inspector, and
+generation calls the live studio API.
+
+## Features
+
+- **A real viewer, as the default editor for model files.** Orbit, pan, and zoom
+ with the mouse. Animation clips get a picker, a play/pause button, and a scrub
+ bar. Toggle a wireframe, the skeleton, the ground grid, or a slow auto-orbit.
+ Draco, KTX2/Basis, and meshopt assets decode locally from decoders shipped
+ inside the extension, so a compressed three.ws avatar renders offline.
+- **Model report.** Triangles, vertices, meshes, materials, texture count and
+ weight, animations, rig size, and glTF extensions, plus optimization notes
+ ("3 textures at 4K", "re-indexing typically halves the vertex count"). It is
+ the same inspector that powers the three.ws `/validation` page, running in the
+ extension host: your model is never uploaded anywhere to be measured.
+- **Text to 3D.** `3D: Generate a Model from Text` for an object or prop,
+ `3D: Generate an Avatar from Text` for a character. Both run on the free lane
+ (no key, no account), save the GLB into your workspace, and open it.
+- **Auto-rigging.** `3D: Rig a Model for Animation` sends a static model to the
+ three.ws rigger and brings back one with a humanoid skeleton and skin weights.
+- **Embed snippet, correctly pinned.** `3D: Insert <agent-3d> Embed Snippet`
+ resolves the current library version and its subresource-integrity hash from
+ the live release manifest and writes a ready-to-paste snippet at your cursor.
+- **Forge gallery.** Browse recent public three.ws creations in the sidebar,
+ preview any of them in the viewer, and import the ones you want.
+- **PNG snapshots.** `Snapshot` in the viewer toolbar writes the current camera
+ view as a PNG beside the model, sized to the panel. Useful for a README, a PR,
+ or a design review.
+
+## Install
+
+From the workspace root:
+
+```bash
+cd packages/vscode-3d
+npm install
+npm run build
+```
+
+Then press <kbd>F5</kbd> in VS Code with `packages/vscode-3d` open to launch an
+Extension Development Host, or build a `.vsix` and install it:
+
+```bash
+npm run package
+code --install-extension vscode-3d-0.1.0.vsix
+```
+
+## Use it
+
+Open any `.glb` or `.gltf` in the explorer. That is the whole setup: the viewer
+is the default editor for those files, and the **three.ws 3D** icon in the
+activity bar lists every model in the workspace alongside the public gallery.
+
+To make something new, run **3D: Generate a Model from Text** from the command
+palette, describe one subject ("a friendly round robot mascot, glossy white
+plastic, big blue eyes"), and the finished GLB lands in your `models/` folder and
+opens. Then either **Rig for animation** to make it posable, or **Insert embed**
+to put it on a page:
+
+```html
+<script
+ type="module"
+ src="https://three.ws/agent-3d/1.5.2/agent-3d.js"
+ integrity="sha384-…"
+ crossorigin="anonymous"
+></script>
+
+<agent-3d
+ body="https://three.ws/cdn/creations/…/mesh.glb"
+ style="width: 400px; height: 500px; display: block;"
+></agent-3d>
+```
+
+## Commands
+
+| Command | What it does |
+|---|---|
+| `3D: Generate a Model from Text` | Free text to 3D. Saves the GLB and opens it. |
+| `3D: Generate an Avatar from Text` | Same, tuned for characters. |
+| `3D: Rig a Model for Animation` | Adds a humanoid skeleton to a static model. |
+| `3D: Insert <agent-3d> Embed Snippet` | Writes a pinned, SRI-checked embed at the cursor. |
+| `3D: Preview a Model URL` | Opens any hosted `.glb` in the viewer. |
+| `3D: Open in the three.ws Viewer` | Opens the model in the browser viewer. |
+| `3D: Copy the Model's three.ws URL` | Copies the hosted URL to the clipboard. |
+| `3D: Save a PNG Snapshot of the View` | Writes the current view beside the model. |
+
+## Settings
+
+| Setting | Default | Purpose |
+|---|---|---|
+| `threews3d.origin` | `https://three.ws` | Host of the studio API and the gallery. |
+| `threews3d.downloadFolder` | `models` | Workspace folder generated models are saved into. |
+| `threews3d.tier` | `draft` | Detail level for text to 3D: `draft`, `standard`, or `high`. All free. |
+| `threews3d.environment` | `studio` | Image-based lighting: `studio`, `neutral`, or `none`. |
+| `threews3d.showGrid` | `true` | Show the ground grid when a model opens. |
+| `threews3d.autoRotate` | `false` | Orbit the camera automatically when a model opens. |
+| `threews3d.embedChannel` | `pinned` | `pinned` resolves the current release plus its SRI hash; or name a channel such as `latest`, `1`, or `1.5`. |
+
+## How it works
+
+Generation, rigging, and the gallery go through public, unauthenticated three.ws
+endpoints:
+
+- `POST /api/mcp-studio` is the JSON-RPC studio. The extension calls the
+ `forge_free`, `text_to_avatar`, and `rig_mesh` tools. No key, no account, no
+ payment: the platform's server-side keys cover provider cost.
+- `GET /api/forge-gallery` is the public feed of recent creations.
+- `GET /agent-3d/versions.json` is the library release manifest the embed snippet
+ pins against.
+
+Everything else is local. The viewer runs three.js inside a webview whose content
+security policy allows exactly one nonce-gated script and no remote origin, so
+the only thing that crosses the network is the model file itself. The Draco and
+Basis decoders are copied out of three.js at build time and served from the
+extension, never from a CDN.
+
+## Which model can be embedded or rigged
+
+Both need a URL the browser (or the rigger) can fetch. Models this extension
+generated or imported carry their three.ws URL, so those commands just work. For
+a local file that has never been uploaded, the extension asks for the https URL
+where it is hosted rather than handing you a snippet that renders nothing.
+
+## Develop
+
+```bash
+npm run watch # rebuild the host bundle and the webview on change
+npm test # builds, then runs the suite
+```
+
+`npm test` activates the bundled extension against a stand-in extension host and
+asserts that every command, view, and custom editor the manifest promises really
+registers, that the viewer webview is nonce-gated and CDN-free, and that the
+model reaches it. The studio, gallery, embed, and naming modules are unit tested
+against local HTTP servers.
+
+## Related
+
+- [`docs/vscode.md`](../../docs/vscode.md) walks through the whole workflow.
+- [`@three-ws/vscode-x402`](../vscode-x402) is the sibling extension for paying
+ x402 endpoints from the editor.
+- [`docs/embedding.md`](../../docs/embedding.md) documents every `<agent-3d>`
+ attribute the inserted snippet can take.
+- [`@three-ws/glb-tools`](../glb-tools) does inspection and baking from the shell
+ and CI.
+
+Apache-2.0. Built by [three.ws](https://three.ws).
diff --git a/packages/vscode-3d/build.mjs b/packages/vscode-3d/build.mjs
new file mode 100644
index 000000000..e3aceeafb
--- /dev/null
+++ b/packages/vscode-3d/build.mjs
@@ -0,0 +1,78 @@
+// Two bundles and a decoder copy step.
+//
+// src/extension.js -> dist/extension.cjs (Node, CJS: what the extension host requires)
+// webview/main.js -> media/viewer.js (browser, IIFE: the three.js viewer)
+//
+// The webview never reaches the network for a decoder, so Draco and KTX2 assets
+// are copied out of three's examples into media/vendor and loaded from the
+// webview's own origin. That keeps the viewer working offline and inside the
+// webview's strict CSP.
+import esbuild from 'esbuild';
+import { cp, mkdir, rm } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { dirname, join } from 'node:path';
+
+const require = createRequire(import.meta.url);
+const production = process.argv.includes('--production');
+const watch = process.argv.includes('--watch');
+
+// three does not export ./package.json, so the libs directory is derived from a
+// file that is exported.
+const threeLibs = dirname(dirname(require.resolve('three/examples/jsm/libs/basis/basis_transcoder.js')));
+
+// Only what the loaders fetch at runtime: the Draco encoder alone is a megabyte
+// of dead weight in the .vsix.
+const DECODERS = [
+ ['draco/gltf/draco_decoder.js', 'draco/draco_decoder.js'],
+ ['draco/gltf/draco_decoder.wasm', 'draco/draco_decoder.wasm'],
+ ['draco/gltf/draco_wasm_wrapper.js', 'draco/draco_wasm_wrapper.js'],
+ ['basis/basis_transcoder.js', 'basis/basis_transcoder.js'],
+ ['basis/basis_transcoder.wasm', 'basis/basis_transcoder.wasm'],
+];
+
+async function copyDecoders() {
+ await rm('media/vendor', { recursive: true, force: true });
+ for (const [from, to] of DECODERS) {
+ await mkdir(dirname(join('media/vendor', to)), { recursive: true });
+ await cp(join(threeLibs, from), join('media/vendor', to));
+ }
+}
+
+/** @type {import('esbuild').BuildOptions} */
+const host = {
+ entryPoints: ['src/extension.js'],
+ bundle: true,
+ // .cjs (not .js) because package.json declares "type": "module" for the ESM
+ // sources; the extension host still requires this bundle as CommonJS.
+ outfile: 'dist/extension.cjs',
+ platform: 'node',
+ format: 'cjs',
+ target: 'node18',
+ external: ['vscode'],
+ sourcemap: !production,
+ minify: production,
+ logLevel: 'info',
+};
+
+/** @type {import('esbuild').BuildOptions} */
+const webview = {
+ entryPoints: ['webview/main.js'],
+ bundle: true,
+ outfile: 'media/viewer.js',
+ platform: 'browser',
+ format: 'iife',
+ target: 'es2020',
+ sourcemap: !production,
+ minify: production,
+ logLevel: 'info',
+};
+
+await copyDecoders();
+
+if (watch) {
+ const contexts = await Promise.all([esbuild.context(host), esbuild.context(webview)]);
+ await Promise.all(contexts.map((c) => c.watch()));
+ console.log('[vscode-3d] watching…');
+} else {
+ await Promise.all([esbuild.build(host), esbuild.build(webview)]);
+}
diff --git a/packages/vscode-3d/media/cube.svg b/packages/vscode-3d/media/cube.svg
new file mode 100644
index 000000000..f31a83f4a
--- /dev/null
+++ b/packages/vscode-3d/media/cube.svg
@@ -0,0 +1,4 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M12 2.6 21 7.3v9.4L12 21.4 3 16.7V7.3L12 2.6Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>
+ <path d="M3 7.3 12 12l9-4.7M12 12v9.4" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>
+</svg>
diff --git a/packages/vscode-3d/media/icon.png b/packages/vscode-3d/media/icon.png
new file mode 100644
index 000000000..615806681
Binary files /dev/null and b/packages/vscode-3d/media/icon.png differ
diff --git a/packages/vscode-3d/media/viewer.css b/packages/vscode-3d/media/viewer.css
new file mode 100644
index 000000000..f2fed6f3b
--- /dev/null
+++ b/packages/vscode-3d/media/viewer.css
@@ -0,0 +1,227 @@
+/* Viewer chrome. Every colour comes from the active VS Code theme so the panel
+ belongs to the editor rather than sitting on top of it. */
+
+:root {
+ --pad: 10px;
+ --radius: 6px;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html,
+body {
+ height: 100%;
+ margin: 0;
+ overflow: hidden;
+ color: var(--vscode-foreground);
+ font-family: var(--vscode-font-family);
+ font-size: var(--vscode-font-size);
+ background: var(--vscode-editor-background);
+}
+
+#stage {
+ position: absolute;
+ inset: 0;
+}
+
+#stage canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ outline: none;
+}
+
+#loading,
+#error {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ pointer-events: none;
+ text-align: center;
+ padding: 24px;
+}
+
+#error {
+ pointer-events: auto;
+ color: var(--vscode-errorForeground);
+}
+
+#error h2 {
+ margin: 0;
+ font-size: 1.1em;
+}
+
+#error p {
+ margin: 0;
+ max-width: 46ch;
+ color: var(--vscode-descriptionForeground);
+ word-break: break-word;
+}
+
+.spinner {
+ width: 22px;
+ height: 22px;
+ border: 2px solid var(--vscode-descriptionForeground);
+ border-top-color: transparent;
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+}
+
+@keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .spinner {
+ animation-duration: 3s;
+ }
+}
+
+#toolbar {
+ position: absolute;
+ left: 50%;
+ bottom: var(--pad);
+ transform: translateX(-50%);
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 4px;
+ padding: 5px;
+ max-width: calc(100% - 2 * var(--pad));
+ background: var(--vscode-editorWidget-background);
+ border: 1px solid var(--vscode-editorWidget-border, transparent);
+ border-radius: var(--radius);
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
+}
+
+#toolbar button,
+#toolbar select {
+ appearance: none;
+ background: transparent;
+ color: var(--vscode-foreground);
+ border: 1px solid transparent;
+ border-radius: 4px;
+ padding: 4px 8px;
+ font: inherit;
+ cursor: pointer;
+ transition: background 0.12s ease, border-color 0.12s ease;
+}
+
+#toolbar select {
+ background: var(--vscode-dropdown-background);
+ color: var(--vscode-dropdown-foreground);
+ border-color: var(--vscode-dropdown-border, transparent);
+ max-width: 220px;
+}
+
+#toolbar button:hover {
+ background: var(--vscode-toolbar-hoverBackground, rgba(128, 128, 128, 0.2));
+}
+
+#toolbar button:active {
+ background: var(--vscode-toolbar-activeBackground, rgba(128, 128, 128, 0.31));
+}
+
+#toolbar button:focus-visible,
+#toolbar select:focus-visible {
+ outline: 1px solid var(--vscode-focusBorder);
+ outline-offset: 1px;
+}
+
+#toolbar button[aria-pressed='true'] {
+ background: var(--vscode-inputOption-activeBackground, rgba(51, 122, 183, 0.4));
+ border-color: var(--vscode-inputOption-activeBorder, var(--vscode-focusBorder));
+ color: var(--vscode-inputOption-activeForeground, var(--vscode-foreground));
+}
+
+#playback {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+#scrub {
+ width: 120px;
+ accent-color: var(--vscode-focusBorder);
+}
+
+#report {
+ position: absolute;
+ top: var(--pad);
+ right: var(--pad);
+ width: 268px;
+ max-height: calc(100% - 78px);
+ overflow: auto;
+ padding: 12px 14px;
+ background: var(--vscode-editorWidget-background);
+ border: 1px solid var(--vscode-editorWidget-border, transparent);
+ border-radius: var(--radius);
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
+}
+
+#report h2 {
+ margin: 0 0 8px;
+ font-size: 0.95em;
+ font-weight: 600;
+}
+
+#report dl {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 3px 12px;
+ margin: 0 0 12px;
+ font-size: 0.92em;
+}
+
+#report dt {
+ color: var(--vscode-descriptionForeground);
+ white-space: nowrap;
+}
+
+#report dd {
+ margin: 0;
+ text-align: right;
+ word-break: break-word;
+}
+
+#report ul {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: 0.9em;
+}
+
+#report li {
+ padding-left: 9px;
+ border-left: 2px solid var(--vscode-descriptionForeground);
+ color: var(--vscode-descriptionForeground);
+}
+
+#report li.sev-warn {
+ border-left-color: var(--vscode-editorWarning-foreground);
+ color: var(--vscode-foreground);
+}
+
+#report li.sev-critical {
+ border-left-color: var(--vscode-errorForeground);
+ color: var(--vscode-foreground);
+}
+
+#report[hidden],
+#playback[hidden],
+#clips[hidden],
+#loading[hidden],
+#error[hidden] {
+ display: none;
+}
diff --git a/packages/vscode-3d/package-lock.json b/packages/vscode-3d/package-lock.json
new file mode 100644
index 000000000..da780c22d
--- /dev/null
+++ b/packages/vscode-3d/package-lock.json
@@ -0,0 +1,566 @@
+{
+ "name": "@three-ws/vscode-3d",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@three-ws/vscode-3d",
+ "version": "0.1.0",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@gltf-transform/core": "^4.4.0",
+ "@gltf-transform/extensions": "^4.4.0",
+ "meshoptimizer": "^1.1.1",
+ "three": "^0.184.0"
+ },
+ "devDependencies": {
+ "@types/vscode": "^1.85.0",
+ "esbuild": "^0.28.1"
+ },
+ "engines": {
+ "vscode": "^1.85.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@gltf-transform/core": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/core/-/core-4.5.0.tgz",
+ "integrity": "sha512-JlvShvnB4AtfGZqjnESS/wfPJbpVnyHhTwJBbWN4qXqkB3C5HIoxxpu/orwGBge6Pc0zObeWj70lVf+4gbuu0A==",
+ "license": "MIT",
+ "dependencies": {
+ "property-graph": "^4.1.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@gltf-transform/extensions": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/extensions/-/extensions-4.5.0.tgz",
+ "integrity": "sha512-J4cKzrmEr75YkrtdI4cKosBg2vDC4rT56aq/QoijW7GT1Y9gSEMJbqyFO9xcFO3FNpZaZiDrHWUqE5Okrl5nOQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "^4.5.0",
+ "ktx-parse": "^1.1.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@types/vscode": {
+ "version": "1.136.0",
+ "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.136.0.tgz",
+ "integrity": "sha512-DO746VAfnHk8+Y8CsUKYMm2rjWD0mxEuYBZI+ssaqJY7yvLJPf9lcwxSSz9W60gbdvdcGyvHQxHTyByfF9mVqg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.2",
+ "@esbuild/android-arm": "0.28.2",
+ "@esbuild/android-arm64": "0.28.2",
+ "@esbuild/android-x64": "0.28.2",
+ "@esbuild/darwin-arm64": "0.28.2",
+ "@esbuild/darwin-x64": "0.28.2",
+ "@esbuild/freebsd-arm64": "0.28.2",
+ "@esbuild/freebsd-x64": "0.28.2",
+ "@esbuild/linux-arm": "0.28.2",
+ "@esbuild/linux-arm64": "0.28.2",
+ "@esbuild/linux-ia32": "0.28.2",
+ "@esbuild/linux-loong64": "0.28.2",
+ "@esbuild/linux-mips64el": "0.28.2",
+ "@esbuild/linux-ppc64": "0.28.2",
+ "@esbuild/linux-riscv64": "0.28.2",
+ "@esbuild/linux-s390x": "0.28.2",
+ "@esbuild/linux-x64": "0.28.2",
+ "@esbuild/netbsd-arm64": "0.28.2",
+ "@esbuild/netbsd-x64": "0.28.2",
+ "@esbuild/openbsd-arm64": "0.28.2",
+ "@esbuild/openbsd-x64": "0.28.2",
+ "@esbuild/openharmony-arm64": "0.28.2",
+ "@esbuild/sunos-x64": "0.28.2",
+ "@esbuild/win32-arm64": "0.28.2",
+ "@esbuild/win32-ia32": "0.28.2",
+ "@esbuild/win32-x64": "0.28.2"
+ }
+ },
+ "node_modules/ktx-parse": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-1.1.0.tgz",
+ "integrity": "sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ==",
+ "license": "MIT"
+ },
+ "node_modules/meshoptimizer": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.2.0.tgz",
+ "integrity": "sha512-davRZeIJbxJrE24cwQle7ZDsxjdk/OphNOV83oX+efQinyoHY9Jcyz3MHbaoG0qySZajldGztNZ1RN/T19PZsg==",
+ "license": "MIT"
+ },
+ "node_modules/property-graph": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/property-graph/-/property-graph-4.1.0.tgz",
+ "integrity": "sha512-AvPcP7XECNWy4LGmFQ77k7un4lSKM4eS29PTvW4ck95uYeLxXPWJM7hLuBqK91FaHqCcgJvIUCuNJjjxKE7VKQ==",
+ "license": "MIT"
+ },
+ "node_modules/three": {
+ "version": "0.184.0",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.184.0.tgz",
+ "integrity": "sha512-wtTRjG92pM5eUg/KuUnHsqSAlPM296brTOcLgMRqEeylYTh/CdtvKUvCyyCQTzFuStieWxvZb8mVTMvdPyUpxg==",
+ "license": "MIT"
+ }
+ }
+}
diff --git a/packages/vscode-3d/package.json b/packages/vscode-3d/package.json
new file mode 100644
index 000000000..f5611b4ad
--- /dev/null
+++ b/packages/vscode-3d/package.json
@@ -0,0 +1,266 @@
+{
+ "name": "vscode-3d",
+ "displayName": "three.ws 3D",
+ "description": "Preview GLB and glTF models inside VS Code, generate new ones from a text prompt on the free three.ws lane, rig them for animation, and paste a working <agent-3d> embed. Powered by three.ws.",
+ "version": "0.1.0",
+ "publisher": "threews",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/vscode-3d"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "engines": {
+ "vscode": "^1.85.0"
+ },
+ "categories": [
+ "Visualization",
+ "Programming Languages",
+ "Other"
+ ],
+ "keywords": [
+ "3d",
+ "glb",
+ "gltf",
+ "three.js",
+ "model viewer",
+ "avatar",
+ "text to 3d",
+ "preview",
+ "three",
+ "webgl"
+ ],
+ "type": "module",
+ "main": "./dist/extension.cjs",
+ "icon": "media/icon.png",
+ "galleryBanner": {
+ "color": "#0E1116",
+ "theme": "dark"
+ },
+ "activationEvents": [],
+ "contributes": {
+ "customEditors": [
+ {
+ "viewType": "threews3d.modelViewer",
+ "displayName": "three.ws 3D Viewer",
+ "selector": [
+ { "filenamePattern": "*.glb" },
+ { "filenamePattern": "*.gltf" }
+ ],
+ "priority": "default"
+ }
+ ],
+ "viewsContainers": {
+ "activitybar": [
+ {
+ "id": "threews3d",
+ "title": "three.ws 3D",
+ "icon": "media/cube.svg"
+ }
+ ]
+ },
+ "views": {
+ "threews3d": [
+ {
+ "id": "threews3d.models",
+ "name": "Models in workspace",
+ "icon": "media/cube.svg"
+ },
+ {
+ "id": "threews3d.gallery",
+ "name": "Forge gallery",
+ "icon": "media/cube.svg",
+ "visibility": "collapsed"
+ }
+ ]
+ },
+ "viewsWelcome": [
+ {
+ "view": "threews3d.models",
+ "contents": "No .glb or .gltf files here yet.\n\nGenerate one from a text prompt on the free three.ws lane. No key, no account.\n[Generate a 3D model](command:threews3d.generateModel)\n[Generate an avatar](command:threews3d.generateAvatar)\n\nAlready have a model on a URL?\n[Preview a model URL](command:threews3d.previewUrl)"
+ }
+ ],
+ "commands": [
+ {
+ "command": "threews3d.generateModel",
+ "title": "3D: Generate a Model from Text",
+ "icon": "$(sparkle)"
+ },
+ {
+ "command": "threews3d.generateAvatar",
+ "title": "3D: Generate an Avatar from Text",
+ "icon": "$(person)"
+ },
+ {
+ "command": "threews3d.rigModel",
+ "title": "3D: Rig a Model for Animation"
+ },
+ {
+ "command": "threews3d.insertEmbed",
+ "title": "3D: Insert <agent-3d> Embed Snippet"
+ },
+ {
+ "command": "threews3d.previewUrl",
+ "title": "3D: Preview a Model URL"
+ },
+ {
+ "command": "threews3d.openInBrowser",
+ "title": "3D: Open in the three.ws Viewer"
+ },
+ {
+ "command": "threews3d.copyModelUrl",
+ "title": "3D: Copy the Model's three.ws URL"
+ },
+ {
+ "command": "threews3d.saveSnapshot",
+ "title": "3D: Save a PNG Snapshot of the View"
+ },
+ {
+ "command": "threews3d.importGalleryItem",
+ "title": "3D: Import Model into the Workspace",
+ "icon": "$(cloud-download)"
+ },
+ {
+ "command": "threews3d.previewCreation",
+ "title": "3D: Preview a Gallery Creation"
+ },
+ {
+ "command": "threews3d.refreshModels",
+ "title": "3D: Refresh Workspace Models",
+ "icon": "$(refresh)"
+ },
+ {
+ "command": "threews3d.refreshGallery",
+ "title": "3D: Refresh Forge Gallery",
+ "icon": "$(refresh)"
+ }
+ ],
+ "menus": {
+ "view/title": [
+ {
+ "command": "threews3d.generateModel",
+ "when": "view == threews3d.models",
+ "group": "navigation@1"
+ },
+ {
+ "command": "threews3d.refreshModels",
+ "when": "view == threews3d.models",
+ "group": "navigation@2"
+ },
+ {
+ "command": "threews3d.refreshGallery",
+ "when": "view == threews3d.gallery",
+ "group": "navigation@1"
+ }
+ ],
+ "view/item/context": [
+ {
+ "command": "threews3d.importGalleryItem",
+ "when": "view == threews3d.gallery && viewItem == threews3dGalleryItem",
+ "group": "inline"
+ },
+ {
+ "command": "threews3d.insertEmbed",
+ "when": "view == threews3d.models && viewItem == threews3dModel"
+ },
+ {
+ "command": "threews3d.rigModel",
+ "when": "view == threews3d.models && viewItem == threews3dModel"
+ }
+ ],
+ "explorer/context": [
+ {
+ "command": "threews3d.rigModel",
+ "when": "resourceExtname == .glb",
+ "group": "threews3d@1"
+ },
+ {
+ "command": "threews3d.insertEmbed",
+ "when": "resourceExtname == .glb",
+ "group": "threews3d@2"
+ }
+ ],
+ "commandPalette": [
+ {
+ "command": "threews3d.importGalleryItem",
+ "when": "false"
+ },
+ {
+ "command": "threews3d.previewCreation",
+ "when": "false"
+ },
+ {
+ "command": "threews3d.refreshModels",
+ "when": "false"
+ },
+ {
+ "command": "threews3d.refreshGallery",
+ "when": "false"
+ }
+ ]
+ },
+ "configuration": {
+ "title": "three.ws 3D",
+ "properties": {
+ "threews3d.origin": {
+ "type": "string",
+ "default": "https://three.ws",
+ "description": "Origin that serves the studio API (/api/mcp-studio) and the forge gallery."
+ },
+ "threews3d.downloadFolder": {
+ "type": "string",
+ "default": "models",
+ "description": "Workspace-relative folder that generated and imported models are written to."
+ },
+ "threews3d.tier": {
+ "type": "string",
+ "enum": ["draft", "standard", "high"],
+ "default": "draft",
+ "description": "Detail level for text to 3D generation. Higher tiers take longer; all of them are free."
+ },
+ "threews3d.environment": {
+ "type": "string",
+ "enum": ["studio", "neutral", "none"],
+ "default": "studio",
+ "description": "Image-based lighting used to light the model in the viewer."
+ },
+ "threews3d.showGrid": {
+ "type": "boolean",
+ "default": true,
+ "description": "Show the ground grid in the viewer."
+ },
+ "threews3d.autoRotate": {
+ "type": "boolean",
+ "default": false,
+ "description": "Slowly orbit the camera around the model when the viewer opens."
+ },
+ "threews3d.embedChannel": {
+ "type": "string",
+ "default": "pinned",
+ "description": "Version channel used by the inserted <agent-3d> snippet: 'pinned' resolves the current release and adds its SRI hash, or name a channel such as latest, 1, or 1.5."
+ }
+ }
+ }
+ },
+ "scripts": {
+ "build": "node build.mjs",
+ "watch": "node build.mjs --watch",
+ "test": "node build.mjs && node --test \"test/*.test.mjs\"",
+ "package": "npx --yes @vscode/vsce package --no-dependencies",
+ "vscode:prepublish": "node build.mjs --production"
+ },
+ "dependencies": {
+ "@gltf-transform/core": "^4.4.0",
+ "@gltf-transform/extensions": "^4.4.0",
+ "meshoptimizer": "^1.1.1",
+ "three": "^0.184.0"
+ },
+ "devDependencies": {
+ "@types/vscode": "^1.85.0",
+ "esbuild": "^0.28.1"
+ }
+}
diff --git a/packages/vscode-3d/src/active-panel.js b/packages/vscode-3d/src/active-panel.js
new file mode 100644
index 000000000..580067d44
--- /dev/null
+++ b/packages/vscode-3d/src/active-panel.js
@@ -0,0 +1,23 @@
+// Which viewer a palette command acts on.
+//
+// Custom editors and remote panels both register here, so "Save a PNG snapshot"
+// works the same whether the model came from the workspace or from a URL.
+
+let current = null;
+
+/** @param {import('vscode').WebviewPanel} panel */
+export function trackPanel(panel) {
+ current = panel;
+ panel.onDidChangeViewState(() => {
+ if (panel.active) current = panel;
+ else if (current === panel) current = null;
+ });
+ panel.onDidDispose(() => {
+ if (current === panel) current = null;
+ });
+ return panel;
+}
+
+export function activeViewer() {
+ return current;
+}
diff --git a/packages/vscode-3d/src/download.js b/packages/vscode-3d/src/download.js
new file mode 100644
index 000000000..b240476f0
--- /dev/null
+++ b/packages/vscode-3d/src/download.js
@@ -0,0 +1,63 @@
+// Download a model into the workspace.
+//
+// Writes through vscode.workspace.fs (not node:fs) so this works the same in a
+// remote, WSL, or virtual workspace as it does on a local disk.
+
+import * as vscode from 'vscode';
+import { slugFromPrompt, slugFromUrl, uniqueName } from './naming.js';
+
+/** The configured download folder as a Uri, created if it does not exist yet. */
+export async function ensureDownloadFolder() {
+ const folders = vscode.workspace.workspaceFolders;
+ if (!folders?.length) {
+ throw new Error('open a folder in VS Code first; models are saved into the workspace');
+ }
+ const rel = vscode.workspace.getConfiguration('threews3d').get('downloadFolder', 'models');
+ const dir = vscode.Uri.joinPath(folders[0].uri, ...String(rel || 'models').split('/').filter(Boolean));
+ await vscode.workspace.fs.createDirectory(dir);
+ return dir;
+}
+
+/** Names already present in a directory, as a lookup for uniqueName(). */
+async function namesIn(dir) {
+ try {
+ const entries = await vscode.workspace.fs.readDirectory(dir);
+ return new Set(entries.map(([name]) => name.toLowerCase()));
+ } catch {
+ return new Set();
+ }
+}
+
+/**
+ * Fetch a GLB and write it into the download folder.
+ *
+ * @param {string} url
+ * @param {{ prompt?: string, token?: vscode.CancellationToken, progress?: vscode.Progress<{ message?: string }> }} [opts]
+ * @returns {Promise<{ uri: vscode.Uri, bytes: number }>}
+ */
+export async function downloadModel(url, { prompt, token, progress } = {}) {
+ const dir = await ensureDownloadFolder();
+ const taken = await namesIn(dir);
+ const stem = prompt ? slugFromPrompt(prompt) : slugFromUrl(url);
+ const ext = /\.gltf(\?|$)/i.test(url) ? '.gltf' : '.glb';
+ const name = uniqueName(stem, ext, (candidate) => taken.has(candidate.toLowerCase()));
+ const target = vscode.Uri.joinPath(dir, name);
+
+ const controller = new AbortController();
+ const sub = token?.onCancellationRequested(() => controller.abort());
+ let res;
+ try {
+ res = await fetch(url, { signal: controller.signal });
+ } catch (err) {
+ if (controller.signal.aborted) throw new Error('download cancelled');
+ throw new Error(`could not download the model: ${err?.message || err}`);
+ } finally {
+ sub?.dispose();
+ }
+ if (!res.ok) throw new Error(`the model URL returned HTTP ${res.status}`);
+ progress?.report({ message: 'downloading the model…' });
+ const bytes = new Uint8Array(await res.arrayBuffer());
+ if (!bytes.byteLength) throw new Error('the model URL returned an empty file');
+ await vscode.workspace.fs.writeFile(target, bytes);
+ return { uri: target, bytes: bytes.byteLength };
+}
diff --git a/packages/vscode-3d/src/embed.js b/packages/vscode-3d/src/embed.js
new file mode 100644
index 000000000..dd3d70590
--- /dev/null
+++ b/packages/vscode-3d/src/embed.js
@@ -0,0 +1,86 @@
+// Builds the <agent-3d> embed snippet.
+//
+// The snippet follows docs/embedding.md exactly: a pinned, subresource-integrity
+// checked module script plus the element. The version and its SRI hash come from
+// the live release manifest (/agent-3d/versions.json) so a snippet pasted today
+// keeps working when the library moves on.
+
+import { normalizeOrigin } from './studio.js';
+
+/** The channel used when a pinned release cannot be resolved. */
+const FALLBACK_CHANNEL = 'latest';
+
+/**
+ * Resolve which library build the snippet should load.
+ *
+ * @param {string} origin
+ * @param {string} channel 'pinned' for the current release plus its SRI hash, or
+ * a channel name such as 'latest', '1', or '1.5'.
+ * @returns {Promise<{ channel: string, integrity: string | null }>}
+ */
+export async function resolveEmbedRelease(origin, channel = 'pinned') {
+ const wanted = String(channel || 'pinned').trim() || 'pinned';
+ if (wanted !== 'pinned') return { channel: wanted, integrity: null };
+ try {
+ const url = new URL('/agent-3d/versions.json', normalizeOrigin(origin)).href;
+ const res = await fetch(url, { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const manifest = await res.json();
+ return readRelease(manifest);
+ } catch {
+ // A snippet that loads the moving channel still works; only the pin is lost.
+ return { channel: FALLBACK_CHANNEL, integrity: null };
+ }
+}
+
+/** Pull the pinned version and its script hash out of the release manifest. */
+export function readRelease(manifest) {
+ const version = manifest?.latest;
+ if (typeof version !== 'string' || !version) {
+ return { channel: FALLBACK_CHANNEL, integrity: null };
+ }
+ const integrity = manifest?.channels?.[version]?.integrity?.['agent-3d.js'];
+ return { channel: version, integrity: typeof integrity === 'string' ? integrity : null };
+}
+
+/**
+ * Render the snippet.
+ *
+ * @param {object} opts
+ * @param {string} opts.src https URL of the GLB to show
+ * @param {string} opts.origin site that serves the library
+ * @param {string} opts.channel version or channel path segment
+ * @param {string | null} [opts.integrity] SRI hash for the pinned build
+ * @param {number} [opts.width] CSS pixels
+ * @param {number} [opts.height] CSS pixels
+ */
+export function buildEmbedSnippet({ src, origin, channel, integrity, width = 400, height = 500 }) {
+ if (!/^https?:\/\//.test(String(src || ''))) {
+ throw new Error('the embed needs an http(s) URL for the model');
+ }
+ const lib = `${normalizeOrigin(origin)}/agent-3d/${channel}/agent-3d.js`;
+ const script = integrity
+ ? [
+ '<script',
+ ' type="module"',
+ ` src="${lib}"`,
+ ` integrity="${integrity}"`,
+ ' crossorigin="anonymous"',
+ '></script>',
+ ].join('\n')
+ : `<script type="module" src="${lib}"></script>`;
+ const element = [
+ '<agent-3d',
+ ` body="${src}"`,
+ ` style="width: ${width}px; height: ${height}px; display: block;"`,
+ '></agent-3d>',
+ ].join('\n');
+ return `${script}\n\n${element}\n`;
+}
+
+/** The three.ws hosted viewer URL for a model, for "open in browser". */
+export function viewerUrl(origin, src) {
+ const url = new URL('/viewer', normalizeOrigin(origin));
+ url.searchParams.set('src', src);
+ return url.href;
+}
diff --git a/packages/vscode-3d/src/extension.js b/packages/vscode-3d/src/extension.js
new file mode 100644
index 000000000..76612e6b7
--- /dev/null
+++ b/packages/vscode-3d/src/extension.js
@@ -0,0 +1,338 @@
+// three.ws 3D — VS Code extension entry.
+//
+// Registers the model viewer (a custom editor for .glb/.gltf), the workspace and
+// gallery trees, and the commands that generate, rig, embed, and import models
+// through the live three.ws studio. Every call hits the real public API; nothing
+// here is stubbed.
+
+import * as vscode from 'vscode';
+import { GalleryProvider } from './gallery-tree.js';
+import { ModelLinks } from './links.js';
+import { ModelsProvider } from './models-tree.js';
+import { ModelViewerProvider, openRemoteModel } from './viewer.js';
+import { TOOLS, callTool } from './studio.js';
+import { downloadModel } from './download.js';
+import { buildEmbedSnippet, resolveEmbedRelease, viewerUrl } from './embed.js';
+import { slugFromUrl } from './naming.js';
+import { activeViewer } from './active-panel.js';
+
+let output;
+let links;
+
+export function activate(context) {
+ output = vscode.window.createOutputChannel('three.ws 3D');
+ links = new ModelLinks(context.workspaceState);
+
+ const models = new ModelsProvider(links);
+ const gallery = new GalleryProvider();
+ const modelsView = vscode.window.createTreeView('threews3d.models', {
+ treeDataProvider: models,
+ });
+ const galleryView = vscode.window.createTreeView('threews3d.gallery', {
+ treeDataProvider: gallery,
+ });
+
+ context.subscriptions.push(
+ output,
+ models,
+ gallery,
+ modelsView,
+ galleryView,
+ ModelViewerProvider.register(context, links, output),
+ );
+
+ const reg = (id, fn) => context.subscriptions.push(vscode.commands.registerCommand(id, fn));
+
+ reg('threews3d.generateModel', () => generate('model'));
+ reg('threews3d.generateAvatar', () => generate('avatar'));
+ reg('threews3d.rigModel', (target) => rig(target));
+ reg('threews3d.insertEmbed', (target) => insertEmbed(target));
+ reg('threews3d.previewUrl', () => previewUrl(context));
+ reg('threews3d.previewCreation', (item) => {
+ if (item?.glbUrl) openRemoteModel(context, links, output, item.glbUrl, title(item));
+ });
+ reg('threews3d.importGalleryItem', (node) => importCreation(node?.creation || node));
+ reg('threews3d.openInBrowser', (target) => openInBrowser(target));
+ reg('threews3d.copyModelUrl', (target) => copyModelUrl(target));
+ reg('threews3d.saveSnapshot', () => {
+ const panel = activeViewer();
+ if (!panel) {
+ vscode.window.showWarningMessage('three.ws 3D: open a model in the viewer first.');
+ return;
+ }
+ panel.webview.postMessage({ type: 'snapshot' });
+ });
+ reg('threews3d.refreshModels', () => models.refresh());
+ reg('threews3d.refreshGallery', () => gallery.refresh());
+
+ models.refresh();
+ // The gallery view starts collapsed; load it the first time it is expanded so
+ // activation never blocks on the network.
+ const once = galleryView.onDidChangeVisibility((e) => {
+ if (e.visible) {
+ once.dispose();
+ gallery.refresh();
+ }
+ });
+ context.subscriptions.push(once);
+}
+
+export function deactivate() {}
+
+function config() {
+ return vscode.workspace.getConfiguration('threews3d');
+}
+
+function origin() {
+ return config().get('origin', 'https://three.ws');
+}
+
+function title(creation) {
+ return creation.prompt ? creation.prompt.slice(0, 48) : `creation ${creation.id.slice(0, 8)}`;
+}
+
+// ---------------------------------------------------------------- generation
+
+async function generate(kind) {
+ const prompt = await vscode.window.showInputBox({
+ title: kind === 'avatar' ? 'Generate a 3D avatar' : 'Generate a 3D model',
+ prompt:
+ kind === 'avatar'
+ ? 'Describe the character. Lead with the subject, then clothing and colours.'
+ : 'Describe one object. Lead with the subject, then its materials and colours.',
+ placeHolder:
+ kind === 'avatar'
+ ? 'a cheerful astronaut in a white suit with an orange visor'
+ : 'a friendly round robot mascot, glossy white plastic, big blue eyes',
+ validateInput: (v) => {
+ const value = v.trim();
+ if (value.length < 3) return 'Describe the subject in at least 3 characters';
+ if (value.length > 1000) return 'Keep the description under 1000 characters';
+ return null;
+ },
+ });
+ if (!prompt) return;
+
+ const args =
+ kind === 'avatar'
+ ? { prompt: prompt.trim() }
+ : { prompt: prompt.trim(), tier: config().get('tier', 'draft') };
+ const tool = kind === 'avatar' ? TOOLS.avatar : TOOLS.model;
+
+ await vscode.window.withProgress(
+ {
+ location: vscode.ProgressLocation.Notification,
+ title: kind === 'avatar' ? 'Generating your avatar' : 'Generating your 3D model',
+ cancellable: true,
+ },
+ async (progress, token) => {
+ const controller = new AbortController();
+ token.onCancellationRequested(() => controller.abort());
+ progress.report({ message: 'the free lane is working on it…' });
+ try {
+ const model = await callTool(origin(), tool, args, { signal: controller.signal });
+ output.appendLine(`${tool}: ${model.glbUrl}`);
+ progress.report({ message: 'saving into the workspace…' });
+ const saved = await downloadModel(model.glbUrl, {
+ prompt: prompt.trim(),
+ token,
+ progress,
+ });
+ await links.set(saved.uri, model.glbUrl);
+ await openInViewer(saved.uri);
+ await offerFollowUp(saved.uri);
+ } catch (err) {
+ if (token.isCancellationRequested) return;
+ report(err, kind === 'avatar' ? 'avatar generation' : 'model generation');
+ }
+ },
+ );
+}
+
+async function offerFollowUp(uri) {
+ const choice = await vscode.window.showInformationMessage(
+ `Saved ${vscode.workspace.asRelativePath(uri, false)}`,
+ 'Insert embed',
+ 'Rig for animation',
+ );
+ if (choice === 'Insert embed') await vscode.commands.executeCommand('threews3d.insertEmbed', uri);
+ if (choice === 'Rig for animation') await vscode.commands.executeCommand('threews3d.rigModel', uri);
+}
+
+async function openInViewer(uri) {
+ await vscode.commands.executeCommand('vscode.openWith', uri, 'threews3d.modelViewer');
+}
+
+// --------------------------------------------------------------------- rigging
+
+async function rig(target) {
+ const url = await resolveUrl(target, {
+ title: 'Rig a model for animation',
+ prompt: 'https URL of the static GLB to rig',
+ });
+ if (!url) return;
+
+ await vscode.window.withProgress(
+ {
+ location: vscode.ProgressLocation.Notification,
+ title: 'Rigging the model',
+ cancellable: true,
+ },
+ async (progress, token) => {
+ const controller = new AbortController();
+ token.onCancellationRequested(() => controller.abort());
+ progress.report({ message: 'fitting a humanoid skeleton…' });
+ try {
+ const rigged = await callTool(
+ origin(),
+ TOOLS.rig,
+ { glb_url: url },
+ { signal: controller.signal },
+ );
+ output.appendLine(`${TOOLS.rig}: ${rigged.glbUrl}`);
+ const saved = await downloadModel(rigged.glbUrl, {
+ prompt: `${slugFromUrl(url)}-rigged`,
+ token,
+ progress,
+ });
+ await links.set(saved.uri, rigged.glbUrl);
+ await openInViewer(saved.uri);
+ } catch (err) {
+ if (token.isCancellationRequested) return;
+ report(err, 'rigging');
+ }
+ },
+ );
+}
+
+// ---------------------------------------------------------------------- embed
+
+async function insertEmbed(target) {
+ const src = await resolveUrl(target, {
+ title: 'Insert an <agent-3d> embed',
+ prompt: 'https URL of the hosted model the embed should show',
+ });
+ if (!src) return;
+
+ let snippet;
+ try {
+ const release = await resolveEmbedRelease(origin(), config().get('embedChannel', 'pinned'));
+ snippet = buildEmbedSnippet({ src, origin: origin(), ...release });
+ } catch (err) {
+ report(err, 'building the embed snippet');
+ return;
+ }
+
+ const editor = vscode.window.activeTextEditor;
+ if (editor) {
+ await editor.edit((edit) => {
+ for (const selection of editor.selections) edit.replace(selection, snippet);
+ });
+ return;
+ }
+ await vscode.env.clipboard.writeText(snippet);
+ vscode.window.showInformationMessage(
+ 'three.ws 3D: no editor was open, so the embed snippet was copied to the clipboard.',
+ );
+}
+
+// -------------------------------------------------------------------- viewing
+
+async function previewUrl(context) {
+ const url = await vscode.window.showInputBox({
+ title: 'Preview a model URL',
+ prompt: 'https URL of a .glb or .gltf file',
+ placeHolder: 'https://three.ws/avatars/default.glb',
+ validateInput: (v) => (isHttpUrl(v) ? null : 'Enter a valid http(s) URL'),
+ });
+ if (!url) return;
+ openRemoteModel(context, links, output, url.trim(), slugFromUrl(url));
+}
+
+async function importCreation(creation) {
+ if (!creation?.glbUrl) return;
+ await vscode.window.withProgress(
+ { location: vscode.ProgressLocation.Notification, title: 'Importing the model', cancellable: true },
+ async (progress, token) => {
+ try {
+ const saved = await downloadModel(creation.glbUrl, {
+ prompt: creation.prompt || slugFromUrl(creation.glbUrl),
+ token,
+ progress,
+ });
+ await links.set(saved.uri, creation.glbUrl);
+ await openInViewer(saved.uri);
+ } catch (err) {
+ if (token.isCancellationRequested) return;
+ report(err, 'importing the model');
+ }
+ },
+ );
+}
+
+async function openInBrowser(target) {
+ const url = await resolveUrl(target, {
+ title: 'Open in the three.ws viewer',
+ prompt: 'https URL of the hosted model',
+ });
+ if (!url) return;
+ await vscode.env.openExternal(vscode.Uri.parse(viewerUrl(origin(), url)));
+}
+
+async function copyModelUrl(target) {
+ const url = await resolveUrl(target, {
+ title: 'Copy the model URL',
+ prompt: 'https URL of the hosted model',
+ });
+ if (!url) return;
+ await vscode.env.clipboard.writeText(url);
+ vscode.window.showInformationMessage('three.ws 3D: model URL copied.');
+}
+
+// -------------------------------------------------------------------- helpers
+
+/**
+ * Work out which hosted model a command should act on.
+ *
+ * Tree items and explorer entries arrive as a Uri; models this extension
+ * generated or imported carry their CDN URL in the link store. A local file with
+ * no recorded URL cannot be embedded or rigged (the studio and the browser both
+ * need to fetch it), so the user is asked for one rather than being handed a
+ * broken snippet.
+ */
+async function resolveUrl(target, { title: boxTitle, prompt }) {
+ const uri = target?.resourceUri || target;
+ if (typeof uri === 'string' && isHttpUrl(uri)) return uri;
+ if (uri instanceof vscode.Uri) {
+ if (uri.scheme === 'http' || uri.scheme === 'https') return uri.toString();
+ const known = links.get(uri);
+ if (known) return known;
+ }
+ const name = uri instanceof vscode.Uri ? vscode.workspace.asRelativePath(uri, false) : '';
+ const entered = await vscode.window.showInputBox({
+ title: boxTitle,
+ prompt: name
+ ? `${name} has no public URL yet. Paste the https URL where the model is hosted.`
+ : prompt,
+ placeHolder: 'https://…/model.glb',
+ validateInput: (v) => (isHttpUrl(v) ? null : 'Enter a valid http(s) URL'),
+ });
+ return entered?.trim() || null;
+}
+
+function isHttpUrl(value) {
+ try {
+ const url = new URL(String(value).trim());
+ return url.protocol === 'http:' || url.protocol === 'https:';
+ } catch {
+ return false;
+ }
+}
+
+function report(err, what) {
+ const message = err?.message || String(err);
+ output.appendLine(`${what} failed: ${message}`);
+ vscode.window.showErrorMessage(`three.ws 3D: ${what} failed. ${message}`, 'Show log').then((pick) => {
+ if (pick === 'Show log') output.show(true);
+ });
+}
diff --git a/packages/vscode-3d/src/gallery-tree.js b/packages/vscode-3d/src/gallery-tree.js
new file mode 100644
index 000000000..f83cdb3e9
--- /dev/null
+++ b/packages/vscode-3d/src/gallery-tree.js
@@ -0,0 +1,100 @@
+// Recent public creations from the three.ws forge. Click one to preview it in
+// the viewer; the inline action imports it into the workspace.
+
+import * as vscode from 'vscode';
+import { listCreations } from './gallery.js';
+
+const STATE = { loading: 'loading', error: 'error', ready: 'ready' };
+
+export class GalleryProvider {
+ constructor() {
+ this._emitter = new vscode.EventEmitter();
+ this.onDidChangeTreeData = this._emitter.event;
+ this._items = [];
+ this._state = STATE.ready;
+ this._message = '';
+ }
+
+ dispose() {
+ this._emitter.dispose();
+ }
+
+ origin() {
+ return vscode.workspace.getConfiguration('threews3d').get('origin', 'https://three.ws');
+ }
+
+ async refresh() {
+ this._state = STATE.loading;
+ this._emitter.fire();
+ try {
+ this._items = await listCreations(this.origin(), { limit: 40 });
+ this._state = STATE.ready;
+ } catch (err) {
+ this._state = STATE.error;
+ this._message = err?.message || String(err);
+ this._items = [];
+ }
+ this._emitter.fire();
+ }
+
+ getTreeItem(node) {
+ return node;
+ }
+
+ getChildren(node) {
+ if (node) return [];
+ if (this._state === STATE.loading) {
+ return [infoNode('Loading recent creations…', 'loading~spin')];
+ }
+ if (this._state === STATE.error) {
+ return [infoNode(`Could not load the gallery: ${this._message}`, 'error')];
+ }
+ if (!this._items.length) {
+ return [infoNode('No public creations right now', 'info')];
+ }
+ return this._items.map(creationNode);
+ }
+}
+
+function creationNode(item) {
+ const title = item.prompt ? shorten(item.prompt, 60) : item.id.slice(0, 8);
+ const node = new vscode.TreeItem(title, vscode.TreeItemCollapsibleState.None);
+ node.description = [item.category, item.tier].filter(Boolean).join(' · ');
+ node.tooltip = new vscode.MarkdownString(
+ [
+ `**${escapeMd(shorten(item.prompt || 'Untitled creation', 240))}**`,
+ '',
+ item.category ? `- **Category:** ${item.category}` : '',
+ item.tier ? `- **Tier:** ${item.tier}` : '',
+ item.backend ? `- **Backend:** ${item.backend}` : '',
+ item.createdAt ? `- **Created:** ${item.createdAt}` : '',
+ ]
+ .filter(Boolean)
+ .join('\n'),
+ );
+ node.iconPath = new vscode.ThemeIcon(item.category === 'avatar' ? 'person' : 'symbol-color');
+ node.contextValue = 'threews3dGalleryItem';
+ node.creation = item;
+ node.command = {
+ command: 'threews3d.previewCreation',
+ title: 'Preview in the 3D viewer',
+ arguments: [item],
+ };
+ return node;
+}
+
+function shorten(text, max) {
+ const clean = String(text || '').replace(/\s+/g, ' ').trim();
+ return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
+}
+
+function escapeMd(text) {
+ return text.replace(/([\\`*_[\]])/g, '\\$1');
+}
+
+function infoNode(label, icon) {
+ const node = new vscode.TreeItem(label, vscode.TreeItemCollapsibleState.None);
+ node.iconPath = new vscode.ThemeIcon(icon);
+ node.contextValue = 'threews3dInfo';
+ return node;
+}
diff --git a/packages/vscode-3d/src/gallery.js b/packages/vscode-3d/src/gallery.js
new file mode 100644
index 000000000..ab361678f
--- /dev/null
+++ b/packages/vscode-3d/src/gallery.js
@@ -0,0 +1,58 @@
+// Recent public creations from the three.ws forge, read from the same feed the
+// /forge gallery renders. Public, unauthenticated, read-only.
+
+import { normalizeOrigin } from './studio.js';
+
+/**
+ * Normalise one gallery row into what the tree and the viewer need.
+ * `web_glb_url` is the web-optimized copy (meshopt, smaller); prefer it and keep
+ * the original as the download source when it is the only one present.
+ */
+export function normalizeCreation(row) {
+ const glbUrl = row?.web_glb_url || row?.glb_url;
+ if (typeof glbUrl !== 'string' || !/^https?:\/\//.test(glbUrl)) return null;
+ return {
+ id: String(row.id || ''),
+ prompt: String(row.prompt || '').trim(),
+ glbUrl,
+ previewImageUrl: row.preview_image_url || null,
+ category: row.model_category || null,
+ tier: row.tier || null,
+ backend: row.backend || null,
+ createdAt: row.created_at || null,
+ };
+}
+
+/**
+ * List recent forge creations.
+ * @param {string} origin
+ * @param {{ limit?: number, signal?: AbortSignal }} [opts]
+ * @returns {Promise<Array<ReturnType<typeof normalizeCreation>>>}
+ */
+export async function listCreations(origin, { limit = 40, signal } = {}) {
+ const url = new URL('/api/forge-gallery', normalizeOrigin(origin));
+ url.searchParams.set('limit', String(Math.min(Math.max(limit, 1), 100)));
+ const controller = new AbortController();
+ const onAbort = () => controller.abort();
+ signal?.addEventListener('abort', onAbort, { once: true });
+ const timer = setTimeout(() => controller.abort(), 20_000);
+ let res;
+ try {
+ res = await fetch(url.href, {
+ headers: { accept: 'application/json' },
+ signal: controller.signal,
+ });
+ } catch (err) {
+ throw new Error(`could not reach the forge gallery: ${err?.message || err}`);
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
+ }
+ if (!res.ok) throw new Error(`the forge gallery returned HTTP ${res.status}`);
+ const body = await res.json().catch(() => null);
+ if (body && body.enabled === false) {
+ throw new Error('the forge gallery is turned off on this origin');
+ }
+ const rows = Array.isArray(body?.creations) ? body.creations : [];
+ return rows.map(normalizeCreation).filter(Boolean);
+}
diff --git a/packages/vscode-3d/src/inspect.js b/packages/vscode-3d/src/inspect.js
new file mode 100644
index 000000000..857656efb
--- /dev/null
+++ b/packages/vscode-3d/src/inspect.js
@@ -0,0 +1,51 @@
+// Local model report.
+//
+// Reuses the platform's own inspector (src/gltf-inspect.js, the same code behind
+// the /validation page and the model-check API) so the numbers in the editor are
+// the numbers three.ws reports everywhere else. It runs entirely in the
+// extension host: the file is never uploaded anywhere.
+//
+// esbuild inlines the inspector and its glTF-Transform dependencies into
+// dist/extension.cjs at build time, so the shipped extension has no path
+// dependency back into the repo.
+
+import { inspectModel, suggestOptimizations } from '../../../src/gltf-inspect.js';
+import { formatBytes } from './naming.js';
+
+/**
+ * @param {Uint8Array} bytes raw .glb or .gltf contents
+ * @returns {Promise<{ info: any, suggestions: any[], rows: Array<[string, string]> }>}
+ */
+export async function reportFor(bytes) {
+ const info = await inspectModel(bytes);
+ const suggestions = suggestOptimizations(info);
+ return { info, suggestions, rows: rowsFor(info) };
+}
+
+/** The report as ordered label/value pairs, ready to render. */
+export function rowsFor(info) {
+ const c = info.counts;
+ const textureBytes = info.textures.reduce((a, t) => a + (t.byteSize || 0), 0);
+ const largest = info.textures.reduce(
+ (max, t) => Math.max(max, Math.max(t.width || 0, t.height || 0)),
+ 0,
+ );
+ const rows = [
+ ['File size', formatBytes(info.fileSize)],
+ ['Triangles', num(c.totalTriangles)],
+ ['Vertices', num(c.totalVertices)],
+ ['Meshes', num(c.meshes)],
+ ['Materials', num(c.materials)],
+ ['Textures', c.textures ? `${num(c.textures)} · ${formatBytes(textureBytes)}${largest ? ` · up to ${largest}px` : ''}` : '0'],
+ ['Animations', num(c.animations)],
+ ['Rig', c.skins ? `${num(c.skins)} skin${c.skins === 1 ? '' : 's'} · ${num(c.totalJoints)} bones` : 'none'],
+ ['Nodes', num(c.nodes)],
+ ];
+ if (info.extensionsUsed.length) rows.push(['Extensions', info.extensionsUsed.join(', ')]);
+ if (info.generator) rows.push(['Generator', info.generator]);
+ return rows;
+}
+
+function num(n) {
+ return Number(n || 0).toLocaleString('en-US');
+}
diff --git a/packages/vscode-3d/src/links.js b/packages/vscode-3d/src/links.js
new file mode 100644
index 000000000..6bd2ca880
--- /dev/null
+++ b/packages/vscode-3d/src/links.js
@@ -0,0 +1,36 @@
+// Remembers where a local model came from.
+//
+// A generated or imported GLB has a public URL on the three.ws CDN. That URL is
+// what the embed snippet and the rigger need, and it cannot be recovered from
+// the bytes on disk, so it is recorded when the file is written and looked up
+// later by workspace-relative path (absolute paths break when a repo is cloned
+// somewhere else or opened over a remote).
+
+import * as vscode from 'vscode';
+
+const KEY = 'threews3d.modelLinks';
+
+export class ModelLinks {
+ /** @param {vscode.Memento} memento */
+ constructor(memento) {
+ this.memento = memento;
+ }
+
+ /** @param {vscode.Uri} uri */
+ get(uri) {
+ const map = this.memento.get(KEY, {});
+ return map[keyFor(uri)] || null;
+ }
+
+ /** @param {vscode.Uri} uri @param {string} url */
+ async set(uri, url) {
+ const map = { ...this.memento.get(KEY, {}) };
+ map[keyFor(uri)] = url;
+ await this.memento.update(KEY, map);
+ }
+}
+
+function keyFor(uri) {
+ const relative = vscode.workspace.asRelativePath(uri, false);
+ return relative.replace(/\\/g, '/').toLowerCase();
+}
diff --git a/packages/vscode-3d/src/models-tree.js b/packages/vscode-3d/src/models-tree.js
new file mode 100644
index 000000000..f077e0b1a
--- /dev/null
+++ b/packages/vscode-3d/src/models-tree.js
@@ -0,0 +1,125 @@
+// Every model in the workspace, grouped by the folder that holds it.
+// Clicking one opens it in the 3D viewer; the tree refreshes itself when models
+// are added, generated, or deleted.
+
+import * as vscode from 'vscode';
+import { formatBytes } from './naming.js';
+
+const GLOB = '**/*.{glb,gltf}';
+const EXCLUDE = '**/{node_modules,.git,dist,dist-lib,build,out}/**';
+
+export class ModelsProvider {
+ /** @param {import('./links.js').ModelLinks} links */
+ constructor(links) {
+ this.links = links;
+ this._emitter = new vscode.EventEmitter();
+ this.onDidChangeTreeData = this._emitter.event;
+ this._files = [];
+ this._error = '';
+ this._loading = true;
+ this._watcher = vscode.workspace.createFileSystemWatcher(GLOB);
+ const bump = () => this.refresh();
+ this._watcher.onDidCreate(bump);
+ this._watcher.onDidDelete(bump);
+ }
+
+ dispose() {
+ this._watcher.dispose();
+ this._emitter.dispose();
+ }
+
+ async refresh() {
+ this._loading = true;
+ this._emitter.fire();
+ try {
+ const uris = await vscode.workspace.findFiles(GLOB, EXCLUDE, 2000);
+ const stats = await Promise.all(
+ uris.map(async (uri) => {
+ const size = await vscode.workspace.fs.stat(uri).then(
+ (s) => s.size,
+ () => 0,
+ );
+ return { uri, size };
+ }),
+ );
+ stats.sort((a, b) => a.uri.path.localeCompare(b.uri.path));
+ this._files = stats;
+ this._error = '';
+ } catch (err) {
+ this._error = err?.message || String(err);
+ this._files = [];
+ }
+ this._loading = false;
+ this._emitter.fire();
+ }
+
+ getTreeItem(node) {
+ return node;
+ }
+
+ getChildren(node) {
+ if (this._loading) return [];
+ if (this._error) return [infoNode(`Could not scan the workspace: ${this._error}`, 'error')];
+ if (!node) return this._groups();
+ return (node.files || []).map((file) => this._modelNode(file));
+ }
+
+ _groups() {
+ if (!this._files.length) return [];
+ const byFolder = new Map();
+ for (const file of this._files) {
+ const folder = dirLabel(file.uri);
+ if (!byFolder.has(folder)) byFolder.set(folder, []);
+ byFolder.get(folder).push(file);
+ }
+ // A single folder is not worth a level of nesting.
+ if (byFolder.size === 1) return this._files.map((file) => this._modelNode(file));
+ return [...byFolder.entries()].map(([folder, files]) => {
+ const item = new vscode.TreeItem(folder, vscode.TreeItemCollapsibleState.Expanded);
+ item.iconPath = vscode.ThemeIcon.Folder;
+ item.description = `${files.length} model${files.length === 1 ? '' : 's'}`;
+ item.files = files;
+ item.contextValue = 'threews3dFolder';
+ return item;
+ });
+ }
+
+ _modelNode({ uri, size }) {
+ const name = uri.path.split('/').pop();
+ const item = new vscode.TreeItem(name, vscode.TreeItemCollapsibleState.None);
+ item.resourceUri = uri;
+ item.description = formatBytes(size);
+ const url = this.links.get(uri);
+ item.tooltip = new vscode.MarkdownString(
+ [
+ `**${name}**`,
+ '',
+ `- **Size:** ${formatBytes(size)}`,
+ `- **Path:** \`${vscode.workspace.asRelativePath(uri, false)}\``,
+ url ? `- **Source:** ${url}` : '- **Source:** local file',
+ ].join('\n'),
+ );
+ item.iconPath = new vscode.ThemeIcon('symbol-color');
+ item.contextValue = 'threews3dModel';
+ item.command = {
+ command: 'vscode.openWith',
+ title: 'Open in the 3D viewer',
+ arguments: [uri, 'threews3d.modelViewer'],
+ };
+ return item;
+ }
+}
+
+function dirLabel(uri) {
+ const relative = vscode.workspace.asRelativePath(uri, false);
+ const parts = relative.split('/');
+ parts.pop();
+ return parts.join('/') || '.';
+}
+
+function infoNode(label, icon) {
+ const node = new vscode.TreeItem(label, vscode.TreeItemCollapsibleState.None);
+ node.iconPath = new vscode.ThemeIcon(icon);
+ node.contextValue = 'threews3dInfo';
+ return node;
+}
diff --git a/packages/vscode-3d/src/naming.js b/packages/vscode-3d/src/naming.js
new file mode 100644
index 000000000..220fdbb71
--- /dev/null
+++ b/packages/vscode-3d/src/naming.js
@@ -0,0 +1,55 @@
+// Filename helpers. Pure: no vscode, no fs, so they are unit tested directly.
+
+const MAX_SLUG = 48;
+
+/**
+ * Turn a prompt into a short, safe, readable file stem.
+ * "A friendly round robot mascot, glossy white" -> "a-friendly-round-robot-mascot-glossy-white"
+ */
+export function slugFromPrompt(prompt, fallback = 'model') {
+ const slug = String(prompt || '')
+ .toLowerCase()
+ .normalize('NFKD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, MAX_SLUG)
+ .replace(/-+$/g, '');
+ return slug || fallback;
+}
+
+/** The stem of a URL's last path segment, slugified. */
+export function slugFromUrl(url, fallback = 'model') {
+ try {
+ const last = new URL(url).pathname.split('/').filter(Boolean).pop() || '';
+ return slugFromPrompt(last.replace(/\.(glb|gltf)$/i, ''), fallback);
+ } catch {
+ return fallback;
+ }
+}
+
+/**
+ * First name in `<stem>.glb`, `<stem>-2.glb`, `<stem>-3.glb`… that `taken` does
+ * not already hold. Keeps generated models from silently overwriting each other.
+ *
+ * @param {string} stem
+ * @param {string} ext including the dot, e.g. ".glb"
+ * @param {(name: string) => boolean} taken
+ */
+export function uniqueName(stem, ext, taken) {
+ const base = `${stem}${ext}`;
+ if (!taken(base)) return base;
+ for (let n = 2; n < 1000; n++) {
+ const candidate = `${stem}-${n}${ext}`;
+ if (!taken(candidate)) return candidate;
+ }
+ return `${stem}-${Date.now()}${ext}`;
+}
+
+/** Human file size, matching how the viewer reports it. */
+export function formatBytes(bytes) {
+ const n = Number(bytes) || 0;
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
+}
diff --git a/packages/vscode-3d/src/studio.js b/packages/vscode-3d/src/studio.js
new file mode 100644
index 000000000..9452506fa
--- /dev/null
+++ b/packages/vscode-3d/src/studio.js
@@ -0,0 +1,127 @@
+// The one place this extension talks to the three.ws studio.
+//
+// Everything goes through POST /api/mcp-studio, the public JSON-RPC endpoint
+// behind the free text to 3D lane: no API key, no account, no payment. The
+// origin is a setting so the same code drives a local dev server or a preview
+// deployment without a rebuild.
+
+/** Tools this extension calls, with the argument each one takes. */
+export const TOOLS = Object.freeze({
+ model: 'forge_free',
+ avatar: 'text_to_avatar',
+ rig: 'rig_mesh',
+});
+
+/**
+ * Pull the model out of a tools/call result.
+ *
+ * The studio answers with `structuredContent` when it has a model, and with
+ * `content[]` text blocks when it has something to say instead (a refusal, a
+ * provider error). Both shapes are handled so a lane change upstream degrades
+ * to a readable message rather than "undefined".
+ *
+ * @param {any} result
+ * @returns {{ glbUrl: string, viewerUrl?: string, format?: string, prompt?: string }}
+ */
+export function readModelResult(result) {
+ if (!result || typeof result !== 'object') {
+ throw new Error('the studio returned an empty response');
+ }
+ const structured = result.structuredContent;
+ const glbUrl = structured?.glbUrl || structured?.glb_url;
+ if (typeof glbUrl === 'string' && /^https?:\/\//.test(glbUrl)) {
+ return {
+ glbUrl,
+ viewerUrl: structured.viewerUrl || structured.viewer_url,
+ format: structured.format || 'glb',
+ prompt: structured.prompt,
+ };
+ }
+ const text = textOf(result);
+ if (result.isError) throw new Error(text || 'the studio refused the request');
+ // A successful call with no model is still a failure for the caller; surface
+ // whatever the studio said rather than an empty viewer.
+ throw new Error(text || 'the studio returned no model URL');
+}
+
+/** Join every text block of an MCP result into one message. */
+export function textOf(result) {
+ const blocks = Array.isArray(result?.content) ? result.content : [];
+ return blocks
+ .map((b) => (typeof b?.text === 'string' ? b.text.trim() : ''))
+ .filter(Boolean)
+ .join('\n')
+ .slice(0, 2000);
+}
+
+/**
+ * Call one studio tool and return its model.
+ *
+ * @param {string} origin
+ * @param {string} name tool name, see TOOLS
+ * @param {Record<string, unknown>} args
+ * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
+ */
+export async function callTool(origin, name, args, opts = {}) {
+ const body = {
+ jsonrpc: '2.0',
+ id: Date.now(),
+ method: 'tools/call',
+ params: { name, arguments: args },
+ };
+ const payload = await rpc(origin, body, opts);
+ return readModelResult(payload.result);
+}
+
+/** Raw JSON-RPC call with a timeout, an abort hook, and readable errors. */
+export async function rpc(origin, body, { signal, timeoutMs = 6 * 60_000 } = {}) {
+ const url = new URL('/api/mcp-studio', normalizeOrigin(origin)).href;
+ const controller = new AbortController();
+ const onAbort = () => controller.abort();
+ if (signal) {
+ if (signal.aborted) controller.abort();
+ else signal.addEventListener('abort', onAbort, { once: true });
+ }
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ let res;
+ try {
+ res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify(body),
+ signal: controller.signal,
+ });
+ } catch (err) {
+ if (controller.signal.aborted && !signal?.aborted) {
+ throw new Error(`the studio did not answer within ${Math.round(timeoutMs / 1000)}s`);
+ }
+ throw new Error(`could not reach ${url}: ${err?.message || err}`);
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
+ }
+
+ const text = await res.text();
+ let payload;
+ try {
+ payload = JSON.parse(text);
+ } catch {
+ throw new Error(`the studio returned ${res.status} with a non-JSON body`);
+ }
+ if (payload.error) {
+ throw new Error(payload.error.message || `the studio returned error ${payload.error.code}`);
+ }
+ if (!res.ok) {
+ throw new Error(`the studio returned HTTP ${res.status}`);
+ }
+ return payload;
+}
+
+/** Trim a trailing slash and reject anything that is not an http(s) origin. */
+export function normalizeOrigin(raw) {
+ const origin = String(raw || '').trim().replace(/\/+$/, '');
+ if (!/^https?:\/\//.test(origin)) {
+ throw new Error(`threews3d.origin must be an http(s) origin, got "${raw}"`);
+ }
+ return origin;
+}
diff --git a/packages/vscode-3d/src/viewer.js b/packages/vscode-3d/src/viewer.js
new file mode 100644
index 000000000..5ce8f83f4
--- /dev/null
+++ b/packages/vscode-3d/src/viewer.js
@@ -0,0 +1,274 @@
+// The 3D viewer: a custom editor for .glb/.gltf files in the workspace, and a
+// panel for models that live on a URL.
+//
+// The host owns the file: it reads the bytes, runs the inspector, and streams
+// the report to the webview. The webview owns the picture.
+
+import * as vscode from 'vscode';
+import { reportFor } from './inspect.js';
+import { trackPanel } from './active-panel.js';
+
+export const VIEW_TYPE = 'threews3d.modelViewer';
+
+/** Models larger than this are rendered but not inspected; the report would stall. */
+const MAX_INSPECT_BYTES = 96 * 1024 * 1024;
+
+/** Custom editor for model files. One webview per open document. */
+export class ModelViewerProvider {
+ /** @param {vscode.ExtensionContext} context @param {import('./links.js').ModelLinks} links */
+ constructor(context, links, output) {
+ this.context = context;
+ this.links = links;
+ this.output = output;
+ }
+
+ static register(context, links, output) {
+ return vscode.window.registerCustomEditorProvider(
+ VIEW_TYPE,
+ new ModelViewerProvider(context, links, output),
+ {
+ webviewOptions: { retainContextWhenHidden: true },
+ supportsMultipleEditorsPerDocument: false,
+ },
+ );
+ }
+
+ async openCustomDocument(uri) {
+ return { uri, dispose: () => {} };
+ }
+
+ async resolveCustomEditor(document, panel) {
+ const dir = vscode.Uri.joinPath(document.uri, '..');
+ panel.webview.options = {
+ enableScripts: true,
+ localResourceRoots: [vscode.Uri.joinPath(this.context.extensionUri, 'media'), dir],
+ };
+ panel.webview.html = viewerHtml(panel.webview, this.context.extensionUri);
+ trackPanel(panel);
+
+ const src = panel.webview.asWebviewUri(document.uri).toString();
+ const wire = attachViewer(this.context, panel, {
+ src,
+ resource: document.uri,
+ links: this.links,
+ output: this.output,
+ readBytes: () => vscode.workspace.fs.readFile(document.uri),
+ });
+
+ // Regenerate the model on disk and the open viewer catches up on its own.
+ const watcher = vscode.workspace.createFileSystemWatcher(
+ new vscode.RelativePattern(dir, path(document.uri)),
+ );
+ watcher.onDidChange(() => wire.reload());
+ panel.onDidDispose(() => {
+ watcher.dispose();
+ wire.dispose();
+ });
+ }
+}
+
+/** Open a model that lives on an http(s) URL in its own panel. */
+export function openRemoteModel(context, links, output, url, title) {
+ const panel = vscode.window.createWebviewPanel(
+ VIEW_TYPE,
+ title || 'three.ws 3D',
+ vscode.ViewColumn.Active,
+ {
+ enableScripts: true,
+ retainContextWhenHidden: true,
+ localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'media')],
+ },
+ );
+ panel.webview.html = viewerHtml(panel.webview, context.extensionUri);
+ trackPanel(panel);
+ const wire = attachViewer(context, panel, {
+ src: url,
+ remoteUrl: url,
+ links,
+ output,
+ readBytes: async () => {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return new Uint8Array(await res.arrayBuffer());
+ },
+ });
+ panel.onDidDispose(() => wire.dispose());
+ return panel;
+}
+
+/**
+ * Wire one webview: hand it the model, run the report, and route its actions
+ * back into the extension's commands.
+ */
+function attachViewer(context, panel, { src, resource, remoteUrl, links, output, readBytes }) {
+ let disposed = false;
+
+ const post = (message) => {
+ if (!disposed) panel.webview.postMessage(message);
+ };
+
+ const sendReport = async () => {
+ try {
+ const bytes = await readBytes();
+ if (bytes.byteLength > MAX_INSPECT_BYTES) return;
+ const { rows, suggestions } = await reportFor(bytes);
+ post({ type: 'report', rows, suggestions });
+ } catch (err) {
+ output.appendLine(`report failed for ${resource?.fsPath || remoteUrl}: ${err?.message || err}`);
+ }
+ };
+
+ const sub = panel.webview.onDidReceiveMessage(async (msg) => {
+ if (msg?.type === 'ready') {
+ post({ type: 'load', src });
+ sendReport();
+ } else if (msg?.type === 'error') {
+ output.appendLine(`viewer: ${msg.message}`);
+ } else if (msg?.type === 'snapshot') {
+ await saveSnapshot(msg.dataUrl, resource, output);
+ } else if (msg?.type === 'action') {
+ await runAction(msg.action, { resource, remoteUrl });
+ }
+ });
+
+ return {
+ reload: () => {
+ post({ type: 'load', src: `${src}${src.includes('?') ? '&' : '?'}t=${Date.now()}` });
+ sendReport();
+ },
+ dispose: () => {
+ disposed = true;
+ sub.dispose();
+ },
+ };
+}
+
+async function runAction(action, { resource, remoteUrl }) {
+ const target = resource || (remoteUrl ? vscode.Uri.parse(remoteUrl) : undefined);
+ if (action === 'openInBrowser') {
+ await vscode.commands.executeCommand('threews3d.openInBrowser', target);
+ } else if (action === 'embed') {
+ await vscode.commands.executeCommand('threews3d.insertEmbed', target);
+ } else if (action === 'rig') {
+ await vscode.commands.executeCommand('threews3d.rigModel', target);
+ }
+}
+
+/** Write the webview's PNG next to the model (or into the workspace root). */
+async function saveSnapshot(dataUrl, resource, output) {
+ const match = /^data:image\/png;base64,(.+)$/.exec(String(dataUrl || ''));
+ if (!match) {
+ vscode.window.showErrorMessage('three.ws 3D: the snapshot came back empty.');
+ return;
+ }
+ const bytes = Buffer.from(match[1], 'base64');
+ const folder = resource
+ ? vscode.Uri.joinPath(resource, '..')
+ : vscode.workspace.workspaceFolders?.[0]?.uri;
+ if (!folder) {
+ vscode.window.showErrorMessage('three.ws 3D: open a folder to save a snapshot into.');
+ return;
+ }
+ const stem = resource ? path(resource).replace(/\.(glb|gltf)$/i, '') : 'model';
+ const target = vscode.Uri.joinPath(folder, `${stem}.png`);
+ await vscode.workspace.fs.writeFile(target, bytes);
+ output.appendLine(`snapshot written to ${target.fsPath}`);
+ const open = await vscode.window.showInformationMessage(
+ `Snapshot saved as ${path(target)}`,
+ 'Open',
+ );
+ if (open === 'Open') await vscode.commands.executeCommand('vscode.open', target);
+}
+
+function path(uri) {
+ return uri.path.split('/').pop() || '';
+}
+
+/** The webview document. Scripts are nonce-gated; nothing loads from a CDN. */
+export function viewerHtml(webview, extensionUri) {
+ const nonce = randomNonce();
+ const asset = (...parts) =>
+ webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, 'media', ...parts)).toString();
+ const config = {
+ dracoPath: `${asset('vendor', 'draco')}/`,
+ basisPath: `${asset('vendor', 'basis')}/`,
+ environment: setting('environment', 'studio'),
+ showGrid: setting('showGrid', true),
+ autoRotate: setting('autoRotate', false),
+ };
+ // wasm-unsafe-eval: the meshopt, Draco, and Basis decoders are WebAssembly.
+ // blob: workers: Draco and KTX2 build their worker from a blob at runtime.
+ const csp = [
+ "default-src 'none'",
+ `img-src ${webview.cspSource} data: blob:`,
+ `style-src ${webview.cspSource}`,
+ `script-src 'nonce-${nonce}' 'wasm-unsafe-eval' blob:`,
+ `connect-src ${webview.cspSource} https: data: blob:`,
+ 'worker-src blob:',
+ 'child-src blob:',
+ ].join('; ');
+
+ return `<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="${csp}">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<link rel="stylesheet" href="${asset('viewer.css')}">
+<title>three.ws 3D</title>
+</head>
+<body>
+<div id="stage"></div>
+
+<div id="loading">
+ <div class="spinner" aria-hidden="true"></div>
+ <p id="loading-label">Loading model…</p>
+</div>
+
+<div id="error" hidden role="alert">
+ <h2>This model could not be rendered</h2>
+ <p id="error-text"></p>
+ <p>Check that the file is a valid glTF 2.0 asset. A .gltf that points at
+ external buffers needs those files next to it in the workspace.</p>
+</div>
+
+<aside id="report" hidden aria-label="Model report">
+ <h2>Model report</h2>
+ <dl id="report-body"></dl>
+ <ul id="stats"></ul>
+</aside>
+
+<div id="toolbar" role="toolbar" aria-label="Viewer controls">
+ <span id="playback" hidden>
+ <button id="play" data-action="play" aria-pressed="true" title="Play or pause the animation">Pause</button>
+ <input id="scrub" type="range" min="0" max="1" step="0.001" value="0" aria-label="Animation time">
+ <select id="clips" hidden aria-label="Animation clip"></select>
+ </span>
+ <button data-toggle="grid" aria-pressed="${config.showGrid ? 'true' : 'false'}" title="Show the ground grid">Grid</button>
+ <button data-toggle="wireframe" aria-pressed="false" title="Draw the mesh as a wireframe">Wireframe</button>
+ <button data-toggle="skeleton" aria-pressed="false" title="Overlay the skeleton">Skeleton</button>
+ <button data-toggle="rotate" aria-pressed="${config.autoRotate ? 'true' : 'false'}" title="Orbit the camera automatically">Rotate</button>
+ <button data-action="reset" title="Frame the model again">Reset view</button>
+ <button data-toggle="report" aria-pressed="false" title="Triangles, materials, textures, rig, and optimization notes">Report</button>
+ <button data-action="snapshot" title="Save the current view as a PNG next to the model">Snapshot</button>
+ <button data-action="embed" title="Insert an &lt;agent-3d&gt; embed snippet">Embed</button>
+ <button data-action="rig" title="Add a humanoid skeleton with the three.ws rigger">Rig</button>
+ <button data-action="openInBrowser" title="Open this model in the three.ws viewer">three.ws</button>
+</div>
+
+<script nonce="${nonce}">window.__THREEWS_CONFIG__ = ${JSON.stringify(config)};</script>
+<script nonce="${nonce}" src="${asset('viewer.js')}"></script>
+</body>
+</html>`;
+}
+
+function setting(key, fallback) {
+ return vscode.workspace.getConfiguration('threews3d').get(key, fallback);
+}
+
+function randomNonce() {
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+ let out = '';
+ for (let i = 0; i < 32; i++) out += chars[Math.floor(Math.random() * chars.length)];
+ return out;
+}
diff --git a/packages/vscode-3d/test/activate.test.mjs b/packages/vscode-3d/test/activate.test.mjs
new file mode 100644
index 000000000..0d8bf0e50
--- /dev/null
+++ b/packages/vscode-3d/test/activate.test.mjs
@@ -0,0 +1,92 @@
+// Activates the bundled extension against a stand-in extension host and checks
+// that everything package.json promises actually exists at runtime: the
+// commands, the trees, the custom editor, and the viewer webview it renders.
+
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { readFileSync } from 'node:fs';
+import Module from 'node:module';
+
+const require = createRequire(import.meta.url);
+const { vscode, state, makePanel } = require('./fake-vscode.cjs');
+
+// The bundle requires 'vscode', which only the real host provides.
+const load = Module._load;
+Module._load = function (request, parent, isMain) {
+ if (request === 'vscode') return vscode;
+ return load.call(this, request, parent, isMain);
+};
+
+const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
+const extension = require('../dist/extension.cjs');
+
+const context = {
+ subscriptions: [],
+ extensionUri: vscode.Uri.file('/ext'),
+ workspaceState: (() => {
+ const store = new Map();
+ return { get: (k, d) => (store.has(k) ? store.get(k) : d), update: (k, v) => (store.set(k, v), Promise.resolve()) };
+ })(),
+};
+
+test('activate registers every contributed command', () => {
+ extension.activate(context);
+ for (const { command } of manifest.contributes.commands) {
+ assert.ok(state.commands.has(command), `${command} was never registered`);
+ }
+});
+
+test('activate registers both tree views and the custom editor', () => {
+ for (const view of manifest.contributes.views.threews3d) {
+ assert.ok(state.trees.has(view.id), `${view.id} has no provider`);
+ }
+ assert.ok(state.customEditors.has('threews3d.modelViewer'));
+});
+
+test('the workspace tree lists model files with their size', async () => {
+ state.files = [vscode.Uri.file('/workspace/models/robot.glb')];
+ const provider = state.trees.get('threews3d.models').provider;
+ await provider.refresh();
+ const children = await provider.getChildren();
+ assert.equal(children.length, 1);
+ assert.equal(children[0].label, 'robot.glb');
+ assert.equal(children[0].description, '1.0 KB');
+ assert.equal(children[0].command.arguments[1], 'threews3d.modelViewer');
+});
+
+test('the viewer webview is nonce-gated and loads only local assets', async () => {
+ const provider = state.customEditors.get('threews3d.modelViewer');
+ const uri = vscode.Uri.file('/workspace/models/robot.glb');
+ const document = await provider.openCustomDocument(uri);
+ const panel = makePanel();
+ await provider.resolveCustomEditor(document, panel);
+
+ const html = panel.webview.html;
+ const nonce = /nonce-([A-Za-z0-9]{32})/.exec(html)?.[1];
+ assert.ok(nonce, 'the CSP carries no nonce');
+ assert.ok(html.includes(`<script nonce="${nonce}" src="https://fake.vscode-cdn.net/ext/media/viewer.js">`));
+ assert.ok(html.includes("default-src 'none'"), 'CSP is not locked down');
+ assert.ok(html.includes("'wasm-unsafe-eval'"), 'the wasm decoders would be blocked');
+ assert.ok(!/src="http(s)?:\/\/(?!fake\.vscode-cdn\.net)/.test(html), 'the webview loads a remote asset');
+ assert.ok(html.includes('id="toolbar"'));
+ assert.ok(panel.webview.options.enableScripts);
+ assert.equal(panel.webview.options.localResourceRoots.length, 2);
+});
+
+test('the viewer hands the webview the model as soon as it is ready', async () => {
+ const provider = state.customEditors.get('threews3d.modelViewer');
+ const uri = vscode.Uri.file('/workspace/models/robot.glb');
+ const panel = makePanel();
+ const posted = [];
+ panel.webview.postMessage = (msg) => {
+ posted.push(msg);
+ return Promise.resolve(true);
+ };
+ await provider.resolveCustomEditor(await provider.openCustomDocument(uri), panel);
+ panel.webview.send({ type: 'ready' });
+ await new Promise((r) => setImmediate(r));
+ const load = posted.find((m) => m.type === 'load');
+ assert.ok(load, 'the model was never sent to the webview');
+ assert.equal(load.src, 'https://fake.vscode-cdn.net/workspace/models/robot.glb');
+});
diff --git a/packages/vscode-3d/test/embed.test.mjs b/packages/vscode-3d/test/embed.test.mjs
new file mode 100644
index 000000000..ddf86a333
--- /dev/null
+++ b/packages/vscode-3d/test/embed.test.mjs
@@ -0,0 +1,62 @@
+// The embed snippet is what a user pastes into their own site, so its shape is
+// pinned here: the library URL, the SRI hash, and the element attribute that
+// points at a bare GLB (body, not src).
+
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { buildEmbedSnippet, readRelease, viewerUrl } from '../src/embed.js';
+
+const MANIFEST = {
+ latest: '1.5.2',
+ channels: {
+ '1.5.2': { integrity: { 'agent-3d.js': 'sha384-abc' }, immutable: true },
+ latest: { tracks: '*' },
+ },
+};
+
+test('the pinned release carries its version and hash', () => {
+ assert.deepEqual(readRelease(MANIFEST), { channel: '1.5.2', integrity: 'sha384-abc' });
+});
+
+test('a manifest with no release falls back to the moving channel', () => {
+ assert.deepEqual(readRelease({}), { channel: 'latest', integrity: null });
+ assert.deepEqual(readRelease({ latest: '2.0.0' }), { channel: '2.0.0', integrity: null });
+});
+
+test('a pinned snippet loads the exact build with integrity', () => {
+ const snippet = buildEmbedSnippet({
+ src: 'https://three.ws/cdn/creations/abc/mesh.glb',
+ origin: 'https://three.ws',
+ ...readRelease(MANIFEST),
+ });
+ assert.match(snippet, /src="https:\/\/three\.ws\/agent-3d\/1\.5\.2\/agent-3d\.js"/);
+ assert.match(snippet, /integrity="sha384-abc"/);
+ assert.match(snippet, /crossorigin="anonymous"/);
+ assert.match(snippet, /<agent-3d\n {2}body="https:\/\/three\.ws\/cdn\/creations\/abc\/mesh\.glb"/);
+ assert.match(snippet, /width: 400px; height: 500px; display: block;/);
+});
+
+test('an unpinned snippet is a single script tag', () => {
+ const snippet = buildEmbedSnippet({
+ src: 'https://x/y.glb',
+ origin: 'https://three.ws',
+ channel: 'latest',
+ integrity: null,
+ });
+ assert.match(snippet, /^<script type="module" src="https:\/\/three\.ws\/agent-3d\/latest\/agent-3d\.js"><\/script>$/m);
+ assert.doesNotMatch(snippet, /integrity/);
+});
+
+test('a model that is not on http(s) cannot be embedded', () => {
+ assert.throws(
+ () => buildEmbedSnippet({ src: '/models/local.glb', origin: 'https://three.ws', channel: 'latest' }),
+ /http\(s\) URL/,
+ );
+});
+
+test('the hosted viewer link encodes the model URL', () => {
+ assert.equal(
+ viewerUrl('https://three.ws', 'https://x/y.glb'),
+ 'https://three.ws/viewer?src=https%3A%2F%2Fx%2Fy.glb',
+ );
+});
diff --git a/packages/vscode-3d/test/fake-vscode.cjs b/packages/vscode-3d/test/fake-vscode.cjs
new file mode 100644
index 000000000..036cdb8f2
--- /dev/null
+++ b/packages/vscode-3d/test/fake-vscode.cjs
@@ -0,0 +1,207 @@
+// A minimal stand-in for the VS Code extension host API.
+//
+// Enough of the real surface for the bundled extension to activate, register
+// everything it contributes, and render the viewer webview, so the tests
+// exercise the shipped dist/extension.cjs rather than a rearranged copy of it.
+
+class EventEmitter {
+ constructor() {
+ this.listeners = new Set();
+ this.event = (fn) => {
+ this.listeners.add(fn);
+ return { dispose: () => this.listeners.delete(fn) };
+ };
+ }
+ fire(value) {
+ for (const fn of [...this.listeners]) fn(value);
+ }
+ dispose() {
+ this.listeners.clear();
+ }
+}
+
+class Uri {
+ constructor(scheme, path) {
+ this.scheme = scheme;
+ this.path = path;
+ }
+ get fsPath() {
+ return this.path;
+ }
+ toString() {
+ return `${this.scheme}://${this.path}`;
+ }
+ static file(p) {
+ return new Uri('file', p);
+ }
+ static parse(value) {
+ const match = /^([a-z][a-z0-9+.-]*):\/\/(.*)$/i.exec(String(value));
+ return match ? new Uri(match[1], match[2]) : new Uri('file', String(value));
+ }
+ static joinPath(base, ...parts) {
+ const joined = [base.path.replace(/\/+$/, ''), ...parts].join('/');
+ // Resolve the ".." segment the viewer uses to reach a model's folder.
+ const stack = [];
+ for (const segment of joined.split('/')) {
+ if (segment === '..') stack.pop();
+ else if (segment !== '.') stack.push(segment);
+ }
+ return new Uri(base.scheme, stack.join('/'));
+ }
+}
+
+class TreeItem {
+ constructor(label, collapsibleState) {
+ this.label = label;
+ this.collapsibleState = collapsibleState;
+ }
+}
+
+class ThemeIcon {
+ constructor(id) {
+ this.id = id;
+ }
+}
+ThemeIcon.Folder = new ThemeIcon('folder');
+
+class MarkdownString {
+ constructor(value) {
+ this.value = value;
+ }
+}
+
+class RelativePattern {
+ constructor(base, pattern) {
+ this.base = base;
+ this.pattern = pattern;
+ }
+}
+
+function watcher() {
+ return {
+ onDidCreate: () => ({ dispose() {} }),
+ onDidChange: () => ({ dispose() {} }),
+ onDidDelete: () => ({ dispose() {} }),
+ dispose() {},
+ };
+}
+
+const state = {
+ commands: new Map(),
+ trees: new Map(),
+ customEditors: new Map(),
+ outputs: [],
+ messages: [],
+ config: {},
+ files: [],
+ fileBytes: new Map(),
+};
+
+const vscode = {
+ EventEmitter,
+ Uri,
+ TreeItem,
+ ThemeIcon,
+ MarkdownString,
+ RelativePattern,
+ TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 },
+ ViewColumn: { Active: -1 },
+ ProgressLocation: { Notification: 15 },
+ ConfigurationTarget: { Global: 1 },
+ window: {
+ activeTextEditor: undefined,
+ createOutputChannel(name) {
+ const channel = { name, lines: [], appendLine: (l) => channel.lines.push(l), show() {}, dispose() {} };
+ state.outputs.push(channel);
+ return channel;
+ },
+ createTreeView(id, options) {
+ const view = {
+ id,
+ provider: options.treeDataProvider,
+ visible: false,
+ onDidChangeVisibility: () => ({ dispose() {} }),
+ dispose() {},
+ };
+ state.trees.set(id, view);
+ return view;
+ },
+ registerCustomEditorProvider(viewType, provider) {
+ state.customEditors.set(viewType, provider);
+ return { dispose() {} };
+ },
+ createWebviewPanel: () => makePanel(),
+ showInformationMessage: (m) => {
+ state.messages.push(['info', m]);
+ return Promise.resolve(undefined);
+ },
+ showWarningMessage: (m) => {
+ state.messages.push(['warn', m]);
+ return Promise.resolve(undefined);
+ },
+ showErrorMessage: (m) => {
+ state.messages.push(['error', m]);
+ return Promise.resolve(undefined);
+ },
+ showInputBox: () => Promise.resolve(undefined),
+ withProgress: (_options, task) =>
+ task({ report() {} }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) }),
+ },
+ workspace: {
+ workspaceFolders: [{ uri: Uri.file('/workspace'), name: 'workspace', index: 0 }],
+ getConfiguration: () => ({
+ get: (key, fallback) => (key in state.config ? state.config[key] : fallback),
+ update: () => Promise.resolve(),
+ }),
+ findFiles: () => Promise.resolve(state.files),
+ createFileSystemWatcher: watcher,
+ asRelativePath: (uri) => String(uri.path || uri).replace('/workspace/', ''),
+ fs: {
+ stat: () => Promise.resolve({ size: 1024 }),
+ readFile: (uri) => Promise.resolve(state.fileBytes.get(uri.path) || new Uint8Array()),
+ writeFile: (uri, bytes) => {
+ state.fileBytes.set(uri.path, bytes);
+ return Promise.resolve();
+ },
+ readDirectory: () => Promise.resolve([]),
+ createDirectory: () => Promise.resolve(),
+ },
+ },
+ commands: {
+ registerCommand(id, fn) {
+ state.commands.set(id, fn);
+ return { dispose: () => state.commands.delete(id) };
+ },
+ executeCommand: (id, ...args) => Promise.resolve(state.commands.get(id)?.(...args)),
+ },
+ env: {
+ clipboard: { writeText: () => Promise.resolve() },
+ openExternal: () => Promise.resolve(true),
+ },
+};
+
+function makePanel() {
+ const emitter = new EventEmitter();
+ return {
+ webview: {
+ options: {},
+ html: '',
+ cspSource: 'vscode-resource://fake',
+ asWebviewUri: (uri) => Uri.parse(`https://fake.vscode-cdn.net${uri.path}`),
+ onDidReceiveMessage: (fn) => {
+ emitter.event(fn);
+ return { dispose() {} };
+ },
+ postMessage: () => Promise.resolve(true),
+ send: (msg) => emitter.fire(msg),
+ },
+ active: true,
+ title: '',
+ reveal() {},
+ onDidChangeViewState: () => ({ dispose() {} }),
+ onDidDispose: () => ({ dispose() {} }),
+ dispose() {},
+ };
+}
+
+module.exports = { vscode, state, makePanel };
diff --git a/packages/vscode-3d/test/gallery.test.mjs b/packages/vscode-3d/test/gallery.test.mjs
new file mode 100644
index 000000000..d5d256680
--- /dev/null
+++ b/packages/vscode-3d/test/gallery.test.mjs
@@ -0,0 +1,72 @@
+// The forge gallery feed. Rows come from a public endpoint, so anything without
+// a usable model URL is dropped rather than rendered as a dead tree item.
+
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { normalizeCreation, listCreations } from '../src/gallery.js';
+
+test('the web-optimized copy wins over the original', () => {
+ const item = normalizeCreation({
+ id: 'abc',
+ prompt: ' a frog ',
+ glb_url: 'https://x/raw.glb',
+ web_glb_url: 'https://x/web.glb',
+ model_category: 'avatar',
+ });
+ assert.equal(item.glbUrl, 'https://x/web.glb');
+ assert.equal(item.prompt, 'a frog');
+ assert.equal(item.category, 'avatar');
+});
+
+test('a row with no model URL is dropped', () => {
+ assert.equal(normalizeCreation({ id: 'abc' }), null);
+ assert.equal(normalizeCreation({ id: 'abc', glb_url: 'ftp://x/y.glb' }), null);
+});
+
+test('the feed is normalised and filtered', async () => {
+ const server = createServer((req, res) => {
+ assert.match(req.url, /^\/api\/forge-gallery\?limit=40$/);
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ enabled: true,
+ creations: [
+ { id: '1', prompt: 'a frog', glb_url: 'https://x/1.glb' },
+ { id: '2', prompt: 'broken' },
+ ],
+ }),
+ );
+ });
+ await new Promise((r) => server.listen(0, r));
+ const items = await listCreations(`http://127.0.0.1:${server.address().port}`);
+ assert.equal(items.length, 1);
+ assert.equal(items[0].id, '1');
+ server.close();
+});
+
+test('a disabled gallery says so', async () => {
+ const server = createServer((req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ enabled: false }));
+ });
+ await new Promise((r) => server.listen(0, r));
+ await assert.rejects(
+ () => listCreations(`http://127.0.0.1:${server.address().port}`),
+ /turned off/,
+ );
+ server.close();
+});
+
+test('an HTTP failure is reported with its status', async () => {
+ const server = createServer((req, res) => {
+ res.writeHead(500);
+ res.end('nope');
+ });
+ await new Promise((r) => server.listen(0, r));
+ await assert.rejects(
+ () => listCreations(`http://127.0.0.1:${server.address().port}`),
+ /HTTP 500/,
+ );
+ server.close();
+});
diff --git a/packages/vscode-3d/test/naming.test.mjs b/packages/vscode-3d/test/naming.test.mjs
new file mode 100644
index 000000000..653b9b07c
--- /dev/null
+++ b/packages/vscode-3d/test/naming.test.mjs
@@ -0,0 +1,47 @@
+// File naming. A generated model lands next to the user's own files, so the name
+// has to be readable, safe on every platform, and never silently overwrite.
+
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { slugFromPrompt, slugFromUrl, uniqueName, formatBytes } from '../src/naming.js';
+
+test('a prompt becomes a readable stem', () => {
+ assert.equal(slugFromPrompt('A friendly round robot mascot'), 'a-friendly-round-robot-mascot');
+ assert.equal(slugFromPrompt(' Spaced out '), 'spaced-out');
+});
+
+test('accents, punctuation, and path separators are stripped', () => {
+ assert.equal(slugFromPrompt('Café Zürich naïve'), 'cafe-zurich-naive');
+ assert.equal(slugFromPrompt('../../etc/passwd'), 'etc-passwd');
+ assert.equal(slugFromPrompt('emoji 🐸 frog'), 'emoji-frog');
+});
+
+test('an empty or unusable prompt falls back', () => {
+ assert.equal(slugFromPrompt(''), 'model');
+ assert.equal(slugFromPrompt('***'), 'model');
+ assert.equal(slugFromPrompt('', 'avatar'), 'avatar');
+});
+
+test('a long prompt is truncated without a trailing dash', () => {
+ const stem = slugFromPrompt('a'.repeat(20) + ' ' + 'b'.repeat(40));
+ assert.ok(stem.length <= 48);
+ assert.doesNotMatch(stem, /-$/);
+});
+
+test('a URL contributes its file stem', () => {
+ assert.equal(slugFromUrl('https://x/forge/anon/abc123.glb'), 'abc123');
+ assert.equal(slugFromUrl('not a url'), 'model');
+});
+
+test('names never collide with what is already on disk', () => {
+ const taken = new Set(['robot.glb', 'robot-2.glb']);
+ assert.equal(uniqueName('robot', '.glb', (n) => taken.has(n)), 'robot-3.glb');
+ assert.equal(uniqueName('frog', '.glb', () => false), 'frog.glb');
+});
+
+test('sizes read the way the viewer reports them', () => {
+ assert.equal(formatBytes(512), '512 B');
+ assert.equal(formatBytes(2048), '2.0 KB');
+ assert.equal(formatBytes(2_500_000), '2.4 MB');
+ assert.equal(formatBytes(undefined), '0 B');
+});
diff --git a/packages/vscode-3d/test/studio.test.mjs b/packages/vscode-3d/test/studio.test.mjs
new file mode 100644
index 000000000..56d81579b
--- /dev/null
+++ b/packages/vscode-3d/test/studio.test.mjs
@@ -0,0 +1,114 @@
+// The studio client: how a tools/call answer becomes a model, and how the
+// transport reports the ways a call can fail.
+
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { readModelResult, textOf, normalizeOrigin, rpc, callTool, TOOLS } from '../src/studio.js';
+
+test('a structured result yields the model', () => {
+ const model = readModelResult({
+ structuredContent: {
+ kind: 'model',
+ glbUrl: 'https://three.ws/cdn/creations/abc/mesh.glb',
+ viewerUrl: 'https://three.ws/viewer?src=x',
+ format: 'glb',
+ prompt: 'a frog',
+ },
+ });
+ assert.equal(model.glbUrl, 'https://three.ws/cdn/creations/abc/mesh.glb');
+ assert.equal(model.prompt, 'a frog');
+});
+
+test('a snake_case glb_url is accepted too', () => {
+ assert.equal(
+ readModelResult({ structuredContent: { glb_url: 'https://x/y.glb' } }).glbUrl,
+ 'https://x/y.glb',
+ );
+});
+
+test('an error result surfaces what the studio said', () => {
+ assert.throws(
+ () => readModelResult({ isError: true, content: [{ type: 'text', text: 'lane is busy' }] }),
+ /lane is busy/,
+ );
+});
+
+test('a result with no model is a failure, not an empty viewer', () => {
+ assert.throws(() => readModelResult({ content: [] }), /no model URL/);
+ assert.throws(() => readModelResult(null), /empty response/);
+});
+
+test('a non-http URL is refused rather than opened', () => {
+ assert.throws(() => readModelResult({ structuredContent: { glbUrl: 'file:///etc/passwd' } }), /no model URL/);
+});
+
+test('text blocks are joined and capped', () => {
+ assert.equal(textOf({ content: [{ text: ' one ' }, { text: 'two' }] }), 'one\ntwo');
+ assert.equal(textOf({}), '');
+});
+
+test('the origin must be an http(s) origin', () => {
+ assert.equal(normalizeOrigin('https://three.ws/'), 'https://three.ws');
+ assert.throws(() => normalizeOrigin('three.ws'), /must be an http\(s\) origin/);
+});
+
+test('a JSON-RPC error is reported with its message', async () => {
+ const server = createServer((req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32602, message: 'prompt too short' } }));
+ });
+ await new Promise((r) => server.listen(0, r));
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ await assert.rejects(() => rpc(origin, { jsonrpc: '2.0', id: 1, method: 'tools/list' }), /prompt too short/);
+ server.close();
+});
+
+test('a non-JSON body is reported with its status', async () => {
+ const server = createServer((req, res) => {
+ res.writeHead(502, { 'content-type': 'text/html' });
+ res.end('<html>bad gateway</html>');
+ });
+ await new Promise((r) => server.listen(0, r));
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ await assert.rejects(() => rpc(origin, { jsonrpc: '2.0', id: 1, method: 'tools/list' }), /502 with a non-JSON body/);
+ server.close();
+});
+
+test('callTool posts a tools/call for the named tool', async () => {
+ let seen = null;
+ const server = createServer((req, res) => {
+ let body = '';
+ req.on('data', (c) => (body += c));
+ req.on('end', () => {
+ seen = JSON.parse(body);
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ jsonrpc: '2.0',
+ id: seen.id,
+ result: { structuredContent: { glbUrl: 'https://x/y.glb' } },
+ }),
+ );
+ });
+ });
+ await new Promise((r) => server.listen(0, r));
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ const model = await callTool(origin, TOOLS.model, { prompt: 'a frog', tier: 'draft' });
+ assert.equal(model.glbUrl, 'https://x/y.glb');
+ assert.equal(seen.method, 'tools/call');
+ assert.equal(seen.params.name, 'forge_free');
+ assert.deepEqual(seen.params.arguments, { prompt: 'a frog', tier: 'draft' });
+ server.close();
+});
+
+test('a timeout is reported as a timeout', async () => {
+ const server = createServer(() => {});
+ await new Promise((r) => server.listen(0, r));
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ await assert.rejects(
+ () => rpc(origin, { jsonrpc: '2.0', id: 1, method: 'tools/list' }, { timeoutMs: 60 }),
+ /did not answer within/,
+ );
+ server.close();
+});
diff --git a/packages/vscode-3d/webview/main.js b/packages/vscode-3d/webview/main.js
new file mode 100644
index 000000000..66f16967b
--- /dev/null
+++ b/packages/vscode-3d/webview/main.js
@@ -0,0 +1,405 @@
+// The viewer that runs inside the VS Code webview.
+//
+// Loads a GLB/glTF with three.js, lights it the way the three.ws viewer does
+// (ACES tone mapping, an image-based studio environment, one shadow-casting key
+// light), and exposes the controls a developer actually wants while looking at a
+// model in their editor: animation playback, wireframe, skeleton, grid, and a
+// PNG snapshot. Everything is local; the only network fetch is the model itself.
+
+import * as THREE from 'three';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+
+const vscode = acquireVsCodeApi();
+const stage = document.getElementById('stage');
+const els = {
+ loading: document.getElementById('loading'),
+ loadingLabel: document.getElementById('loading-label'),
+ error: document.getElementById('error'),
+ errorText: document.getElementById('error-text'),
+ toolbar: document.getElementById('toolbar'),
+ clips: document.getElementById('clips'),
+ play: document.getElementById('play'),
+ scrub: document.getElementById('scrub'),
+ playback: document.getElementById('playback'),
+ report: document.getElementById('report'),
+ reportBody: document.getElementById('report-body'),
+ stats: document.getElementById('stats'),
+};
+
+const config = window.__THREEWS_CONFIG__ || {};
+const state = {
+ mixer: null,
+ action: null,
+ clips: [],
+ model: null,
+ skeleton: null,
+ wireframe: false,
+ playing: true,
+ radius: 1,
+};
+
+const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
+renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+renderer.toneMapping = THREE.ACESFilmicToneMapping;
+renderer.toneMappingExposure = 1;
+renderer.shadowMap.enabled = true;
+renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+stage.appendChild(renderer.domElement);
+
+const scene = new THREE.Scene();
+scene.background = new THREE.Color(readThemeColor('--vscode-editor-background', '#1e1e1e'));
+
+const camera = new THREE.PerspectiveCamera(45, 1, 0.01, 1000);
+camera.position.set(0, 1.4, 3);
+
+const controls = new OrbitControls(camera, renderer.domElement);
+controls.enableDamping = true;
+controls.dampingFactor = 0.08;
+controls.autoRotateSpeed = 1.2;
+controls.autoRotate = Boolean(config.autoRotate);
+
+const key = new THREE.DirectionalLight(0xffffff, 2.2);
+key.position.set(3, 6, 4);
+key.castShadow = true;
+key.shadow.mapSize.set(2048, 2048);
+key.shadow.bias = -0.0005;
+scene.add(key, new THREE.HemisphereLight(0xffffff, 0x404040, 0.6));
+
+const ground = new THREE.Mesh(
+ new THREE.PlaneGeometry(1, 1),
+ new THREE.ShadowMaterial({ opacity: 0.28 }),
+);
+ground.rotation.x = -Math.PI / 2;
+ground.receiveShadow = true;
+scene.add(ground);
+
+let grid = null;
+
+if (config.environment !== 'none') {
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ if (config.environment === 'neutral') scene.environmentIntensity = 0.6;
+ pmrem.dispose();
+}
+
+const loader = new GLTFLoader();
+if (config.dracoPath) {
+ const draco = new DRACOLoader();
+ draco.setDecoderPath(config.dracoPath);
+ loader.setDRACOLoader(draco);
+}
+if (config.basisPath) {
+ const ktx2 = new KTX2Loader();
+ ktx2.setTranscoderPath(config.basisPath);
+ ktx2.detectSupport(renderer);
+ loader.setKTX2Loader(ktx2);
+}
+
+// Every three.ws avatar ships meshopt-compressed, so the decoder is wired before
+// the first load rather than lazily: GLTFLoader throws if it arrives late.
+MeshoptDecoder.ready
+ .then(() => {
+ loader.setMeshoptDecoder(MeshoptDecoder);
+ vscode.postMessage({ type: 'ready' });
+ })
+ .catch((err) => fail(`the meshopt decoder failed to start: ${err?.message || err}`));
+
+function readThemeColor(varName, fallback) {
+ const value = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
+ return value || fallback;
+}
+
+function fail(message) {
+ els.loading.hidden = true;
+ els.errorText.textContent = message;
+ els.error.hidden = false;
+ vscode.postMessage({ type: 'error', message });
+}
+
+function clearModel() {
+ if (!state.model) return;
+ scene.remove(state.model);
+ state.model.traverse((node) => {
+ if (node.isMesh) {
+ node.geometry?.dispose?.();
+ for (const mat of materialsOf(node)) {
+ for (const value of Object.values(mat)) value?.isTexture && value.dispose();
+ mat.dispose();
+ }
+ }
+ });
+ state.model = null;
+ if (state.skeleton) {
+ scene.remove(state.skeleton);
+ state.skeleton = null;
+ }
+ state.mixer = null;
+ state.action = null;
+ state.clips = [];
+}
+
+function materialsOf(mesh) {
+ return Array.isArray(mesh.material) ? mesh.material : [mesh.material];
+}
+
+function load(src) {
+ clearModel();
+ els.error.hidden = true;
+ els.loading.hidden = false;
+ els.loadingLabel.textContent = 'Loading model…';
+ loader.load(
+ src,
+ (gltf) => {
+ els.loading.hidden = true;
+ state.model = gltf.scene || gltf.scenes[0];
+ state.model.traverse((node) => {
+ if (node.isMesh) {
+ node.castShadow = true;
+ node.receiveShadow = true;
+ node.frustumCulled = false;
+ }
+ });
+ scene.add(state.model);
+ frame(state.model);
+ setupAnimations(gltf.animations || []);
+ applyGrid(config.showGrid !== false);
+ vscode.postMessage({ type: 'loaded', stats: sceneStats(gltf) });
+ },
+ (event) => {
+ if (event?.total) {
+ const pct = Math.round((event.loaded / event.total) * 100);
+ els.loadingLabel.textContent = `Loading model… ${pct}%`;
+ } else if (event?.loaded) {
+ els.loadingLabel.textContent = `Loading model… ${(event.loaded / 1024 / 1024).toFixed(1)} MB`;
+ }
+ },
+ (err) => fail(err?.message || 'the model could not be loaded'),
+ );
+}
+
+/** Frame the model: centre it on the origin, sit it on the ground, fit the camera. */
+function frame(model) {
+ const box = new THREE.Box3().setFromObject(model);
+ const size = box.getSize(new THREE.Vector3());
+ const center = box.getCenter(new THREE.Vector3());
+ const radius = Math.max(size.x, size.y, size.z) / 2 || 1;
+ state.radius = radius;
+
+ model.position.sub(new THREE.Vector3(center.x, box.min.y, center.z));
+
+ ground.scale.setScalar(radius * 20);
+ camera.near = radius / 100;
+ camera.far = radius * 100;
+ camera.updateProjectionMatrix();
+ resetView();
+}
+
+function resetView() {
+ const r = state.radius;
+ const height = state.model
+ ? new THREE.Box3().setFromObject(state.model).getSize(new THREE.Vector3()).y
+ : r * 2;
+ controls.target.set(0, height / 2, 0);
+ camera.position.set(r * 1.9, height * 0.62 + r * 0.6, r * 2.6);
+ controls.update();
+ key.target.position.set(0, height / 2, 0);
+ key.target.updateMatrixWorld();
+ scene.add(key.target);
+ const span = Math.max(r * 3, height * 1.5);
+ key.shadow.camera.left = -span;
+ key.shadow.camera.right = span;
+ key.shadow.camera.top = span;
+ key.shadow.camera.bottom = -span;
+ key.shadow.camera.far = span * 6;
+ key.shadow.camera.updateProjectionMatrix();
+}
+
+function applyGrid(show) {
+ if (grid) {
+ scene.remove(grid);
+ grid.geometry.dispose();
+ grid.material.dispose();
+ grid = null;
+ }
+ if (!show) return;
+ const span = Math.max(2, Math.ceil(state.radius * 6));
+ grid = new THREE.GridHelper(span * 2, span * 2, 0x9aa0a6, 0x6f767d);
+ grid.material.transparent = true;
+ grid.material.opacity = 0.5;
+ scene.add(grid);
+}
+
+function setupAnimations(clips) {
+ state.clips = clips;
+ els.playback.hidden = clips.length === 0;
+ els.clips.innerHTML = '';
+ if (!clips.length) return;
+ state.mixer = new THREE.AnimationMixer(state.model);
+ clips.forEach((clip, i) => {
+ const option = document.createElement('option');
+ option.value = String(i);
+ option.textContent = `${clip.name || `clip ${i + 1}`} (${clip.duration.toFixed(2)}s)`;
+ els.clips.appendChild(option);
+ });
+ els.clips.hidden = clips.length < 2;
+ playClip(0);
+}
+
+function playClip(index) {
+ const clip = state.clips[index];
+ if (!clip || !state.mixer) return;
+ state.action?.fadeOut(0.2);
+ state.action = state.mixer.clipAction(clip);
+ state.action.reset().fadeIn(0.2).play();
+ state.action.paused = !state.playing;
+ els.scrub.max = String(clip.duration);
+}
+
+function sceneStats(gltf) {
+ let triangles = 0;
+ let meshes = 0;
+ const materials = new Set();
+ const textures = new Set();
+ let bones = 0;
+ (gltf.scene || gltf.scenes[0]).traverse((node) => {
+ if (node.isBone) bones++;
+ if (!node.isMesh) return;
+ meshes++;
+ const geo = node.geometry;
+ const count = geo.index ? geo.index.count : geo.attributes.position?.count || 0;
+ triangles += Math.floor(count / 3);
+ for (const mat of materialsOf(node)) {
+ if (!mat) continue;
+ materials.add(mat.uuid);
+ for (const value of Object.values(mat)) {
+ if (value?.isTexture) textures.add(value.uuid);
+ }
+ }
+ });
+ return {
+ triangles,
+ meshes,
+ materials: materials.size,
+ textures: textures.size,
+ bones,
+ animations: (gltf.animations || []).length,
+ };
+}
+
+function setWireframe(on) {
+ state.wireframe = on;
+ state.model?.traverse((node) => {
+ if (!node.isMesh) return;
+ for (const mat of materialsOf(node)) {
+ if (mat) mat.wireframe = on;
+ }
+ });
+}
+
+function setSkeleton(on) {
+ if (on && !state.skeleton && state.model) {
+ state.skeleton = new THREE.SkeletonHelper(state.model);
+ state.skeleton.material.linewidth = 2;
+ scene.add(state.skeleton);
+ } else if (!on && state.skeleton) {
+ scene.remove(state.skeleton);
+ state.skeleton = null;
+ }
+}
+
+function renderReport(rows, suggestions) {
+ els.reportBody.innerHTML = '';
+ for (const [label, value] of rows) {
+ const dt = document.createElement('dt');
+ dt.textContent = label;
+ const dd = document.createElement('dd');
+ dd.textContent = value;
+ els.reportBody.append(dt, dd);
+ }
+ els.stats.innerHTML = '';
+ for (const s of suggestions) {
+ const li = document.createElement('li');
+ li.className = `sev-${s.severity}`;
+ li.textContent = s.message;
+ els.stats.appendChild(li);
+ }
+}
+
+// Toolbar wiring. Each toggle button carries data-toggle so the handler stays
+// one place instead of one listener per control.
+els.toolbar.addEventListener('click', (event) => {
+ const button = event.target.closest('button');
+ if (!button) return;
+ const action = button.dataset.action;
+ const toggle = button.dataset.toggle;
+ if (toggle) {
+ const on = button.getAttribute('aria-pressed') !== 'true';
+ button.setAttribute('aria-pressed', String(on));
+ if (toggle === 'grid') applyGrid(on);
+ if (toggle === 'wireframe') setWireframe(on);
+ if (toggle === 'skeleton') setSkeleton(on);
+ if (toggle === 'rotate') controls.autoRotate = on;
+ if (toggle === 'report') els.report.hidden = !on;
+ return;
+ }
+ if (action === 'reset') resetView();
+ if (action === 'snapshot') sendSnapshot();
+ if (action === 'play') togglePlay();
+ if (action) vscode.postMessage({ type: 'action', action });
+});
+
+els.clips.addEventListener('change', () => playClip(Number(els.clips.value)));
+
+els.scrub.addEventListener('input', () => {
+ if (!state.action) return;
+ state.action.time = Number(els.scrub.value);
+ state.mixer.update(0);
+});
+
+function togglePlay() {
+ state.playing = !state.playing;
+ if (state.action) state.action.paused = !state.playing;
+ els.play.setAttribute('aria-pressed', String(state.playing));
+ els.play.textContent = state.playing ? 'Pause' : 'Play';
+}
+
+function sendSnapshot() {
+ renderer.render(scene, camera);
+ vscode.postMessage({ type: 'snapshot', dataUrl: renderer.domElement.toDataURL('image/png') });
+}
+
+window.addEventListener('message', (event) => {
+ const msg = event.data;
+ if (msg?.type === 'load') load(msg.src);
+ if (msg?.type === 'report') renderReport(msg.rows || [], msg.suggestions || []);
+ if (msg?.type === 'snapshot') sendSnapshot();
+});
+
+const observer = new ResizeObserver(() => resize());
+observer.observe(stage);
+
+function resize() {
+ const { clientWidth: w, clientHeight: h } = stage;
+ if (!w || !h) return;
+ camera.aspect = w / h;
+ camera.updateProjectionMatrix();
+ renderer.setSize(w, h, false);
+}
+
+const clock = new THREE.Clock();
+renderer.setAnimationLoop(() => {
+ const dt = clock.getDelta();
+ if (state.mixer && state.playing) state.mixer.update(dt);
+ if (state.action && !els.scrub.matches(':active')) {
+ els.scrub.value = String(state.action.time % (state.action.getClip().duration || 1));
+ }
+ controls.update();
+ renderer.render(scene, camera);
+});
+
+resize();