forma-3d 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md ADDED
@@ -0,0 +1,97 @@
1
+ # Using Forma with AI Agents
2
+
3
+ Forma is a 1.2 MB pure-Rust rewrite of headless Blender built so any LLM or coding agent can create, inspect, and export watertight 3D models in milliseconds with minimal token overhead.
4
+
5
+ ---
6
+
7
+ ## 1. Connect via MCP (`forma-mcp`) — Recommended
8
+
9
+ `forma-mcp` is a stateful stdio JSON-RPC 2.0 server with **4 tools** totaling **789 `o200k` tokens** (including the full `Forma-Pipe` syntax spec).
10
+
11
+ Build the binary once:
12
+ ```bash
13
+ cargo build --release
14
+ ```
15
+
16
+ Add to your MCP client config (Claude Code, Cursor, Codex, Antigravity, etc.) — either zero-install via npm (`forma-3d`) or pointing directly at the compiled native binary:
17
+ ```json
18
+ {
19
+ "mcpServers": {
20
+ "forma": {
21
+ "command": "npx",
22
+ "args": ["-y", "forma-3d-mcp"]
23
+ }
24
+ }
25
+ }
26
+ ```
27
+
28
+ > Also see [`SKILL.md`](SKILL.md) for a compact, drop-in Agent Skill file ready for LLM skill loaders.
29
+
30
+ ### Exposed Tools
31
+ | Tool | Purpose |
32
+ |---|---|
33
+ | `eval` | Execute transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result); returns a ~100-token spatial diff (`WT`, `NM`, `g` genus, `vol`, `bbox`, `size`, tags). |
34
+ | `inspect` | Inspect current scene invariants and bounding boxes without mutating state. |
35
+ | `tx` | O(1) copy-on-write state control: `checkpoint`, `rollback`, `undo`, `reset`. |
36
+ | `export` | Export to `.glb` (PBR + triplanar UVs), `.step`, `.3mf`, `.stl`, `.obj`, or render a zero-GPU 4-view studio `.png` preview (`~20–75 KB`). |
37
+
38
+ ---
39
+
40
+ ## 2. Use via Shell / Unix CLI (`forma`)
41
+
42
+ If your agent already has a shell tool, you don't even need MCP—pipe scripts directly into `forma`:
43
+
44
+ ```bash
45
+ # 1. Read the compact zero-shot language spec (~355 tokens)
46
+ forma spec
47
+
48
+ # 2. Build, verify watertightness, export CAD/mesh, and render a 4-view preview in ~15 ms
49
+ forma eval --strict --out part.glb --render preview.png --draw blueprint.svg <<'EOF'
50
+ flange = box(4, 2, 0.4)
51
+ | mat("steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)
52
+ | cut(cyl(0.5, 1))
53
+ | cut(cyl(0.25, 1), at=[(-1.4,-0.5,0), (-1.4,0.5,0), (1.4,-0.5,0), (1.4,0.5,0)])
54
+ section(flange, 0.0)
55
+ EOF
56
+ ```
57
+
58
+ Example compact diagnostic returned to the agent (~85 tokens):
59
+ ```text
60
+ OK [6.92ms] parts=1
61
+ - flange: V=265 F=546 WT=ok NM=0 B=0 g=5 vol=2.576 bbox=[-2.00,-1.00,-0.20]..[2.00,1.00,0.20] size=[4.00,2.00,0.40]
62
+ tags: back(2) bottom(196) front(2) left(2) right(2) side(146) top(196)
63
+ diff: +flange (vol=2.576)
64
+ query: section(part, z=0.000): loops=6 area=6.4393 perim=21.4096 xy=[-2.000,-1.000]..[2.000,1.000] size=[4.000,2.000]
65
+ ```
66
+
67
+ ---
68
+
69
+ ## 3. Recommended Agent Loop
70
+
71
+ 1. **Draft in `Forma-Pipe`**: Use semantic selectors (`vertical`, `top_rim`, `bottom_rim`, `outer_rim`, `top`, `sides`) and relational placement (`z0=0`, `| on(base)`, `| align(z, min, 0)`) instead of manual vertex/offset math.
72
+ 2. **Verify Invariants Immediately**: Check `WT=ok NM=0 B=0`, bounding box `size=[x,y,z]`, volume `vol`, and Euler genus `g` (e.g., `g=1` confirms a mug handle or bore is open; `g=5` confirms 5 through-holes).
73
+ 3. **Run Geometric Checks When Assembling Parts**:
74
+ - `clearance(part_a, part_b)` verifies exact minimum surface distance and catches collisions.
75
+ - `section(part, z)` verifies cross-section loop count and wall area at any height `z`.
76
+ 4. **Optional Visual Check for VLMs**: Render a 4-view (`Front / Right / Top / Iso`) studio preview via `--render preview.png` or `export(path="preview.png")` in ~4 ms with zero GPU, then inspect the image.
77
+ 5. **Safe Exploration**: Use `tx(action="checkpoint", tag="v1")` before risky boolean/bevel steps and `tx(action="rollback", tag="v1")` on error.
78
+
79
+ ---
80
+
81
+ ## 4. Zero-Syntax-Error Constrained Decoding (GBNF)
82
+
83
+ For local or self-hosted inference engines (`llama.cpp`, `vLLM`, `XGrammar`), export the formal GBNF grammar directly from the CLI or repo:
84
+
85
+ ```bash
86
+ forma spec --gbnf > forma_pipe.gbnf
87
+ # or use grammar/forma_pipe.gbnf directly
88
+ ```
89
+
90
+ ---
91
+
92
+ ## 5. Common Pitfalls & Best Practices
93
+
94
+ - **Cutting through-holes cleanly:** Make cutting cylinders slightly taller than the target plate (e.g., `cyl(0.5, 1.0)` for a `0.4` thick plate) to avoid grazing coplanar caps.
95
+ - **Multi-hole patterns:** Pass `at=[(x1,y1,z1), (x2,y2,z2), ...]` in a single `| cut(...)` or `| add(...)` call—Forma automatically batches pairwise-disjoint booleans in one pass.
96
+ - **Sharp revolved/mechanical subsurf:** Use `subsurf(1, crease=true)` if you want smooth curvature without shrinking sharp rims.
97
+ - **Exporting for downstream tools:** Use `.glb` for web/Blender/Three.js (includes PBR materials + triplanar UVs), `.step` for SolidWorks/Fusion 360/FreeCAD, `.3mf`/`.stl` for 3D printing, `.svg` for dimensioned blueprints, and `.blend` via Blender bridge.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 wrong-nebula
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,149 @@
1
- # Temporary Holding Version
1
+ # Forma
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server.**
4
+
5
+ <p align="center">
6
+ <img src="assets/readme_hero.png" alt="Forma — Pure-Rust Rewrite of Headless Blender for AI Agents" width="100%" />
7
+ </p>
8
+
9
+ Forma rewrites headless Blender's 3D modeling, boolean, and studio-preview workflow from scratch in pure Rust—replacing the 953 MB desktop stack and brittle `bpy` scripting with a compact declarative pipe language (`Forma-Pipe`), semantic edge/face selectors, guaranteed-manifold CSG booleans, transactional snapshots, and a built-in zero-GPU studio renderer.
10
+
11
+ | Metric | Stock Headless Blender 5.3 (`bpy`) | **Forma** | Improvement |
12
+ |---|---:|---:|---:|
13
+ | **Cold-Start Eval + GLB Export** | 1,306.8 ms | **16.9 ms** (`5.4 ms` batch flange) | **~77×–89× faster** |
14
+ | **Completion Tokens (12-model avg)** | 294,661 total | **84,551 total** | **3.49× fewer** (up to **15.5×**) |
15
+ | **Pass Rate (12 models / 10 labs)** | 79.1% (`bpy`) | **95.5% – 100%** | **+16.4 pp** |
16
+ | **Binary / Install Footprint** | 953 MB | **1.2 MB** | **~800× smaller** |
17
+ | **Peak Memory RSS** | 223 MB | **2.16 MB** | **103× less RAM** |
18
+ | **MCP Tool Schema Budget** | — | **789 `o200k` tokens** (4 tools) | Strictly `< 800` |
19
+
20
+ ---
21
+
22
+ ## Features
23
+
24
+ - **Declarative `Forma-Pipe` Language:** Chain primitives and ops cleanly (`box | bevel | shell | cut`) with semantic selectors (`vertical`, `top_rim`, `bottom_rim`, `outer_rim`, `top`, `sides`)—zero fragile integer vertex indices.
25
+ - **Fast, Watertight Pure-Rust Kernel:** Double-precision polyhedral B-rep, BVH-localized Möller-guarded booleans, automatic batch CSG for multi-hole patterns, zero-error Link-Condition coplanar mesh simplification, ring-preserving bevels, shell, crease-aware Catmull-Clark subsurf, `pipe`, `loft`, helical `thread`, `sweep`, `text3d`, and `pattern_linear`/`pattern_radial`.
26
+ - **Spatial Constraints & Queries:** Relational placement (`| on(base)`, `| align(axis, min|center|max, val)`), exact 3D `clearance(a, b)`, 2D `section(part, z)` loop/area queries, and Euler genus (`g`) diagnostics.
27
+ - **Zero-GPU Rendering & Blueprints:** Built-in 4-view (`Front / Right / Top / Iso`) studio PNG renderer with SSAO-lite + depth silhouettes + pure-Rust Deflate compression (`~20–75 KB` PNG in ~4 ms), plus dimensioned 1200×900 vector SVG technical blueprints (`forma draw`).
28
+ - **Universal Export:** Native `.glb` (PBR materials + automatic triplanar UVs), ISO 10303-21 `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, `.png`, and `.blend` (via optional Blender bridge).
29
+
30
+ ---
31
+
32
+ ## Quickstart
33
+
34
+ ### Option 1 — Zero-Install via npm (Cross-Platform WASM)
35
+
36
+ ```bash
37
+ npx -y forma-3d eval --strict --out flange.glb --render flange.png --draw flange.svg <<'EOF'
38
+ flange = box(4, 2, 0.4)
39
+ | mat("brushed_steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)
40
+ | cut(cyl(0.5, 1))
41
+ | cut(cyl(0.25, 1), at=[(-1.4,-0.5,0), (-1.4,0.5,0), (1.4,-0.5,0), (1.4,0.5,0)])
42
+ section(flange, 0.0)
43
+ EOF
44
+ ```
45
+
46
+ ### Option 2 — Build Native 1.2 MB Rust Binary
47
+
48
+ ```bash
49
+ git clone https://github.com/wrong-nebula/forma.git
50
+ cd forma
51
+ cargo build --release
52
+ ./target/release/forma eval --strict --out flange.glb --render flange.png --draw flange.svg script.forma
53
+ ```
54
+
55
+ <p align="center">
56
+ <img src="assets/readme_quad_views.png" alt="Built-In Pure-Rust 4-View Studio Renders" width="100%" />
57
+ </p>
58
+
59
+ ---
60
+
61
+ ## For AI Agents
62
+
63
+ Forma is designed for drop-in agent use via **MCP**, **CLI**, **Agent Skills**, or **GBNF constrained decoding**:
64
+
65
+ - **LLM Agent Skill:** [`SKILL.md`](SKILL.md)
66
+ - **Machine-readable index:** [`llms.txt`](llms.txt)
67
+ - **Full agent integration guide:** [`AGENTS.md`](AGENTS.md)
68
+ - **Constrained-decoding grammar:** [`grammar/forma_pipe.gbnf`](grammar/forma_pipe.gbnf) (`forma spec --gbnf`)
69
+
70
+ ### MCP Server Setup (`forma-mcp` / `npx forma-3d-mcp`)
71
+
72
+ Add Forma's MCP server (4 tools: `eval`, `inspect`, `tx`, `export` — **789 `o200k` tokens** total) to any MCP client:
73
+
74
+ ```json
75
+ {
76
+ "mcpServers": {
77
+ "forma": {
78
+ "command": "npx",
79
+ "args": ["-y", "forma-3d-mcp"]
80
+ }
81
+ }
82
+ }
83
+ ```
84
+
85
+ Or invoke directly from any shell-capable agent:
86
+ ```bash
87
+ forma spec # ~355-token language reference
88
+ forma eval --strict --out out.glb script.forma # transactional eval + ~100-tok spatial diff
89
+ forma render --out preview.png script.forma # 4-view studio PNG (~4 ms, zero GPU)
90
+ forma draw --out blueprint.svg script.forma # dimensioned vector engineering blueprint
91
+ ```
92
+
93
+ ---
94
+
95
+ ## Benchmarks
96
+
97
+ All models were evaluated head-to-head on stock headless **Blender 5.3.0 (`bpy`)** vs **Forma (`Forma-Pipe`)** across 6 cross-category exact-dimension tasks (`flange_plate`, `pipe_tee`, `beveled_enclosure`, `hex_nut`, `subdiv_mug`, `pedestal_bowl`), verified independently with `trimesh` + `scipy` (Chamfer distance, Hausdorff-99, Generalized Winding Number Volumetric IoU, watertight/0-non-manifold checks, and 16-layer planar sliceability).
98
+
99
+ <p align="center">
100
+ <img src="assets/readme_benchmarks.png" alt="12-Model Benchmark Results: Forma vs Stock Blender 5.3" width="100%" />
101
+ </p>
102
+
103
+ ### 1. Cross-Lab Results — 12 Models Across 10 Labs (`low` reasoning)
104
+
105
+ | Model | `bpy` Pass (P@1 / P@3) | **Forma Pass (P@1 / P@3)** | `bpy` Tokens (API / Comp) | **Forma Tokens (API / Comp)** | `bpy` Mean IoU | **Forma Mean IoU** | Comp Token Reduction |
106
+ |---|---:|---:|---:|---:|---:|---:|---:|
107
+ | `anthropic/claude-opus-5.5` | 4/6 · 6/6 | **6/6 · 6/6** | 15,139 / 9,333 | **6,140 / 731** | 0.973 | **0.980** | **12.77×** |
108
+ | `anthropic/claude-haiku-5.5` | 4/6 · 5/6 | **3/6 · 6/6**\* | 36,296 / 25,815 | **18,159 / 8,474** | 0.807 | **0.978** | **3.05×** |
109
+ | `google/gemini-4-neon` | 4/6 · 6/6 | **5/6 · 6/6** | 28,447 / 20,867 | **12,938 / 7,388** | 0.970 | **0.974** | **2.82×** |
110
+ | `google/gemini-4-hydrogen` | 3/6 · 5/6 | **5/6 · 6/6** | 27,794 / 18,297 | **10,157 / 5,020** | 0.818 | **0.989** | **3.64×** |
111
+ | `openai/gpt-6.2-astra` | 4/6 · 6/6 | **4/6 · 6/6** | 9,914 / 5,787 | **6,798 / 950** | 0.970 | **0.978** | **6.09×** |
112
+ | `openai/gpt-6.2-sol` | 4/6 · 6/6 | **4/6 · 6/6** | 10,333 / 6,239 | **7,126 / 1,243** | 0.968 | **0.972** | **5.02×** |
113
+ | `qwen/qwen4-max` | 2/6 · 4/6 | **4/6 · 6/6** | 43,265 / 36,827 | **19,161 / 12,133** | 0.651 | **0.965** | **3.04×** |
114
+ | `z-ai/glm-5.4` | 5/6 · 6/6 | **3/6 · 6/6** | 9,380 / 6,151 | **11,632 / 2,696** | 0.960 | **0.985** | **2.28×** |
115
+ | `x-ai/grok-4.7` | 5/6 · 6/6 | **4/6 · 6/6** | 88,001 / 76,397 | **30,024 / 14,558** | 0.966 | **0.972** | **5.25×** |
116
+ | `deepseek/deepseek-v4.1-flash` | 1/6 · 1/6 | **3/6 · 4/6** | 61,812 / 56,599 | **37,825 / 29,120** | 0.167 | **0.661** | **1.94×** |
117
+ | `tencent/hy4-flash` (`none`) | 1/6 · 1/6 | **3/6 · 5/6** | 52,799 / 22,079 | **10,497 / 1,574** | 0.159 | **0.924** | **14.03×** |
118
+ | `mistralai/mistral-large-4-0`† | 0/1 · 1/1 | **1/1 · 1/1** | 12,666 / 10,270 | **1,331 / 664** | 1.000 | **1.000** | **15.47×** |
119
+ | **Aggregate (67 paired trials)** | **55.2% · 79.1%** | **67.2% · 95.5%** | **395,846 / 294,661** | **171,788 / 84,551** | **0.768** | **0.944** | **3.49×** |
120
+
121
+ *\*On subsequent v0.2+ ring-preserving bevel fixes, `claude-haiku-5.5` improved to **6/6 (100%) Pass@1** (10,920 API tokens) and all 4 re-tested models hit **24/24 (100%) Pass@2** (`0.980` Mean IoU).*
122
+ *†Completed 1 paired task (`flange_plate`: 1-shot Forma vs 3-turn `bpy`) before upstream provider returned HTTP 400.*
123
+
124
+ ### 2. Reasoning-Effort Scaling (`claude-haiku-5.5`, `gpt-6.2-sol`, `gemini-4-hydrogen`, `qwen4-max`)
125
+
126
+ | Reasoning Level | Paired Tasks | `bpy` Pass@3 | **Forma Pass@3** | `bpy` API / Cost | **Forma API / Cost** | `bpy` IoU | **Forma IoU** | Cost Reduction |
127
+ |---|---:|---:|---:|---:|---:|---:|---:|---:|
128
+ | **`none`** | 12 | 83.3% | **91.7%** | 53,812 / \$0.100 | **22,453 / \$0.012** | 0.792 | **0.925** | **8.57×** |
129
+ | **`low`** | 24 | 83.3% | **100.0%** | 117,688 / \$0.402 | **54,603 / \$0.132** | 0.811 | **0.976** | **3.05×** |
130
+ | **`medium`** | 24 | 83.3% | **100.0%** | 178,275 / \$0.693 | **56,488 / \$0.202** | 0.834 | **0.975** | **3.44×** |
131
+ | **`high`** | 24 | 83.3% | **95.8%** | 269,423 / \$1.285 | **80,107 / \$0.326** | 0.864 | **0.941** | **3.95×** |
132
+
133
+ ### 3. Full 12-Task Suite Summary (4 Model Families, 144 Trials)
134
+
135
+ | Metric | Stock Blender 5.3 (`bpy`) | **Forma (`Forma-Pipe`)** | Gain |
136
+ |---|---:|---:|---:|
137
+ | **Pass@1 / Pass@3** | 68.8% / 85.4% | **81.2% / 97.9%** | **+12.5 pp** |
138
+ | **Median Code Tokens (`o200k`)** | 644 | **115** | **5.60× shorter** |
139
+ | **Mean Volumetric IoU** | 0.8421 | **0.9814** | **+0.1393** |
140
+ | **All 12 Canonical Meshes (build + `.glb`)** | ~15,600 ms | **61.2 ms total (`5.1 ms/mesh`)** | **12/12 `WT=ok NM=0`** |
141
+ | **Fuzz & Determinism** | — | **11,000 ops in `2.46 s` (`0.22 ms/op`)** | **0 panics · 0 NaNs · byte-identical `.glb`** |
142
+
143
+ Full logs and methodology: [`docs/EXTENDED_BENCHMARK_REPORT.md`](docs/EXTENDED_BENCHMARK_REPORT.md) · [`docs/VERIFICATION_REPORT.md`](docs/VERIFICATION_REPORT.md).
144
+
145
+ ---
146
+
147
+ ## License
148
+
149
+ MIT License — see [`LICENSE`](LICENSE).
package/SKILL.md ADDED
@@ -0,0 +1,138 @@
1
+ ---
2
+ name: forma
3
+ description: Create, modify, inspect, render, and export watertight 3D B-rep models in milliseconds using Forma (a 1.2 MB pure-Rust rewrite of headless Blender). Use whenever a task involves 3D CAD/mesh generation, mechanical parts, enclosures, brackets, threads, lofts, pipes, booleans, .glb/.step/.3mf/.stl/.obj/.blend export, 4-view .png studio previews, or dimensioned .svg engineering blueprints.
4
+ ---
5
+
6
+ # Forma — Headless 3D Modeling Skill
7
+
8
+ Forma is a 1.2 MB pure-Rust rewrite of headless Blender built for AI agents. It evaluates a compact declarative pipe language (`Forma-Pipe`) into guaranteed-manifold B-rep geometry in ~5–17 ms with zero GPU required.
9
+
10
+ ## 1. Choose Your Interface
11
+
12
+ ### Option A — MCP Server (preferred for iterative modeling)
13
+ Connect `forma-mcp` (native binary) or `npx -y forma-3d-mcp` (zero-install WASM via npm):
14
+ ```json
15
+ {
16
+ "mcpServers": {
17
+ "forma": {
18
+ "command": "npx",
19
+ "args": ["-y", "forma-3d-mcp"]
20
+ }
21
+ }
22
+ }
23
+ ```
24
+ Exposed tools (4 tools, 789 `o200k` tokens total):
25
+ - `eval` — Run transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result) and return a ~100-token spatial diff (`WT`, `NM`, `g`, `vol`, `bbox`, `size`, tags).
26
+ - `inspect` — Read current scene invariants and bounding boxes without mutating state.
27
+ - `tx` — Instant copy-on-write state control: `checkpoint`, `rollback`, `undo`, `reset`.
28
+ - `export` — Export to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, `.png` (4-view studio), or `.blend` (via optional Blender bridge).
29
+
30
+ ### Option B — CLI (single-shot Unix pipes)
31
+ Use either the compiled native binary (`forma`) or the cross-platform npm CLI (`npx -y forma-3d`):
32
+ ```bash
33
+ forma spec # Print ~355-token language reference
34
+ forma spec --gbnf # Print GBNF grammar for constrained decoding
35
+ forma eval --strict \
36
+ --out part.glb \
37
+ --render preview.png \
38
+ --draw blueprint.svg <<'EOF'
39
+ ...Forma-Pipe script...
40
+ EOF
41
+ ```
42
+
43
+ ---
44
+
45
+ ## 2. Standard 5-Step Modeling Workflow
46
+
47
+ 1. **Plan coordinates (Z-up, meters).** Primitives are centered at `(0, 0, 0)` unless placed with `at=(x,y,z)` or `z0=Z` (sets bottom Z; if both `at=` and `z0=` are given, `z0=` overrides the Z coordinate after `at=` positions X/Y).
48
+ 2. **Checkpoint before risky ops (MCP).** Call `tx(action="checkpoint", tag="base")` before complex cuts/bevels so you can roll back in O(1).
49
+ 3. **Write declarative `Forma-Pipe`.** Chain operations with `|`. Intermediate named parts still appear in the spatial diff (`parts=N`), while the **last assigned variable** is exported by default (or pass `part` in MCP `export` to pick a specific part).
50
+ 4. **Always evaluate with `--strict` / `strict: true`.** Verify the returned spatial diff reports `WT=ok` and `NM=0`, plus exact `bbox` / `size` / `section` / `clearance`.
51
+ 5. **Visually inspect & export.** Render a 4-view `.png` (`--render preview.png`) to confirm proportions visually, then export `.glb` (PBR + triplanar UVs), `.step`, `.3mf`, `.stl`, `.obj`, `.blend` (native CLI with Blender installed), or `.svg` blueprint (`--draw blueprint.svg`).
52
+
53
+ ---
54
+
55
+ ## 3. Forma-Pipe Language Reference
56
+
57
+ - **Syntax:** `name = expr | op | op` (multi-line `|` supported; math `+ - * / sqrt sin cos asin acos abs pi`).
58
+ - **Common primitive kwargs:** `at=(x,y,z)` or `at=[(x,y,z), ...]` (batch), `z0=Z`, `rot=(rx,ry,rz)`.
59
+
60
+ ### Primitives
61
+ | Primitive | Notes |
62
+ |---|---|
63
+ | `box(sx, sy, sz, at=, z0=)` | Axis-aligned box |
64
+ | `cyl(r, h, segs=32, axis=x\|y\|z, at=, z0=)` | Cylinder (`axis=x`, `y`, or `z` unquoted, default `z`; `segs=6` gives hex vertices at `k*60°`) |
65
+ | `cone(r0, r1, h)` | Frustum / cone |
66
+ | `sphere(r)` | UV sphere |
67
+ | `torus(R, r)` | Major radius `R`, tube radius `r` |
68
+ | `pipe(ro, ri, h)` | Hollow cylindrical tube |
69
+ | `extrude2d([(x,y), ...], z0, z1)` | Extrude closed 2D polygon |
70
+ | `revolve([(r,z), ...], segs=32)` | Lathe profile around Z (auto-closes at `r=0`) |
71
+ | `loft([(z, [(x,y), ...]), ...])` | Multi-section smooth loft |
72
+ | `thread(r0, r1, pitch, turns)` | Watertight helical screw thread |
73
+ | `arc_tube(center=(x,y,z), rx=, rz=, start=-90, end=90, r=0.08)` | Curved handle / arc sweep |
74
+ | `tube([(x,y,z), ...], r=0.08)` | Polyline pipe sweep |
75
+ | `text3d("TEXT", height=0.3, depth=0.08)` | Watertight 3D extruded vector text |
76
+
77
+ ### Operations & Selectors
78
+ - **Booleans:** `add(b, at=)`, `cut(b, at=)`, `intersect(b)` — `at=[...]` runs fast batch CSG.
79
+ - **Features:**
80
+ - `bevel(edges, w, segs=1)` — semantic selectors: `vertical`, `top_rim`, `bottom_rim`, `outer_rim`, `sharp`, `all` (never guess integer edge indices).
81
+ - `shell(t, open_top=true)` — hollow solid with wall thickness `t`.
82
+ - `subsurf(levels=1, crease=false)` — Catmull-Clark subdivision (`crease=true` preserves sharp rims).
83
+ - `extrude(faces, d)` | `inset(faces, amt, depth=0)` — face selectors: `top`, `bottom`, `sides`, `all`.
84
+ - `mirror(x|y|z)` | `pattern_linear(n, step=(dx,dy,dz))` | `pattern_radial(n, r=)`
85
+ - **Transforms & Relational Placement:**
86
+ - `move(x, y, z)` | `rot(rx, ry, rz)` (degrees) | `scale(sx, sy, sz)`
87
+ - `on(base)` (rests cleanly on top of `base`) | `align(x|y|z, min|center|max, val)` | `align_z0(z)`
88
+ - **Materials & Spatial Queries:**
89
+ - `mat("name", color=(r,g,b), metallic=0.1, roughness=0.5)` | `color(r,g,b)`
90
+ - `section(part, z)` — returns 2D cross-section loop count & area at plane `Z`.
91
+ - `clearance(a, b)` — returns exact minimum 3D distance between parts `a` and `b`.
92
+
93
+ ---
94
+
95
+ ## 4. Verified Recipes
96
+
97
+ ### Brushed-Steel 5-Hole Mounting Flange
98
+ ```forma
99
+ flange = box(4, 2, 0.4)
100
+ | mat("brushed_steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)
101
+ | cut(cyl(0.5, 1.0))
102
+ | cut(cyl(0.25, 1.0), at=[(-1.4,-0.5,0), (-1.4,0.5,0), (1.4,-0.5,0), (1.4,0.5,0)])
103
+ section(flange, 0.0)
104
+ ```
105
+
106
+ ### Beveled Hollow Enclosure
107
+ ```forma
108
+ enclosure = box(3.0, 2.0, 1.0, z0=0)
109
+ | bevel(vertical, 0.2, segs=3)
110
+ | shell(0.15, open_top=true)
111
+ | mat("anodized_teal", color=(0.18, 0.56, 0.60), metallic=0.7, roughness=0.35)
112
+ ```
113
+
114
+ ### Helical Threaded Hex Bolt
115
+ ```forma
116
+ head = cyl(0.7, 0.4, segs=6, z0=0)
117
+ shank = thread(0.32, 0.42, 0.16, 6) | align_z0(0.38)
118
+ bolt = head | add(shank)
119
+ | mat("titanium", color=(0.74, 0.78, 0.84), metallic=0.92, roughness=0.22)
120
+ ```
121
+
122
+ ### Ceramic Mug (Shell + Arc Handle)
123
+ ```forma
124
+ body = cyl(0.5, 1.0, segs=32, z0=0) | shell(0.08, open_top=true)
125
+ handle = arc_tube(center=(0.48, 0, 0.5), rx=0.26, rz=0.28, start=-85, end=85, r=0.065)
126
+ mug = body | add(handle)
127
+ | mat("terracotta", color=(0.72, 0.36, 0.24), metallic=0.0, roughness=0.72)
128
+ ```
129
+
130
+ ---
131
+
132
+ ## 5. Troubleshooting & Best Practices
133
+
134
+ - **Through-cuts:** Always make cutting cylinders/boxes taller than the target solid (e.g., cut a `0.4`-thick plate with a `1.0`-tall cylinder) to avoid grazing coplanar ambiguity.
135
+ - **Overlapping joins:** When joining two solids with `add()` (like a bolt head + thread or mug body + handle), overlap them slightly (`0.02` units) rather than kissing at an exact zero-thickness plane.
136
+ - **Bevel order:** Apply `bevel(vertical, w)` *before* `shell(t)` when hollowing an enclosure so inner and outer walls stay clean and uniform.
137
+ - **Batch multi-hole cuts:** Pass a coordinate list `cut(cyl(r, h), at=[(x1,y1,0), ...])` instead of chaining separate `cut()` calls — it is faster and produces cleaner topology.
138
+ - **Strict verification:** Never deliver a mesh that fails `--strict` (`WT=ok NM=0`). If a boolean fails, adjust cutter clearance/overlap or roll back with `tx(action="undo")`.
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * forma-3d-mcp — Thin, minimal-schema stdio JSON-RPC 2.0 MCP server (4 tools, 789 o200k tokens).
4
+ * Powered by Forma's bundled pure-Rust WebAssembly engine (zero external dependencies).
5
+ */
6
+
7
+ import { createInterface } from "node:readline";
8
+ import { writeFile } from "node:fs/promises";
9
+ import { extname } from "node:path";
10
+ import { performance } from "node:perf_hooks";
11
+ import { loadForma } from "../lib/index.mjs";
12
+
13
+ const VERSION = "0.4.0";
14
+
15
+ function buildToolsSchema(specPipe) {
16
+ return [
17
+ {
18
+ name: "eval",
19
+ description: `Run transactional Forma-Pipe code (auto-rollback on error); returns compact bbox/vol/manifold diff.\n${specPipe}`,
20
+ inputSchema: {
21
+ type: "object",
22
+ properties: {
23
+ code: { type: "string" },
24
+ strict: { type: "boolean" },
25
+ },
26
+ required: ["code"],
27
+ },
28
+ },
29
+ {
30
+ name: "inspect",
31
+ description: "Compact bbox, volume, manifold invariants, and semantic face tags.",
32
+ inputSchema: { type: "object", properties: {} },
33
+ },
34
+ {
35
+ name: "tx",
36
+ description: "CoW snapshot control: checkpoint|rollback|undo|reset.",
37
+ inputSchema: {
38
+ type: "object",
39
+ properties: {
40
+ action: { type: "string", enum: ["checkpoint", "rollback", "undo", "reset"] },
41
+ tag: { type: "string" },
42
+ },
43
+ required: ["action"],
44
+ },
45
+ },
46
+ {
47
+ name: "export",
48
+ description: "Export to .glb/.step/.3mf/.stl/.obj/.svg or 2x2 studio preview .png.",
49
+ inputSchema: {
50
+ type: "object",
51
+ properties: {
52
+ path: { type: "string" },
53
+ part: { type: "string" },
54
+ size: { type: "integer" },
55
+ },
56
+ required: ["path"],
57
+ },
58
+ },
59
+ ];
60
+ }
61
+
62
+ async function handleToolCall(session, name, args) {
63
+ try {
64
+ if (name === "eval") {
65
+ if (typeof args?.code !== "string") {
66
+ return [true, "ERR: missing 'code' string"];
67
+ }
68
+ const t0 = performance.now();
69
+ const obs = session.eval(args.code, { strict: Boolean(args.strict) });
70
+ const ms = performance.now() - t0;
71
+ const text = obs.text.replace("[0.00ms]", `[${ms.toFixed(2)}ms]`);
72
+ return [false, text];
73
+ }
74
+ if (name === "inspect") {
75
+ const obs = session.inspect();
76
+ return [false, obs.text];
77
+ }
78
+ if (name === "tx") {
79
+ const action = typeof args?.action === "string" ? args.action : "";
80
+ const tag = typeof args?.tag === "string" ? args.tag : "default";
81
+ const msg = session.tx(action, tag);
82
+ return [false, msg];
83
+ }
84
+ if (name === "export") {
85
+ if (typeof args?.path !== "string") {
86
+ return [true, "ERR: missing 'path'"];
87
+ }
88
+ const p = args.path;
89
+ const part = typeof args.part === "string" ? args.part : "";
90
+ const ext = extname(p).replace(/^\./, "").toLowerCase();
91
+ const size = Number.isInteger(args.size) ? args.size : 512;
92
+ const t0 = performance.now();
93
+ const bytes = session.exportBytes(ext, { part, size });
94
+ await writeFile(p, bytes);
95
+ const ms = performance.now() - t0;
96
+ if (ext === "png") {
97
+ return [false, `OK rendered ${size}x${size} quad preview '${p}' [${ms.toFixed(2)}ms]`];
98
+ }
99
+ if (ext === "svg") {
100
+ return [false, `OK drew engineering blueprint '${p}' [${ms.toFixed(2)}ms]`];
101
+ }
102
+ const inv = session.invariants(part);
103
+ return [
104
+ false,
105
+ `OK exported '${p}' V=${inv.verts} F=${inv.faces} WT=${inv.watertight} NM=${inv.non_manifold_edges} vol=${Number(inv.volume).toFixed(3)}`,
106
+ ];
107
+ }
108
+ return [true, `ERR: unknown tool '${name}'`];
109
+ } catch (err) {
110
+ return [true, `ERR: ${err instanceof Error ? err.message : String(err)}`];
111
+ }
112
+ }
113
+
114
+ async function runServer() {
115
+ const engine = await loadForma();
116
+ const specPipe = engine.spec({ dialect: "pipe", gbnf: false });
117
+ const tools = buildToolsSchema(specPipe);
118
+ const session = engine.createSession();
119
+
120
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
121
+ const send = (obj) => process.stdout.write(JSON.stringify(obj) + "\n");
122
+
123
+ for await (const line of rl) {
124
+ const trimmed = line.trim();
125
+ if (!trimmed) continue;
126
+
127
+ let req;
128
+ try {
129
+ req = JSON.parse(trimmed);
130
+ } catch (err) {
131
+ send({
132
+ jsonrpc: "2.0",
133
+ id: null,
134
+ error: { code: -32700, message: `parse error: ${err.message}` },
135
+ });
136
+ continue;
137
+ }
138
+
139
+ if (req.id === undefined) continue;
140
+ const { id, method } = req;
141
+
142
+ if (method === "initialize") {
143
+ send({
144
+ jsonrpc: "2.0",
145
+ id,
146
+ result: {
147
+ protocolVersion: "2024-11-05",
148
+ capabilities: { tools: {} },
149
+ serverInfo: { name: "forma-mcp", version: VERSION },
150
+ },
151
+ });
152
+ } else if (method === "ping") {
153
+ send({ jsonrpc: "2.0", id, result: {} });
154
+ } else if (method === "tools/list") {
155
+ send({ jsonrpc: "2.0", id, result: { tools } });
156
+ } else if (method === "tools/call") {
157
+ const name = req.params?.name ?? "";
158
+ const args = req.params?.arguments ?? {};
159
+ const [isError, text] = await handleToolCall(session, name, args);
160
+ send({
161
+ jsonrpc: "2.0",
162
+ id,
163
+ result: {
164
+ content: [{ type: "text", text }],
165
+ isError,
166
+ },
167
+ });
168
+ } else {
169
+ send({
170
+ jsonrpc: "2.0",
171
+ id,
172
+ error: { code: -32601, message: `method not found: ${method}` },
173
+ });
174
+ }
175
+ }
176
+ session.free();
177
+ }
178
+
179
+ runServer().catch((err) => {
180
+ process.stderr.write(`ERR: ${err instanceof Error ? err.message : String(err)}\n`);
181
+ process.exit(1);
182
+ });
package/bin/forma.mjs ADDED
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * forma-3d CLI — cross-platform pure-WASM headless 3D B-rep modeling engine.
4
+ * Supports: eval, render, draw, spec, mcp, version, --help
5
+ */
6
+
7
+ import { readFile, writeFile } from "node:fs/promises";
8
+ import { extname } from "node:path";
9
+ import { performance } from "node:perf_hooks";
10
+ import { loadForma } from "../lib/index.mjs";
11
+
12
+ const VERSION = "0.4.0";
13
+
14
+ function printHelp() {
15
+ process.stdout.write(
16
+ `forma ${VERSION} (WASM) — 1.2 MB pure-Rust rewrite of headless Blender for AI agents\n\n` +
17
+ `USAGE:\n` +
18
+ ` forma-3d eval [--dialect pipe|compact] [--strict] [--json] [--out path.(glb|obj|stl|3mf|step)] [--render preview.png] [--draw blueprint.svg] [file|-]\n` +
19
+ ` forma-3d render [--size 512] --out preview.png [file|-]\n` +
20
+ ` forma-3d draw --out blueprint.svg [file|-]\n` +
21
+ ` forma-3d spec [--dialect pipe|compact] [--gbnf]\n` +
22
+ ` forma-3d mcp\n` +
23
+ ` forma-3d --version\n`
24
+ );
25
+ }
26
+
27
+ async function readStdin() {
28
+ const chunks = [];
29
+ for await (const chunk of process.stdin) {
30
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
31
+ }
32
+ return Buffer.concat(chunks).toString("utf-8");
33
+ }
34
+
35
+ async function main() {
36
+ const args = process.argv.slice(2);
37
+ if (args.length === 0 || args[0] === "-h" || args[0] === "--help" || args[0] === "help") {
38
+ printHelp();
39
+ return;
40
+ }
41
+
42
+ const cmd = args[0];
43
+ if (cmd === "version" || cmd === "--version" || cmd === "-V") {
44
+ process.stdout.write(`forma ${VERSION}\n`);
45
+ return;
46
+ }
47
+
48
+ if (cmd === "mcp") {
49
+ await import("./forma-mcp.mjs");
50
+ return;
51
+ }
52
+
53
+ const engine = await loadForma();
54
+
55
+ if (cmd === "spec") {
56
+ let dialect = "pipe";
57
+ let gbnf = false;
58
+ for (let i = 1; i < args.length; i++) {
59
+ if ((args[i] === "--dialect" || args[i] === "-d") && i + 1 < args.length) {
60
+ dialect = args[++i];
61
+ } else if (args[i] === "--gbnf") {
62
+ gbnf = true;
63
+ }
64
+ }
65
+ process.stdout.write(engine.spec({ dialect, gbnf }) + "\n");
66
+ return;
67
+ }
68
+
69
+ if (cmd !== "eval" && cmd !== "render" && cmd !== "draw") {
70
+ process.stderr.write(`ERR: unknown subcommand '${cmd}'. Run 'forma-3d --help'.\n`);
71
+ process.exit(2);
72
+ }
73
+
74
+ let dialect = "pipe";
75
+ let strict = false;
76
+ let asJson = false;
77
+ let outPath = null;
78
+ let renderPath = null;
79
+ let drawPath = null;
80
+ let renderSize = 512;
81
+ let inFile = null;
82
+
83
+ for (let i = 1; i < args.length; i++) {
84
+ const a = args[i];
85
+ if (a === "--dialect" || a === "-d") {
86
+ dialect = args[++i];
87
+ } else if (a === "--out" || a === "-o") {
88
+ const p = args[++i];
89
+ if (cmd === "render") renderPath = p;
90
+ else if (cmd === "draw") drawPath = p;
91
+ else outPath = p;
92
+ } else if (a === "--render") {
93
+ renderPath = args[++i];
94
+ } else if (a === "--draw") {
95
+ drawPath = args[++i];
96
+ } else if (a === "--size") {
97
+ renderSize = Number.parseInt(args[++i], 10) || 512;
98
+ } else if (a === "--strict") {
99
+ strict = true;
100
+ } else if (a === "--json") {
101
+ asJson = true;
102
+ } else {
103
+ inFile = a;
104
+ }
105
+ }
106
+
107
+ const src = !inFile || inFile === "-" ? await readStdin() : await readFile(inFile, "utf-8");
108
+ const session = engine.createSession();
109
+ const t0 = performance.now();
110
+ try {
111
+ const obs = session.eval(src, { dialect, strict });
112
+ const ms = performance.now() - t0;
113
+ obs.elapsed_ms = Number(ms.toFixed(2));
114
+ obs.text = obs.text.replace("[0.00ms]", `[${ms.toFixed(2)}ms]`);
115
+
116
+ if (outPath) {
117
+ const ext = extname(outPath).replace(/^\./, "").toLowerCase();
118
+ const bytes = session.exportBytes(ext);
119
+ await writeFile(outPath, bytes);
120
+ }
121
+ if (renderPath) {
122
+ const bytes = session.exportBytes("png", { size: renderSize });
123
+ await writeFile(renderPath, bytes);
124
+ }
125
+ if (drawPath) {
126
+ const bytes = session.exportBytes("svg");
127
+ await writeFile(drawPath, bytes);
128
+ }
129
+
130
+ if (asJson) {
131
+ process.stdout.write(JSON.stringify(obs) + "\n");
132
+ } else {
133
+ process.stdout.write(obs.text + "\n");
134
+ }
135
+ if (strict && !obs.ok) {
136
+ process.exit(3);
137
+ }
138
+ } catch (err) {
139
+ const msg = err instanceof Error ? err.message : String(err);
140
+ if (asJson) {
141
+ process.stdout.write(JSON.stringify({ ok: false, error: msg }) + "\n");
142
+ } else {
143
+ process.stderr.write(`ERR: ${msg}\n`);
144
+ }
145
+ process.exit(1);
146
+ } finally {
147
+ session.free();
148
+ }
149
+ }
150
+
151
+ main().catch((err) => {
152
+ process.stderr.write(`ERR: ${err instanceof Error ? err.message : String(err)}\n`);
153
+ process.exit(1);
154
+ });
@@ -0,0 +1,61 @@
1
+ # Formal GBNF (llama.cpp / XGrammar / vLLM) Constrained-Decoding Grammar for Forma-Pipe
2
+ # Guarantees 0% syntax errors under grammar-constrained LLM generation.
3
+
4
+ root ::= ws (stmt (nl stmt)*)? ws
5
+ stmt ::= ident ws "=" ws expr | expr
6
+ expr ::= add-expr (ws "|" ws pipe-call)*
7
+ pipe-call ::= pipe-op "(" ws arg-list? ws ")"
8
+
9
+ add-expr ::= mul-expr (ws ("+" | "-") ws mul-expr)*
10
+ mul-expr ::= unary-expr (ws ("*" | "/") ws unary-expr)*
11
+ unary-expr ::= ("+" | "-") ws unary-expr | atom
12
+
13
+ atom ::= call
14
+ | tuple-or-paren
15
+ | list-lit
16
+ | number
17
+ | string
18
+ | selector-kw
19
+ | bool-lit
20
+ | ident
21
+
22
+ call ::= func-name "(" ws arg-list? ws ")"
23
+ arg-list ::= arg (ws "," ws arg)* (ws ",")?
24
+ arg ::= (kw-name ws "=" ws)? expr
25
+
26
+ tuple-or-paren ::= "(" ws (expr (ws "," ws expr)* (ws ",")?)? ws ")"
27
+ list-lit ::= "[" ws (expr (ws "," ws expr)* (ws ",")?)? ws "]"
28
+
29
+ func-name ::= "box" | "cyl" | "cylinder" | "prism" | "pipe" | "hollow_cyl"
30
+ | "cone" | "frustum" | "sphere" | "torus" | "revolve"
31
+ | "arc_tube" | "tube" | "extrude2d" | "loft" | "thread" | "helix"
32
+ | "sweep" | "text3d" | "text"
33
+ | "clearance" | "section" | "checkpoint" | "rollback" | "undo" | "del"
34
+ | "sqrt" | "sin" | "cos" | "asin" | "acos" | "abs" | "deg" | "rad"
35
+ | pipe-op
36
+
37
+ pipe-op ::= "add" | "union" | "cut" | "sub" | "diff" | "intersect"
38
+ | "bevel" | "shell" | "extrude" | "inset" | "subsurf" | "subdiv"
39
+ | "move" | "translate" | "rot" | "rotate" | "scale"
40
+ | "align_z0" | "align" | "on" | "place_on" | "mirror"
41
+ | "pattern_linear" | "pattern_radial" | "array" | "radial"
42
+ | "mat" | "material" | "color"
43
+
44
+ selector-kw ::= "vertical" | "horizontal" | "top_rim" | "bottom_rim" | "outer_rim"
45
+ | "rim" | "sharp" | "boundary" | "all"
46
+ | "top" | "bottom" | "front" | "back" | "left" | "right" | "sides" | "side"
47
+ | "min" | "center" | "mid" | "max" | "x" | "y" | "z" | "pi"
48
+
49
+ kw-name ::= "sx" | "sy" | "sz" | "r" | "h" | "r0" | "r1" | "R" | "segs" | "segments"
50
+ | "axis" | "at" | "center" | "z0" | "z1" | "rot" | "rx" | "rz"
51
+ | "start" | "end" | "start_deg" | "end_deg" | "profile" | "points" | "closed"
52
+ | "edges" | "faces" | "w" | "width" | "t" | "thickness" | "open_top"
53
+ | "dist" | "amt" | "depth" | "levels" | "union" | "mode" | "val" | "gap"
54
+ | "name" | "color" | "metallic" | "roughness" | "tag" | "other" | "base"
55
+
56
+ bool-lit ::= "true" | "false"
57
+ ident ::= [a-zA-Z_] [a-zA-Z0-9_]*
58
+ number ::= "-"? ([0-9]+ ("." [0-9]+)? | "." [0-9]+) ([eE] [+-]? [0-9]+)?
59
+ string ::= "\"" [^"\\\n]* "\"" | "'" [^'\\\n]* "'"
60
+ nl ::= ([ \t]* ("#" [^\n]*)? ("\r"? "\n" | ";"))+ [ \t]*
61
+ ws ::= [ \t]*
package/lib/index.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ export interface FormaObservation {
2
+ ok: boolean;
3
+ elapsed_ms: number;
4
+ text: string;
5
+ parts: Record<string, unknown>;
6
+ }
7
+
8
+ export interface FormaInvariants {
9
+ verts: number;
10
+ faces: number;
11
+ watertight: boolean;
12
+ non_manifold_edges: number;
13
+ boundary_edges: number;
14
+ genus: number;
15
+ volume: number;
16
+ }
17
+
18
+ export interface EvalOptions {
19
+ dialect?: "pipe" | "compact";
20
+ strict?: boolean;
21
+ }
22
+
23
+ export interface ExportOptions extends EvalOptions {
24
+ part?: string;
25
+ size?: number;
26
+ }
27
+
28
+ export interface SpecOptions {
29
+ dialect?: "pipe" | "compact";
30
+ gbnf?: boolean;
31
+ }
32
+
33
+ export class FormaSession {
34
+ eval(code: string, opts?: EvalOptions): FormaObservation;
35
+ inspect(): FormaObservation;
36
+ tx(action: "checkpoint" | "rollback" | "undo" | "reset", tag?: string): string;
37
+ exportBytes(
38
+ format: "glb" | "step" | "stp" | "3mf" | "stl" | "obj" | "svg" | "png",
39
+ opts?: { part?: string; size?: number }
40
+ ): Uint8Array;
41
+ invariants(part?: string): FormaInvariants;
42
+ free(): void;
43
+ }
44
+
45
+ export interface FormaEngine {
46
+ spec(opts?: SpecOptions): string;
47
+ createSession(): FormaSession;
48
+ }
49
+
50
+ export function loadForma(wasmSource?: string | URL | Uint8Array | ArrayBuffer): Promise<FormaEngine>;
51
+ export function evalPipe(code: string, opts?: EvalOptions): Promise<FormaObservation>;
52
+ export function exportMesh(
53
+ code: string,
54
+ format?: "glb" | "step" | "stp" | "3mf" | "stl" | "obj" | "svg" | "png",
55
+ opts?: ExportOptions
56
+ ): Promise<Uint8Array>;
57
+ export function renderPng(code: string, size?: number, opts?: EvalOptions): Promise<Uint8Array>;
58
+ export function drawSvg(code: string, opts?: EvalOptions): Promise<string>;
59
+ export function getSpec(opts?: SpecOptions): Promise<string>;
package/lib/index.mjs ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * forma-3d — Zero-dependency pure-WASM JavaScript/Node.js API for Forma
3
+ * (a 1.2 MB pure-Rust rewrite of headless Blender built for AI agents).
4
+ */
5
+
6
+ import { readFile } from "node:fs/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import { dirname, join } from "node:path";
9
+
10
+ const __dirname = dirname(fileURLToPath(import.meta.url));
11
+ const DEFAULT_WASM_PATH = join(__dirname, "..", "wasm", "forma.wasm");
12
+
13
+ const encoder = new TextEncoder();
14
+ const decoder = new TextDecoder("utf-8");
15
+
16
+ let cachedEnginePromise = null;
17
+
18
+ class FormaEngine {
19
+ constructor(instance) {
20
+ this.exports = instance.exports;
21
+ this.memory = instance.exports.memory;
22
+ }
23
+
24
+ _withUtf8(str, fn) {
25
+ const bytes = encoder.encode(str ?? "");
26
+ const ptr = this.exports.forma_alloc(bytes.length);
27
+ try {
28
+ if (bytes.length > 0) {
29
+ new Uint8Array(this.memory.buffer, ptr, bytes.length).set(bytes);
30
+ }
31
+ return fn(ptr, bytes.length);
32
+ } finally {
33
+ this.exports.forma_dealloc(ptr, bytes.length);
34
+ }
35
+ }
36
+
37
+ _readResultBytes() {
38
+ const ptr = this.exports.forma_result_ptr();
39
+ const len = this.exports.forma_result_len();
40
+ const isErr = this.exports.forma_result_is_err() !== 0;
41
+ const copy = new Uint8Array(this.memory.buffer, ptr, len).slice();
42
+ if (isErr) {
43
+ throw new Error(decoder.decode(copy));
44
+ }
45
+ return copy;
46
+ }
47
+
48
+ _readResultString() {
49
+ return decoder.decode(this._readResultBytes());
50
+ }
51
+
52
+ /** Return the compact language reference (~355 tokens) or formal GBNF grammar. */
53
+ spec({ dialect = "pipe", gbnf = false } = {}) {
54
+ const d = dialect === "compact" ? 1 : 0;
55
+ this.exports.forma_spec(d, gbnf ? 1 : 0);
56
+ return this._readResultString();
57
+ }
58
+
59
+ /** Create a stateful transactional 3D modeling session. */
60
+ createSession() {
61
+ const id = this.exports.forma_session_new();
62
+ return new FormaSession(this, id);
63
+ }
64
+ }
65
+
66
+ export class FormaSession {
67
+ constructor(engine, id) {
68
+ this._engine = engine;
69
+ this._id = id;
70
+ this._freed = false;
71
+ }
72
+
73
+ _checkOpen() {
74
+ if (this._freed) {
75
+ throw new Error("FormaSession has been freed");
76
+ }
77
+ }
78
+
79
+ /** Evaluate Forma-Pipe (or compact) code transactionally; returns parsed Observation. */
80
+ eval(code, { dialect = "pipe", strict = false } = {}) {
81
+ this._checkOpen();
82
+ const d = dialect === "compact" ? 1 : 0;
83
+ this._engine._withUtf8(code, (ptr, len) => {
84
+ this._engine.exports.forma_session_eval(this._id, ptr, len, d, strict ? 1 : 0);
85
+ });
86
+ return JSON.parse(this._engine._readResultString());
87
+ }
88
+
89
+ /** Inspect current scene state without mutating it. */
90
+ inspect() {
91
+ this._checkOpen();
92
+ this._engine.exports.forma_session_inspect(this._id);
93
+ return JSON.parse(this._engine._readResultString());
94
+ }
95
+
96
+ /** Copy-on-write state control: checkpoint | rollback | undo | reset. */
97
+ tx(action, tag = "default") {
98
+ this._checkOpen();
99
+ return this._engine._withUtf8(action, (ap, al) =>
100
+ this._engine._withUtf8(tag, (tp, tl) => {
101
+ this._engine.exports.forma_session_tx(this._id, ap, al, tp, tl);
102
+ return this._engine._readResultString();
103
+ })
104
+ );
105
+ }
106
+
107
+ /** Export bytes for .glb, .step, .3mf, .stl, .obj, .svg, or 4-view .png. */
108
+ exportBytes(format, { part = "", size = 512 } = {}) {
109
+ this._checkOpen();
110
+ return this._engine._withUtf8(format, (ep, el) =>
111
+ this._engine._withUtf8(part || "", (pp, pl) => {
112
+ this._engine.exports.forma_session_export(this._id, ep, el, pp, pl, size >>> 0);
113
+ return this._engine._readResultBytes();
114
+ })
115
+ );
116
+ }
117
+
118
+ /** Compute MeshInvariants JSON for the current or named part. */
119
+ invariants(part = "") {
120
+ this._checkOpen();
121
+ this._engine._withUtf8(part || "", (pp, pl) => {
122
+ this._engine.exports.forma_session_invariants(this._id, pp, pl);
123
+ });
124
+ return JSON.parse(this._engine._readResultString());
125
+ }
126
+
127
+ /** Free session memory in the WASM heap. */
128
+ free() {
129
+ if (!this._freed) {
130
+ this._freed = true;
131
+ this._engine.exports.forma_session_free(this._id);
132
+ }
133
+ }
134
+ }
135
+
136
+ /** Load and instantiate the Forma WASM engine (cached after first call). */
137
+ export async function loadForma(wasmSource = DEFAULT_WASM_PATH) {
138
+ if (wasmSource === DEFAULT_WASM_PATH && cachedEnginePromise) {
139
+ return cachedEnginePromise;
140
+ }
141
+ const loader = (async () => {
142
+ const bytes =
143
+ wasmSource instanceof Uint8Array || wasmSource instanceof ArrayBuffer
144
+ ? wasmSource
145
+ : await readFile(wasmSource);
146
+ const { instance } = await WebAssembly.instantiate(bytes, {});
147
+ return new FormaEngine(instance);
148
+ })();
149
+ if (wasmSource === DEFAULT_WASM_PATH) {
150
+ cachedEnginePromise = loader;
151
+ }
152
+ return loader;
153
+ }
154
+
155
+ /** One-shot helper: evaluate Forma-Pipe script and return Observation. */
156
+ export async function evalPipe(code, opts = {}) {
157
+ const engine = await loadForma();
158
+ const s = engine.createSession();
159
+ try {
160
+ return s.eval(code, opts);
161
+ } finally {
162
+ s.free();
163
+ }
164
+ }
165
+
166
+ /** One-shot helper: evaluate script and export binary bytes (.glb/.step/.3mf/.stl/.obj/.svg/.png). */
167
+ export async function exportMesh(code, format = "glb", opts = {}) {
168
+ const engine = await loadForma();
169
+ const s = engine.createSession();
170
+ try {
171
+ s.eval(code, opts);
172
+ return s.exportBytes(format, opts);
173
+ } finally {
174
+ s.free();
175
+ }
176
+ }
177
+
178
+ /** One-shot helper: evaluate script and render a 4-view studio PNG (Uint8Array). */
179
+ export async function renderPng(code, size = 512, opts = {}) {
180
+ return exportMesh(code, "png", { ...opts, size });
181
+ }
182
+
183
+ /** One-shot helper: evaluate script and render a 1200x900 engineering SVG blueprint string. */
184
+ export async function drawSvg(code, opts = {}) {
185
+ const bytes = await exportMesh(code, "svg", opts);
186
+ return decoder.decode(bytes);
187
+ }
188
+
189
+ /** Return the compact language reference or formal GBNF grammar. */
190
+ export async function getSpec(opts = {}) {
191
+ const engine = await loadForma();
192
+ return engine.spec(opts);
193
+ }
package/llms.txt ADDED
@@ -0,0 +1,68 @@
1
+ # Forma
2
+
3
+ > A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, Unix CLI, and minimal-schema MCP server. Single static binary, zero GPU required, guaranteed-manifold geometry, ~16.9 ms cold-start eval + export.
4
+
5
+ ## Repository Map
6
+
7
+ - [SKILL.md](SKILL.md): Ready-to-use Agent Skill (`name: forma`) with 5-step workflow, full syntax cheat sheet, verified recipes, and troubleshooting
8
+ - [README.md](README.md): Overview, quickstart, npm/CLI/MCP usage, and full 12-model / 10-lab benchmarks
9
+ - [AGENTS.md](AGENTS.md): Step-by-step integration guide for AI agents (MCP, CLI, constrained decoding, feedback loop)
10
+ - [grammar/forma_pipe.gbnf](grammar/forma_pipe.gbnf): Formal GBNF grammar for zero-syntax-error constrained decoding (llama.cpp, vLLM, XGrammar)
11
+ - [crates/forma-core](crates/forma-core): Pure-Rust double-precision B-rep kernel, BVH booleans, bevel, shell, subsurf, loft, thread, sweep, text3d, spatial queries, pure-Rust PNG/SVG renderer, GLB/STEP/3MF/STL/OBJ exporters
12
+ - [crates/forma-lang](crates/forma-lang): `Forma-Pipe` declarative modeling language evaluator
13
+ - [crates/forma-cli](crates/forma-cli): `forma` CLI (`eval`, `render`, `draw`, `spec`)
14
+ - [crates/forma-mcp](crates/forma-mcp): `forma-mcp` stdio JSON-RPC 2.0 MCP server (4 tools, 789 o200k tokens)
15
+ - [crates/forma-wasm](crates/forma-wasm): WebAssembly browser bindings (`wasm-pack build --target web`)
16
+ - [docs/VERIFICATION_REPORT.md](docs/VERIFICATION_REPORT.md): Independent geometric, slicer, Blender import, fuzz, and MCP verification
17
+ - [docs/EXTENDED_BENCHMARK_REPORT.md](docs/EXTENDED_BENCHMARK_REPORT.md): Full 12-model / 10-lab cross-lab & reasoning-effort scaling study
18
+
19
+ ## Quick Commands
20
+
21
+ ```bash
22
+ # Build release binaries (~1.2 MB each)
23
+ cargo build --release
24
+
25
+ # Print the concise language spec (~355 tokens) or formal GBNF grammar
26
+ ./target/release/forma spec
27
+ ./target/release/forma spec --gbnf
28
+
29
+ # Evaluate a Forma-Pipe script, verify watertightness, export .glb/.step/.3mf/.stl/.obj/.blend, render 4-view .png, draw .svg blueprint
30
+ ./target/release/forma eval --strict --out part.glb --render preview.png --draw blueprint.svg script.forma
31
+
32
+ # Run stdio MCP server (4 tools: eval, inspect, tx, export)
33
+ ./target/release/forma-mcp
34
+ ```
35
+
36
+ ## Forma-Pipe Language Reference (Z-up, meters)
37
+
38
+ - Assignment & chaining: `name = expr | op | op` (multi-line `|` supported, math `+ - * / sqrt sin cos asin acos abs pi`, last assigned part exports).
39
+ - Common placement kwargs on primitives: `at=(x,y,z)` or `at=[(x,y,z),...]`, `z0=Z` (rests bottom at Z), `rot=(rx,ry,rz)`.
40
+ - Primitives:
41
+ - `box(sx, sy, sz, at=, z0=)`
42
+ - `cyl(r, h, segs=32, axis=z, at=, z0=)` (`segs=6` places vertices at `k*60deg`)
43
+ - `cone(r0, r1, h, segs=32, axis=z)`
44
+ - `pipe(r_out, r_in, h, segs=32, axis=z)`
45
+ - `sphere(r, segs=32)` | `torus(R, r, segs=32)`
46
+ - `revolve([(r,z), ...], segs=32)` (around Z, auto-closes to `r=0`)
47
+ - `arc_tube(center=(x,y,z), rx=, rz=, start=-90, end=90, r=0.08)` (XZ elliptical arc)
48
+ - `tube([(x,y,z), ...], r=0.08, closed=false)`
49
+ - `extrude2d([(x,y), ...], z0=0, z1=1)`
50
+ - `loft([(z, [(x,y), ...]), ...], segs=24)`
51
+ - `thread(r_minor, r_major, pitch, turns, segs=28)`
52
+ - `sweep([(x,y), ...], [(x,y,z), ...], closed=false)`
53
+ - `text3d("TEXT", size=0.5, depth=0.1)`
54
+ - Pipeline Ops (`mesh | op(...)` or `op(mesh, ...)`):
55
+ - Booleans: `add(b, at=)`, `cut(b, at=)`, `intersect(b)` (batch-accelerated when `at=[...]`)
56
+ - Modeling: `bevel(edges, w, segs=1)` (`vertical|top_rim|bottom_rim|outer_rim|sharp|all`), `shell(t, open_top=true)`, `extrude(faces, d)`, `inset(faces, amt, depth=0)` (`top|bottom|sides`), `subsurf(levels=1, crease=false)`, `mirror(x|y|z)`, `pattern_linear(n, step)`, `pattern_radial(n)`
57
+ - Placement: `move(x,y,z)`, `rot(rx,ry,rz)`, `scale(sx,sy,sz)`, `align(x|y|z, min|center|max, val)`, `on(base, gap=0)`, `align_z0(z)`
58
+ - Materials: `mat(name, color=(r,g,b), metallic=0.1, roughness=0.5, faces=)`, `color(r,g,b)`
59
+ - Spatial Queries (emitted in compact observation output):
60
+ - `clearance(part_a, part_b)` — exact 3D minimum surface distance & collision check
61
+ - `section(part, z)` — exact 2D cross-section loop count, area, perimeter, XY bounds
62
+
63
+ ## MCP Tools (`forma-mcp`, 789 o200k tokens total)
64
+
65
+ 1. `eval({ code, strict? })` — Run transactional Forma-Pipe code (auto-rollback on error); returns compact ~100-token diff (`V`, `F`, `WT`, `NM`, `B`, `g` genus, `vol`, `bbox`, `size`, tags, query results).
66
+ 2. `inspect({})` — Return current scene summary without mutating state.
67
+ 3. `tx({ action: "checkpoint"|"rollback"|"undo"|"reset", tag? })` — Instant O(1) copy-on-write state control.
68
+ 4. `export({ path, part?, size? })` — Export to `.glb` (PBR + UVs), `.step`, `.3mf`, `.stl`, `.obj`, or render a 4-view `.png` preview.
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "forma-3d",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, WASM library, and MCP server.",
5
+ "license": "MIT",
6
+ "author": "wrong-nebula",
7
+ "type": "module",
8
+ "main": "./lib/index.mjs",
9
+ "types": "./lib/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./lib/index.d.ts",
13
+ "import": "./lib/index.mjs"
14
+ }
15
+ },
16
+ "bin": {
17
+ "forma": "bin/forma.mjs",
18
+ "forma-3d": "bin/forma.mjs",
19
+ "forma-mcp": "bin/forma-mcp.mjs",
20
+ "forma-3d-mcp": "bin/forma-mcp.mjs"
21
+ },
22
+ "files": [
23
+ "bin/",
24
+ "lib/",
25
+ "wasm/forma.wasm",
26
+ "grammar/forma_pipe.gbnf",
27
+ "SKILL.md",
28
+ "AGENTS.md",
29
+ "llms.txt",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "scripts": {
34
+ "build:wasm": "RUSTFLAGS=\"--remap-path-prefix=$HOME=/home\" cargo build --profile wasm-release --target wasm32-unknown-unknown -p forma-wasm && mkdir -p wasm && cp target/wasm32-unknown-unknown/wasm-release/forma_wasm.wasm wasm/forma.wasm",
35
+ "test": "node tests/npm_smoke.mjs"
36
+ },
37
+ "keywords": [
38
+ "3d",
39
+ "cad",
40
+ "brep",
41
+ "csg",
42
+ "blender",
43
+ "mcp",
44
+ "ai-agents",
45
+ "llm",
46
+ "glb",
47
+ "step",
48
+ "3mf",
49
+ "stl",
50
+ "wasm",
51
+ "rust",
52
+ "forma"
53
+ ],
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git+https://github.com/wrong-nebula/forma.git"
57
+ },
58
+ "homepage": "https://github.com/wrong-nebula/forma#readme",
59
+ "bugs": {
60
+ "url": "https://github.com/wrong-nebula/forma/issues"
61
+ },
62
+ "engines": {
63
+ "node": ">=18.0.0"
64
+ },
65
+ "dependencies": {}
66
+ }
Binary file