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(cad): document CAD Forge, list parts in search, and stage the worker for deploy

nirholas360e7ba98c6a
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 32add43b4..ecd139a18 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -44,6 +44,7 @@ bottom.
| Avatar builder (full app) | [character-studio/](character-studio) | Fork of [m3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio), MIT, see [character-studio/LICENSE](character-studio/LICENSE) | Web-first character creator |
| Scene Studio (3D scene editor) | [src/scene-studio/](src/scene-studio) `→ /scene`: boot [main.js](src/scene-studio/main.js), shared GLB loader [loader.js](src/scene-studio/loader.js), action bar [actions.js](src/scene-studio/actions.js), first-run overlay [empty-state.js](src/scene-studio/empty-state.js), icon-button labels [toolbar-a11y.js](src/scene-studio/toolbar-a11y.js), chrome [studio.css](src/scene-studio/studio.css) | Vendored [mrdoob/three.js](https://github.com/mrdoob/three.js) r184 editor, MIT, see [src/scene-studio/vendor/README.md](src/scene-studio/vendor/README.md) | Import GLBs, compose scenes, edit materials/lights, export. The sibling modules never touch `vendor/**`: they add the Import-from-Forge / Export-presets / Share bar (which docks beside the resizable sidebar rather than over its tabs), the empty-state card a brand-new scene needs, accessible names plus `aria-pressed` on the icon-only translate/rotate/scale buttons and names on the animation timeline's play/pause/stop transport, and toast-based failures in place of native `alert()`/`prompt()`. Below 600px the sidebar dock drops the vendored `.TabbedPanel` 335px floor so it fits a 320px screen instead of hanging 15px off it, and the empty-state card starts below the action bar and caps itself at the viewport region. Pinned under the nav by `--nav-h` (the real injected-header height), not `--header-h`. Deep links: `?model=<glb_url>`, `?handoff=1` from `/pose`, `#file=<url>`. Docs: [docs/scene-studio.md](docs/scene-studio.md), [src/scene-studio/README.md](src/scene-studio/README.md). Tests: [tests/scene-studio-actions.test.js](tests/scene-studio-actions.test.js) |
| Diorama (text → 3D world) | [src/diorama/](src/diorama) `→ /diorama` | In-repo · backend [api/diorama.js](api/diorama.js) | One sentence → an explorable 3D diorama: Claude composes the scene, each object is forged to a real GLB, assembled live, saved to a public gallery + shareable permalink |
+| CAD Forge (text → parametric CAD) | Page [pages/cad.html](pages/cad.html) + [src/cad/](src/cad) `→ /cad` and `→ /cad/:id` (controller [main.js](src/cad/main.js), viewer [viewer.js](src/cad/viewer.js), shared parameter contract [params.js](src/cad/params.js)), API [api/cad.js](api/cad.js) `→ /api/cad` over [api/_lib/cad/](api/_lib/cad) (writer ladder, write/build/repair loop, store, service), MCP tools [api/_mcp3d/tools/cad.js](api/_mcp3d/tools/cad.js) (`cad_generate`, `cad_rebuild`), sandboxed kernel worker [workers/cad-forge/](workers/cad-forge) | Live · worker deploys from its own cloudbuild | A sentence becomes a build123d program the OpenCascade kernel has accepted: kernel errors go back to the writer (Kimi K3 on NIM first) until it builds, and the page streams each real stage. Key dimensions are annotated constants that become sliders; each value set rebuilds on the kernel and is cached under its own link. Downloads STEP, STL, GLB (true scale), a four-view SVG drawing and the Python program; handoffs to AR, Materialize and Scene Studio; refinements are linked designs. Parts join cross-entity search as type `part`. The worker runs model-written code with a static policy, seccomp, an unprivileged uid and rlimits, under a zero-role service account. Docs: [docs/cad-forge.md](docs/cad-forge.md). Tests: [tests/cad-forge.test.js](tests/cad-forge.test.js) plus the worker's in-image gate |
| Scene Composer (dress an avatar) | [pages/compose.html](pages/compose.html) `→ /compose` + [src/scene-compose.js](src/scene-compose.js) | Live | Forge props from text and parent them to a rigged avatar's skeleton bones, then Export GLB or save them back onto the avatar record as `appearance.attachments`. Bones are grouped into readable regions and stripped of rig prefixes; transform gizmos, 50-deep undo, grid snap, camera presets. Feeds off [api/forge.js](api/forge.js), [api/forge-gallery.js](api/forge-gallery.js) (own creations, falling back to the community showcase for a first-time visitor), [api/explore.js](api/explore.js) `?source=avatar&only3d=1` for the avatar picker, and `PATCH /api/avatars/:id` for Save outfit. Below 900px the scene panel becomes a drawer. Docs: [docs/compose.md](docs/compose.md) |
| Splat Viewer (photoreal Gaussian avatars) | [pages/splat.html](pages/splat.html) `→ /splat` + page module [src/splat-viewer.js](src/splat-viewer.js), renderer [src/splat-stage.js](src/splat-stage.js) | Live | Renders Gaussian-splat and radiance-field scenes in the browser, the photoreal output of capture engines like GaussianAvatars and HumanGaussian. Loads a `.ply`, `.spz`, `.splat`, `.ksplat` or `.sog` by URL, by upload, by drag-and-drop onto the stage, or from a `?src=` deep link, plus two procedurally generated samples; decoding is entirely client-side and nothing is uploaded. The format is sniffed from the bytes rather than the filename, and the URL loader rewrites GitHub `blob`/`raw`, Hugging Face `/blob/` and Dropbox links to their CORS-enabled raw form so a pasted human-facing link still fetches. [src/splat-stage.js](src/splat-stage.js) is shared with the Forge Studio Lab ([src/forge-studio/lab/mesh-to-splat.js](src/forge-studio/lab/mesh-to-splat.js)) and wraps [Spark](https://github.com/sparkjsdev/spark) (`@sparkjsdev/spark`, MIT), lazy-loaded on first render and torn down explicitly (the WebGL context is released by hand on every scene swap, which Spark's own dispose stops short of). Every state is designed: idle/drop, engine load, fetch, decode, sort, error, and a live HUD carrying the scene label, its real splat count, a recenter control and a download of the loaded buffer. Docs: [docs/splat.md](docs/splat.md) |
| Creator portfolio (human profile) | [pages/profile.html](pages/profile.html) `→ /u/:username` (self-view `/profile`), backend [api/users/[username].js](api/users/%5Busername%5D.js) + paginated [api/users/[username]/creations.js](api/users/%5Busername%5D/creations.js) `→ /api/users/:username/creations` | Live | Every three.ws user's public portfolio: avatars, agents, widgets, skills, plugins, coins, memories, items for sale, and (added 2026-07-12, extended 2026-07-23) a **Creations** tab merging forged 3D models + Scene Studio worlds + Material Studio restyles — real, live, spinning `<model-viewer>` cards, cursor-paginated for 100+ items. `/forge`, `/diorama`, and `/restyle` all stay anonymous by default (no login required); a signed-in creator's `user_id` is attached to `forge_creations`/`dioramas` rows at generation/save time (migration [api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql](api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql)) and to a new `material_restyles` row per AI restyle or colorway variant (migration [api/_lib/migrations/20260723140000_material_restyles.sql](api/_lib/migrations/20260723140000_material_restyles.sql), store [api/_lib/material-restyle-store.js](api/_lib/material-restyle-store.js)) so those creations surface here. The same opt-in attribution now links back from the diorama viewer HUD, the diorama gallery cards, and the forge result bar ("by @user") whenever a creation's creator is known. `/@:handle` ([pages/handle.html](pages/handle.html)) is a separate, narrower agent-embed page — not the human portfolio. |
diff --git a/api/_lib/cross-search.js b/api/_lib/cross-search.js
index b6e2b8b9f..3dd569398 100644
--- a/api/_lib/cross-search.js
+++ b/api/_lib/cross-search.js
@@ -22,6 +22,7 @@ import { sql } from './db.js';
import { publicUrlOrNull, thumbnailUrl } from './r2.js';
import { listRemixable } from './forge-store.js';
import { listDioramas } from './diorama-store.js';
+import { listDesigns } from './cad/store.js';
import { searchAgentLaunches } from './pump-agent-launches.js';
import { searchPumpTokens } from './pump-search.js';
@@ -183,6 +184,25 @@ export async function searchWorlds({ q, limit = 12 } = {}) {
}));
}
+// ── parts (CAD Forge designs) ─────────────────────────────────────────────────
+
+export async function searchParts({ q, limit = 12 } = {}) {
+ const rows = await listDesigns({ scope: 'recent', limit, q });
+ return rows.map((r) => ({
+ type: 'part',
+ id: r.id,
+ title: r.title || 'Untitled part',
+ description: Array.isArray(r.sizeMm) ? `${r.sizeMm.map((v) => Math.round(v * 10) / 10).join(' × ')} mm · ${r.prompt || ''}` : r.prompt || '',
+ image: r.thumb,
+ glbUrl: null,
+ assetUrl: `/cad/${encodeURIComponent(r.id)}`,
+ creator: null,
+ remix: null,
+ createdAt: r.createdAt,
+ signals: { viewCount: r.views || 0 },
+ }));
+}
+
// ── coins (three.ws launches, then market-wide pump.fun/Birdeye) ────────────
export async function searchCoins({ q, limit = 12 } = {}) {
diff --git a/api/search.js b/api/search.js
index 0238313d5..c9f393c79 100644
--- a/api/search.js
+++ b/api/search.js
@@ -43,17 +43,19 @@ import { limits, clientIp } from './_lib/rate-limit.js';
import { databaseConfigured } from './_lib/env.js';
import { forgeStoreEnabled } from './_lib/forge-store.js';
import { dioramaStoreEnabled } from './_lib/diorama-store.js';
+import { cadStoreEnabled } from './_lib/cad/store.js';
import {
searchAvatars,
searchAgents,
searchModels,
searchWorlds,
+ searchParts,
searchCoins,
attachFollowerCounts,
rankItems,
} from './_lib/cross-search.js';
-const TYPES = new Set(['avatar', 'agent', 'model', 'world', 'coin']);
+const TYPES = new Set(['avatar', 'agent', 'model', 'world', 'part', 'coin']);
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
@@ -90,18 +92,20 @@ export default wrap(async (req, res) => {
const wantsModels = forgeStoreEnabled() && (type === 'all' || type === 'model');
const wantsWorlds = dioramaStoreEnabled() && (type === 'all' || type === 'world');
+ const wantsParts = cadStoreEnabled() && (type === 'all' || type === 'part');
- const [avatarItems, agentItems, modelItems, worldItems, coinItems] = await Promise.all([
+ const [avatarItems, agentItems, modelItems, worldItems, partItems, coinItems] = await Promise.all([
type === 'all' || type === 'avatar' ? searchAvatars({ q: q || null, limit: perType }) : [],
type === 'all' || type === 'agent' ? searchAgents({ q: q || null, limit: perType }) : [],
wantsModels ? searchModels({ q: q || undefined, limit: perType }) : [],
wantsWorlds ? searchWorlds({ q: q || undefined, limit: perType }) : [],
+ wantsParts ? searchParts({ q: q || undefined, limit: perType }) : [],
// Coins require a query — there's no "browse all pump.fun tokens"
// concept here (that's /launches / /trending's job), only search.
q && (type === 'all' || type === 'coin') ? searchCoins({ q, limit: perType }) : [],
]);
- let items = [...avatarItems, ...agentItems, ...modelItems, ...worldItems, ...coinItems];
+ let items = [...avatarItems, ...agentItems, ...modelItems, ...worldItems, ...partItems, ...coinItems];
items = await attachFollowerCounts(items);
items = rankItems(items).slice(0, limit);
@@ -110,6 +114,7 @@ export default wrap(async (req, res) => {
agent: agentItems.length,
model: modelItems.length,
world: worldItems.length,
+ part: partItems.length,
coin: coinItems.length,
};
diff --git a/data/changelog.json b/data/changelog.json
index 551f2f404..35e215e7a 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-09",
+ "title": "Agents can now design real CAD parts",
+ "summary": "Two new tools on the 3D Studio MCP server bring CAD Forge to any agent. cad_generate turns a description into a parametric part that the OpenCascade kernel has built, and returns STEP, STL and GLB files, a drawing, exact measurements and a page with dimension sliders. cad_rebuild changes any dimension and rebuilds the part exactly, with no AI guesswork. They are free with a three.ws sign-in and work in Claude, Cursor or any MCP client.",
+ "tags": ["feature"],
+ "link": "/docs/cad-forge"
+ },
{
"date": "2026-10-09",
"title": "Splitting a model into parts says plainly when it cannot read an FBX",
diff --git a/data/pages.json b/data/pages.json
index 5493611c9..b78e0d9e9 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -177,6 +177,15 @@
"added": "2026-07-26",
"showcase": true
},
+ {
+ "path": "/cad",
+ "title": "CAD Forge",
+ "description": "Describe a mechanical part and get real parametric CAD checked by the OpenCascade kernel: STEP, STL, GLB and a drawing sheet, live dimension sliders, true-scale AR and one-click printing.",
+ "priority": 0.8,
+ "changefreq": "daily",
+ "added": "2026-10-09",
+ "showcase": true
+ },
{
"path": "/diorama",
"title": "Diorama",
@@ -3446,6 +3455,14 @@
"changefreq": "monthly",
"added": "2026-07-18"
},
+ {
+ "path": "/docs/cad-forge",
+ "title": "Docs · CAD Forge (text to parametric CAD)",
+ "description": "How a sentence becomes a kernel-checked build123d part: the write, build and repair loop, dimension parameters, the design page, the /api/cad HTTP API, the cad_generate and cad_rebuild MCP tools, and the sandbox that runs model-written code.",
+ "priority": 0.7,
+ "changefreq": "monthly",
+ "added": "2026-10-09"
+ },
{
"path": "/docs/diorama",
"title": "Docs · Diorama (text to world)",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 2b928c1d3..c38f456ae 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -2636,6 +2636,15 @@ as its own real, validated GLB**, not just a live preview swap.
---
+## AI API: text to parametric CAD
+
+`POST /api/cad` turns a description into a kernel-checked build123d part (`action: "generate"`, optionally streamed over SSE) or rebuilds a saved design at new dimension values (`action: "rebuild"`). `GET /api/cad?id=` reads a design, its lineage and a cached configuration; `&format=py` downloads the program; `?list=recent|featured` returns the gallery. Every design carries STEP, STL, GLB and SVG drawing URLs plus the kernel's measurements. Full request and response shapes, errors and limits: [CAD Forge](./cad-forge.md#http-api).
+
+```bash
+curl -s https://three.ws/api/cad -H 'content-type: application/json' \
+ -d '{"action":"generate","prompt":"L bracket, 90 degrees, 3 mm thick, four M4 holes"}' | jq '.design.files'
+```
+
## AI API — text→image
Text→image for agents over x402 — no API key, no account. The first **5 images/day
diff --git a/docs/cad-forge.md b/docs/cad-forge.md
new file mode 100644
index 000000000..c9ee098ae
--- /dev/null
+++ b/docs/cad-forge.md
@@ -0,0 +1,166 @@
+# CAD Forge
+
+Describe a mechanical part in a sentence and get real CAD: a parametric [build123d](https://github.com/gumyr/build123d) program that the OpenCascade geometry kernel has built, with exact dimensions you can change, STEP for engineering tools, STL for printers, a GLB at true scale for the web and AR, and a drawing sheet.
+
+- **Page:** [three.ws/cad](https://three.ws/cad), with each design at `/cad/<id>`
+- **API:** `POST /api/cad` and `GET /api/cad` (below)
+- **MCP:** `cad_generate` and `cad_rebuild` on the [3D Studio server](./mcp-3d-studio.md)
+- **Builder:** [workers/cad-forge](../workers/cad-forge/README.md)
+
+## Why it is different from text to 3D
+
+[Text to 3D](./forge.md) makes a mesh that looks like the thing you described, which suits characters, props and scenery. A functional part needs something else. A phone mount has to fit the phone, the screw holes have to clear an M4 screw, and the wall has to be thick enough to print. CAD Forge produces a boundary-representation solid built from real operations (extrusions, holes, fillets, booleans), so every size in it is exact and editable.
+
+| | Text to 3D | CAD Forge |
+| --- | --- | --- |
+| Output | Textured mesh (GLB) | B-rep solid (STEP) plus STL, GLB, SVG drawing |
+| Dimensions | Approximate, normalised scale | Exact millimetres, true scale |
+| Editable | Retexture, remesh | Every key dimension is a slider; refine in words |
+| Source | None | The Python program, yours to run anywhere |
+| Best for | Characters, props, decoration | Brackets, enclosures, mounts, gears, knobs, adapters |
+
+## How a design is made
+
+1. **Write.** A coding model writes a build123d program for the request, declaring the key dimensions as annotated constants (see [Parameters](#parameters)).
+2. **Build.** The [cad-forge worker](../workers/cad-forge/README.md) runs the program on the OpenCascade kernel in a sandbox and exports the files.
+3. **Repair.** If the kernel rejects the program, the real error (kind, message, failing line) goes back to the model, which rewrites it. This repeats up to three times. If a part builds as several disconnected solids, which almost always means a feature was left floating, the model gets one extra round to connect them; the first build is kept if that round fails.
+4. **Save.** The program, its parameters, the kernel's measurements and the files are stored. The design gets a permanent page.
+
+The page shows each of these stages live, including the kernel's actual error text during a repair. Nothing is shown to you until the kernel has accepted it.
+
+The writer is a model ladder in [`api/_lib/cad/writer.js`](../api/_lib/cad/writer.js): Kimi K3 on NVIDIA NIM first, then Nemotron Super, then gpt-oss-120b on Groq, then the platform's general LLM chain. The order came from a bake-off against the real kernel.
+
+### Kernel adjustments
+
+The worker shrinks a fillet or chamfer the kernel refuses, first to half and then to a quarter of its size, and leaves the edge sharp if no size works. Every adjustment is listed on the design page under **Kernel adjustments** and returned in the API's `adjustments` array, so you always know when the part differs from what the program asked for.
+
+### Standard parts
+
+Programs can use [bd_warehouse](https://github.com/gumyr/bd_warehouse) for parts that should never be modeled by hand: involute spur gears, ISO threads, ISO 4032 nuts, ISO 4762 cap screws, washers and deep-groove ball bearings. Ask for "a 20-tooth module 1.5 gear with a 5 mm bore" and you get a correct involute profile.
+
+## Parameters
+
+Each design declares its tunable dimensions as plain top-level constants with a label and a range:
+
+```python
+# title: Wall-mounted phone holder
+# summary: A cradle that screws to the wall and holds a phone upright.
+from build123d import *
+import math
+
+WIDTH = 80 # Overall width [40..160 mm]
+WALL = 2.4 # Wall thickness [1.2..6 mm]
+SLOTS = 6 # Slot count [2..12 count]
+```
+
+The format is `NAME = number # Label [min..max unit]`. The page turns each line into a slider and a number field. Moving one rebuilds the same program with only that value changed, on the kernel, with no model involved, so the result is exact and repeatable. Each set of values is cached and gets its own link (`/cad/<id>?v=<key>`), and the downloads, measurements and drawing follow the configuration you are looking at.
+
+Because the parameters are ordinary Python, the downloaded program runs unchanged anywhere build123d is installed:
+
+```bash
+pip install build123d bd_warehouse
+python wall-mounted-phone-holder.py
+```
+
+That includes [text-to-cad](https://github.com/earthtojake/text-to-cad), which uses the same kernel, so a design can move into a local agent workflow without conversion.
+
+## The design page
+
+- **3D view** with real-millimetre grid, edge lines and dimension callouts that read the kernel's exact extents. Orbit, zoom, reframe.
+- **Drawing** tab: front, right, top and isometric hidden-line views on one sheet.
+- **Dimensions:** the sliders. **Reset** returns to the original values.
+- **Measurements:** size, volume, surface area, topology, the kernel's validity check, and the mass if made solid in PLA, PETG, nylon, aluminium, steel or brass. Picking a material also changes the 3D finish.
+- **Files:** STEP, STL, GLB, the drawing SVG and the Python program.
+- **View in your space** opens the GLB in AR at true scale through [`/api/ar`](./ar.md). **Print it** hands the GLB to [Materialize](./materialize.md) for a printability check and a quote. **Open in Scene Studio** loads it into the scene editor.
+- **Refine:** describe a change ("add a cable slot in the back, make the walls 3 mm"). The current program, at the values you have set, is rewritten and rebuilt as a new design linked to this one, so every part keeps its history.
+
+## HTTP API
+
+### Generate a design
+
+`POST /api/cad`
+
+```json
+{ "action": "generate", "prompt": "L bracket, 90 degrees, 3 mm thick, four M4 holes", "stream": false }
+```
+
+| Field | Type | Notes |
+| --- | --- | --- |
+| `prompt` | string, 3-600 chars | The part, or the change when refining. Name key sizes in mm. |
+| `parentId` | uuid, optional | Refine this design instead of starting fresh. |
+| `values` | object, optional | With `parentId`: start from these parameter values. |
+| `stream` | boolean | `true` answers `text/event-stream` with `stage` events, then `done` or `error`. |
+
+Response `201`:
+
+```json
+{
+ "design": {
+ "id": "d71c75cc-b878-4ea7-bf29-b44638a1eea6",
+ "title": "Wall-Mounted Phone Holder",
+ "summary": "A wall-mounted phone holder with a cradle base and two countersunk screw holes for secure attachment.",
+ "prompt": "Wall-mounted phone holder with two countersunk screw holes",
+ "code": "# title: Wall-Mounted Phone Holder\n...",
+ "params": [{ "name": "WIDTH", "label": "Overall width", "value": 80, "min": 60, "max": 120, "step": 1, "unit": "mm", "line": 6 }],
+ "metrics": { "size_mm": [80, 100, 27], "volume_mm3": 24488.2485, "area_mm2": 17691.5323, "solids": 2, "faces": 32, "edges": 82, "valid": true },
+ "files": { "step": "https://...", "stl": "https://...", "glb": "https://...", "thumb_svg": "https://...", "drawing_svg": "https://..." },
+ "adjustments": [],
+ "url": "https://three.ws/cad/d71c75cc-b878-4ea7-bf29-b44638a1eea6"
+ },
+ "attempts": 1
+}
+```
+
+Streamed stages are `writing`, `building`, `repairing` (with `error: { kind, message, line }`), `built` and `saving`, each with its `attempt` number.
+
+Errors: `400 prompt_required`, `404 parent_not_found`, `422 design_failed` (with `lastError`, the kernel's final complaint), `429` rate limited (12 designs per 10 minutes per IP), `503 cad_unavailable` or `writer_unavailable`.
+
+```bash
+curl -s https://three.ws/api/cad -H 'content-type: application/json' \
+ -d '{"action":"generate","prompt":"Knob for a 6 mm D-shaft with grip ridges, 25 mm across"}' | jq '.design.url, .design.files.step'
+```
+
+### Rebuild at new values
+
+`POST /api/cad`
+
+```json
+{ "action": "rebuild", "id": "<design id>", "values": { "WIDTH": 120 } }
+```
+
+Returns `{ "variant": { "key", "values", "metrics", "files", "adjustments", "url" }, "cached": false }`. Values are clamped to each parameter's range and snapped to its step. A value set that has been built before returns instantly with `cached: true`. `422 rebuild_failed` means the kernel cannot build those values; `buildError` carries its message.
+
+### Read
+
+| Request | Returns |
+| --- | --- |
+| `GET /api/cad?id=<uuid>` | `{ design, lineage: { parent, children }, variant: null }` |
+| `GET /api/cad?id=<uuid>&v=<key>` | The same plus the cached `variant` |
+| `GET /api/cad?id=<uuid>&format=py[&v=<key>]` | The program as a `.py` download, at the variant's values if given |
+| `GET /api/cad?list=recent\|featured[&q=][&limit=]` | `{ designs: [card], available }`, cards carry `thumb` and `sizeMm` |
+
+## MCP
+
+`cad_generate(prompt, parent_id?, values?)` and `cad_rebuild(id, values)` on `https://three.ws/api/mcp-3d` run the same pipeline and return the files, measurements, parameters and the program. `cad_generate` is synchronous and usually takes 20 to 90 seconds; raise your client's per-call timeout if it is shorter. Pricing and access follow the rest of the [3D Studio server](./mcp-3d-studio.md#access--pricing): free with a three.ws sign-in, or $0.05 and $0.01 per call over x402.
+
+## Safety
+
+The program is written by a model from a request anyone can send, so the builder treats it as hostile. It runs in a one-use process with no network, no exec, no fork, an unprivileged user, hard resource limits and a static policy on what the code may touch. The worker holds no cloud credentials and runs as a service account with no IAM roles. Details: [workers/cad-forge](../workers/cad-forge/README.md#isolation).
+
+## Configuration
+
+| Variable | Where | Purpose |
+| --- | --- | --- |
+| `GCP_CAD_FORGE_URL` | three-ws-api | Base URL of the cad-forge Cloud Run service |
+| `CAD_FORGE_KEY` | three-ws-api | Bearer secret for the worker (`cad-forge-key` in Secret Manager) |
+| `CAD_WRITER_MODEL` | three-ws-api, optional | Override the leading NIM writer model |
+| `CAD_FORGE_GLOBAL_HOURLY` | three-ws-api, optional | Global hourly design ceiling (default 400) |
+
+Without the worker URL and key, or without a database and object storage, `/api/cad` answers `503 cad_unavailable` and the page says so while still showing existing designs.
+
+## Related
+
+- [Text to 3D](./forge.md) for organic and decorative models
+- [Machine Atlas](../src/assembly/README.md): machines generated from code in the browser
+- [Materialize](./materialize.md): print any model
+- [AR & WebXR](./ar.md): true-scale placement
diff --git a/docs/start-here.md b/docs/start-here.md
index af98d9fee..454e25240 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -66,6 +66,8 @@ Generations don't need a babysitter, either: start a forge job, close the tab, a
Curious what happens between the prompt and the model? [How the Forge works](./how-forge-works.md) tells the story in plain language; [the Forge pipeline](./forge-pipeline.md) is the full engineering deep dive.
+Need a functional part rather than a sculpture, such as a bracket, an enclosure, a gear or a knob? [CAD Forge](./cad-forge.md) turns a sentence into real parametric CAD that the OpenCascade kernel has built, with exact dimensions you can drag, STEP and STL downloads, and a drawing sheet.
+
Want the model in your hands rather than on a screen? [Materialize](./materialize.md) prints any generation in resin, nylon, colour sandstone or steel and ships it to your door, paid in USDC on Solana, with a certificate of authenticity attested on-chain. An AI agent can order one too, over x402, without a human in the loop.
---
@@ -255,6 +257,7 @@ Deeper references that don't fit a track above but answer real questions:
- [Guardian console](./guardian.md): the inbox for the other side of social recovery and inheritance of agent wallets
- [Coin Clash](./clash.md): token-gated community battles between coin factions
- [Daily Forge](./daily-forge.md): a new deterministic 3D creative challenge every day
+- [CAD Forge](./cad-forge.md): a sentence becomes a kernel-checked parametric part with STEP, STL, GLB, drawings and dimension sliders
- [x402 Studio](./x402-studio.md): the merchant console for running a paid x402 business on three.ws
- [Contributing](./contributing.md): local environment setup through a mergeable pull request
- [ERC-8004 smart contracts](./smart-contracts.md): contract interfaces, deployed addresses, and how to read and write each registry
diff --git a/src/labs.js b/src/labs.js
index 179d6d353..193a29bc4 100644
--- a/src/labs.js
+++ b/src/labs.js
@@ -12,6 +12,7 @@ const CATEGORIES = {
'/unstoppable': { label: 'AI', cat: 'ai', color: '#60a5fa', bg: 'rgba(96,165,250,.12)' },
'/three-live': { label: '3D Live', cat: '3d', color: '#34d399', bg: 'rgba(52,211,153,.12)' },
'/diorama': { label: '3D Live', cat: '3d', color: '#34d399', bg: 'rgba(52,211,153,.12)' },
+ '/cad': { label: '3D Live', cat: '3d', color: '#34d399', bg: 'rgba(52,211,153,.12)' },
'/mocap-studio': { label: '3D Live', cat: '3d', color: '#34d399', bg: 'rgba(52,211,153,.12)' },
'/assembly': { label: '3D Live', cat: '3d', color: '#34d399', bg: 'rgba(52,211,153,.12)' },
'/agenc/embodied': { label: 'AI', cat: 'ai', color: '#60a5fa', bg: 'rgba(96,165,250,.12)' },
diff --git a/src/search-page.js b/src/search-page.js
index b890b9ff5..61ab3e58d 100644
--- a/src/search-page.js
+++ b/src/search-page.js
@@ -15,6 +15,7 @@ const TYPE_LABELS = {
agent: 'Agents',
model: 'Models',
world: 'Worlds',
+ part: 'CAD parts',
coin: 'Coins',
};
@@ -23,6 +24,7 @@ const TYPE_CREATE_CTA = {
agent: { label: 'Create an agent', href: '/create-agent' },
model: { label: 'Forge a 3D model', href: '/forge' },
world: { label: 'Build a world', href: '/diorama' },
+ part: { label: 'Design a CAD part', href: '/cad' },
coin: { label: 'Launch a coin', href: '/launch' },
};
diff --git a/workers/cad-forge/README.md b/workers/cad-forge/README.md
index 3c213928b..13102be3a 100644
--- a/workers/cad-forge/README.md
+++ b/workers/cad-forge/README.md
@@ -1,31 +1,108 @@
# cad-forge
-Sandboxed worker that turns a build123d program into a real B-rep part (STEP, STL, GLB, optional SVG thumbnail and drawing).
+Builds a [build123d](https://github.com/gumyr/build123d) program into a real B-rep part on the OpenCascade kernel and returns the exported files: STEP, STL, GLB (metres, true scale, Y-up), an isometric hidden-line thumbnail and a four-view drawing sheet as SVG, plus the kernel's measurements.
+
+It is the builder behind [CAD Forge](../../docs/cad-forge.md) (`/cad`, `POST /api/cad`, and the `cad_generate` / `cad_rebuild` MCP tools). The programs it runs are written by a language model from a stranger's prompt, so everything here is built around running hostile Python safely.
+
+CPU only. FastAPI on Cloud Run (gen2).
+
+## Isolation
+
+Every build runs in its own `sandbox_child.py` process, which is used once and then discarded. Four independent layers:
+
+| Layer | Where | What it stops |
+| --- | --- | --- |
+| Static policy | `cad_policy.py` | Imports outside `build123d`, `bd_warehouse`, `math`, `itertools`, `functools`; whole-module imports of the CAD libraries; any underscore attribute or name (`__class__`, `__globals__`); `eval`, `exec`, `open`, `getattr`, `type`, `str.format` and the other escape hatches. The program runs under a trimmed `__builtins__` with an import guard that enforces the same allowlist at runtime and refuses any name that resolves to a module object. |
+| seccomp | `sandbox_child.install_seccomp` | After build123d is imported and before the program runs: `socket`, `connect`, `execve`, `fork`, `ptrace`, `unshare`, `mount` and friends return `EPERM`. Threads stay allowed (OpenCascade meshes in parallel). |
+| Unprivileged uid | `main._spawn` | The child runs as `nobody` with a scrubbed environment, so it cannot read the parent's environment or root-owned files. |
+| Resource limits | `main._limits` | Address space 3 GB, CPU time, file size, open files; a wall-clock kill at `BUILD_TIMEOUT_S`. |
+
+On Cloud Run the service also runs as `cad-forge-sandbox@`, a service account with no IAM roles, and authenticates callers with its own `cad-forge-key` secret, which no other worker shares.
+
+The image's build runs `test_cad_policy.py` and `test_sandbox.py` (real builds, plus real socket, exec, fork and parent-environment escape attempts) as a Docker step, so a sandbox regression fails the image instead of reaching production.
+
+## Kernel help
+
+* **Edge treatments.** `fillet` and `chamfer` are wrapped: a size the kernel rejects is retried at half and quarter size, then skipped, and every change is reported in `adjustments`. A cosmetic round is never worth failing a part over.
+* **Standard parts.** [bd_warehouse](https://github.com/gumyr/bd_warehouse) (Apache-2.0) is installed, so programs can use involute `SpurGear`, `IsoThread`, ISO fasteners and bearings instead of modeling them by hand.
+* **Crashes.** A segfault inside OpenCascade is reported as `kind: "crash"` with the program line that was running (read from `faulthandler`), so the caller's repair round knows what to rewrite.
+* **Drawings last.** The part's files and measurements are written before the hidden-line drawings. A build that times out while projecting views still returns the part, flagged `drawings_skipped`.
## API
-- `POST /build` with `{ "code": "<build123d program>" }`. Returns `200 { ok, metrics, artifacts, log, elapsed_s }`. A program that fails is still a 200 with `ok: false` and an `error` object so the caller can feed it back to the model for a repair round. Artifacts are base64.
-- `GET /health` returns `{ ok, warm, max_concurrent, seccomp_required, build123d }`.
+Every request except `/health` needs `Authorization: Bearer $API_KEY`.
-Every request needs the `API_KEY` bearer secret. Each build runs in its own `sandbox_child.py` process: unprivileged uid, scrubbed environment, resource limits and seccomp. The worker holds no cloud credentials; the API uploads the returned artifacts.
+### `POST /build`
+
+```json
+{ "code": "from build123d import *\nresult = Box(40, 20, 5)\n" }
+```
+
+Success:
+
+```json
+{
+ "ok": true,
+ "metrics": { "size_mm": [40, 20, 5], "min_mm": [-20, -10, -2.5], "volume_mm3": 4000, "area_mm2": 2200,
+ "center_mm": [0, 0, 0], "solids": 1, "faces": 6, "edges": 12, "valid": true },
+ "adjustments": [],
+ "artifacts": { "step": "<base64>", "stl": "<base64>", "glb": "<base64>", "thumb_svg": "<base64>", "drawing_svg": "<base64>" },
+ "timings_s": { "step": 0.012, "mesh": 0.005, "drawing": 0.012 },
+ "seccomp": true,
+ "log": "",
+ "elapsed_s": 0.044
+}
+```
+
+A program that fails is still a `200`, because the failure is the program's and the caller feeds it back to the model:
+
+```json
+{ "ok": false, "error": { "kind": "runtime", "message": "ValueError: ...", "line": 12 }, "log": "", "elapsed_s": 0.3 }
+```
+
+`kind` is one of `syntax`, `policy`, `runtime`, `result` (no solid, 2D sketch, missing `result`, too large), `timeout`, `memory`, `crash`, `export`, `sandbox`. A non-200 means the worker itself could not run the build.
+
+The program must assign the finished solid to `result` (a lone `BuildPart` in scope is accepted). Units are millimetres.
+
+### `GET /health`
+
+`{ "ok": true, "warm": 2, "max_concurrent": 2, "seccomp_required": true, "build123d": "0.13.0" }`
## Configuration
| Variable | Default | Meaning |
| --- | --- | --- |
-| `API_KEY` | required | shared bearer secret |
-| `MAX_CONCURRENT` | 2 | builds allowed at once |
-| `WARM_POOL` | `MAX_CONCURRENT` | parked children kept ready |
-| `BUILD_TIMEOUT_S` | 60 | wall-clock limit per build |
-| `REQUIRE_SECCOMP` | 1 | refuse to build when seccomp cannot load |
+| `API_KEY` | required | Bearer secret (`cad-forge-key` in Secret Manager) |
+| `MAX_CONCURRENT` | `2` | Builds allowed at once |
+| `WARM_POOL` | `MAX_CONCURRENT` | Sandbox children kept parked with build123d already imported |
+| `BUILD_TIMEOUT_S` | `60` | Wall-clock limit per build |
+| `SANDBOX_MEMORY_MB` | `3072` | Address-space limit per build |
+| `REQUIRE_SECCOMP` | `1` | Refuse to build when the seccomp filter cannot load |
-## Run
+## Run locally
```bash
-docker build -t cad-forge workers/cad-forge
-docker run --rm -p 8080:8080 -e API_KEY=secret cad-forge
-curl -s -X POST localhost:8080/build -H 'authorization: Bearer secret' \
- -H 'content-type: application/json' -d '{"code":"result = Box(10, 10, 10)"}'
+docker build -t cad-forge workers/cad-forge # also runs the full test gate
+docker run --rm -p 8091:8080 -e API_KEY=localdev cad-forge
+curl -s -X POST localhost:8091/build \
+ -H 'authorization: Bearer localdev' -H 'content-type: application/json' \
+ -d '{"code":"from build123d import *\nresult = Box(40, 20, 5)\n"}' | head -c 300
+```
+
+Point the API at it with `GCP_CAD_FORGE_URL=http://localhost:8091` and `CAD_FORGE_KEY=localdev`.
+
+Tests run inside the image (`python test_cad_policy.py && python test_sandbox.py`); `test_cad_policy.py` also runs on any Python 3.11+ without build123d.
+
+## Deploy
+
+```bash
+gcloud builds submit --config workers/cad-forge/cloudbuild.yaml \
+ --region us-central1 --project aerial-vehicle-466722-p5 \
+ --substitutions=SHORT_SHA=manual$(date +%s)
+
+URL=$(gcloud run services describe cad-forge --region us-central1 --project aerial-vehicle-466722-p5 --format='value(status.url)')
+gcloud run services update three-ws-api --region us-central1 --project aerial-vehicle-466722-p5 \
+ --update-env-vars GCP_CAD_FORGE_URL=$URL --update-secrets CAD_FORGE_KEY=cad-forge-key:latest
```
-Tests: `python -m pytest workers/cad-forge`. The caller lives in `api/_lib/cad/`.
+The service account, secret and image repository already exist.
diff --git a/workers/cad-forge/cloudbuild.yaml b/workers/cad-forge/cloudbuild.yaml
new file mode 100644
index 000000000..fbd54d050
--- /dev/null
+++ b/workers/cad-forge/cloudbuild.yaml
@@ -0,0 +1,89 @@
+# CAD Forge worker: builds model-written build123d programs on OpenCascade.
+#
+# gcloud builds submit --config workers/cad-forge/cloudbuild.yaml \
+# --region us-central1 --project aerial-vehicle-466722-p5 \
+# --substitutions=SHORT_SHA=manual$(date +%s)
+#
+# Builds run as the pinned three-ws-build service account: the project's
+# default compute service account was deleted.
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
+
+substitutions:
+ _REGION: us-central1
+ # Deliberately holds no IAM roles: this service runs code a model wrote, so a
+ # sandbox escape must find nothing to use. Its only grant is read access to
+ # its own bearer secret, which no other worker shares.
+ _RUN_SA: cad-forge-sandbox@aerial-vehicle-466722-p5.iam.gserviceaccount.com
+ _SERVICE: cad-forge
+ _REPO: cad-forge
+ # Warm by default: a cold start imports OpenCascade twice (server, then the
+ # first parked sandbox child), several seconds a user would watch. CPU-only.
+ _MIN_INSTANCES: "1"
+ _MAX_INSTANCES: "4"
+
+steps:
+ # The repository must exist before the push; create it on first deploy.
+ - id: repo
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: bash
+ args:
+ - -c
+ - >-
+ gcloud artifacts repositories describe ${_REPO} --location=${_REGION} >/dev/null 2>&1 ||
+ gcloud artifacts repositories create ${_REPO} --repository-format=docker --location=${_REGION}
+
+ # The Dockerfile runs the policy tests and the sandbox suite (real builds and
+ # real escape attempts) as a build step, so a sandbox regression fails here.
+ - id: build
+ name: gcr.io/cloud-builders/docker
+ dir: workers/cad-forge
+ args:
+ - build
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - .
+
+ - id: push
+ name: gcr.io/cloud-builders/docker
+ args:
+ - push
+ - --all-tags
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server
+
+ - id: deploy
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ - run
+ - deploy
+ - ${_SERVICE}
+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --region=${_REGION}
+ - --service-account=${_RUN_SA}
+ - --platform=managed
+ # gen2 runs a full Linux kernel, so the per-build seccomp filter and the
+ # uid drop behave exactly as the image's build-time gate tested them.
+ - --execution-environment=gen2
+ - --port=8080
+ - --cpu=4
+ - --memory=8Gi
+ - --concurrency=4
+ - --min-instances=${_MIN_INSTANCES}
+ - --max-instances=${_MAX_INSTANCES}
+ - --timeout=120
+ # The warm pool refills sandbox children in background threads between
+ # requests; throttled CPU would leave the next build cold.
+ - --no-cpu-throttling
+ - --allow-unauthenticated
+ - --set-env-vars=MAX_CONCURRENT=2,WARM_POOL=2,BUILD_TIMEOUT_S=60,REQUIRE_SECCOMP=1
+ - --set-secrets=API_KEY=cad-forge-key:latest
+
+images:
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+
+options:
+ machineType: E2_HIGHCPU_8
+ logging: CLOUD_LOGGING_ONLY
diff --git a/workers/cad-forge/sandbox_child.py b/workers/cad-forge/sandbox_child.py
index 788c697d2..f96c9838a 100644
--- a/workers/cad-forge/sandbox_child.py
+++ b/workers/cad-forge/sandbox_child.py
@@ -25,6 +25,7 @@ import io
import json
import math
import os
+import re
import sys
import time
import traceback
@@ -249,6 +250,25 @@ def _project(shape: Shape, origin, up):
return Compound(children=list(visible)), Compound(children=list(hidden))
+PAPER = "rgb(246,247,249)"
+VIEWBOX = re.compile(r'viewBox="([-\d.e]+) ([-\d.e]+) ([-\d.e]+) ([-\d.e]+)"')
+
+
+def add_paper(path: str) -> None:
+ """Give an exported SVG an opaque paper background so its dark linework
+ reads on any page, dark themes included."""
+ with open(path, "r", encoding="utf-8") as fh:
+ text = fh.read()
+ match = VIEWBOX.search(text)
+ if not match:
+ return
+ x, y, w, h = match.groups()
+ rect = f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{PAPER}"/>'
+ head_end = text.index(">", match.end()) + 1
+ with open(path, "w", encoding="utf-8") as fh:
+ fh.write(text[:head_end] + rect + text[head_end:])
+
+
def write_thumbnail(shape: Shape, path: str) -> None:
centered = shape.moved(bd.Location(-shape.center()))
extent = max(centered.bounding_box().size.X, centered.bounding_box().size.Y, centered.bounding_box().size.Z) or 1.0
@@ -261,6 +281,7 @@ def write_thumbnail(shape: Shape, path: str) -> None:
svg.add_shape(hidden, layer="hidden")
svg.add_shape(visible, layer="visible")
svg.write(path)
+ add_paper(path)
def write_drawing(shape: Shape, size_mm, path: str) -> None:
@@ -307,6 +328,7 @@ def write_drawing(shape: Shape, size_mm, path: str) -> None:
text = text.replace("</svg>", f'<g transform="scale(1,-1)"><g transform="scale(1,-1)">{captions}</g></g></svg>', 1)
with open(path, "w", encoding="utf-8") as fh:
fh.write(text)
+ add_paper(path)
def export_part(shape: Shape, metrics: dict) -> dict:
diff --git a/workers/cad-forge/test_sandbox.py b/workers/cad-forge/test_sandbox.py
index ddda9a4b6..5bf80110a 100644
--- a/workers/cad-forge/test_sandbox.py
+++ b/workers/cad-forge/test_sandbox.py
@@ -66,6 +66,10 @@ class SandboxBuildTests(unittest.TestCase):
self.assertGreater(len(art["stl"]), 84)
self.assertIn(b"<svg", art["thumb_svg"][:400])
self.assertIn(b"ISOMETRIC", art["drawing_svg"])
+ self.assertIn(b'fill="rgb(246,247,249)"', art["thumb_svg"])
+ import xml.dom.minidom
+ xml.dom.minidom.parseString(art["thumb_svg"])
+ xml.dom.minidom.parseString(art["drawing_svg"])
self.assertIn("built 60", out["log"])
if main.REQUIRE_SECCOMP:
self.assertTrue(out["seccomp"])