Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

feat(freecad): add complete CLI harness for FreeCAD (258 commands, 17 groups)

AlexGabbia5bb637802061
diff --git a/.gitignore b/.gitignore
index 10ae83e7a..4a04fc487 100644
--- a/.gitignore
+++ b/.gitignore
@@ -55,6 +55,7 @@
!/browser/
!/musescore/
!/krita/
+!/freecad/
# Step 5: Inside each software dir, ignore everything (including dotfiles)
/gimp/*
@@ -97,6 +98,8 @@
/musescore/.*
/krita/*
/krita/.*
+/freecad/*
+/freecad/.*
# Step 6: ...except agent-harness/
!/gimp/agent-harness/
@@ -120,6 +123,7 @@
!/browser/agent-harness/
!/musescore/agent-harness/
!/krita/agent-harness/
+!/freecad/agent-harness/
# Step 7: Ignore build artifacts within allowed dirs
**/__pycache__/
diff --git a/freecad/agent-harness/FREECAD.md b/freecad/agent-harness/FREECAD.md
new file mode 100644
index 000000000..e24dba78d
--- /dev/null
+++ b/freecad/agent-harness/FREECAD.md
@@ -0,0 +1,159 @@
+# FreeCAD CLI Harness — Standard Operating Procedure
+
+## Software Overview
+
+**FreeCAD** is an open-source parametric 3D CAD modeler built on OpenCASCADE (OCCT).
+It supports Part design, Sketcher, Assembly, TechDraw, Mesh, and many other workbenches.
+
+- **Backend engine**: OpenCASCADE Technology (OCCT)
+- **Native format**: `.FCStd` (ZIP containing `Document.xml` + BREP geometry files)
+- **Python API**: `FreeCAD` (`App`) module — full document/object manipulation
+- **Headless mode**: `freecadcmd` or `freecad -c` — runs without GUI
+- **Macro execution**: `freecadcmd script.py` — executes Python macro headlessly
+- **Export formats**: STEP, IGES, STL, OBJ, DXF, SVG, PDF (via TechDraw)
+
+## Architecture
+
+```
+┌──────────────────────────────────────────────────────┐
+│ cli-anything-freecad (CLI + REPL) │
+│ ┌──────────────┐ ┌──────────────┐ ┌────────────┐ │
+│ │ document.py │ │ parts.py │ │ sketch.py │ │
+│ │ create/save │ │ primitives │ │ 2D shapes │ │
+│ └──────────────┘ └──────────────┘ └────────────┘ │
+│ ┌──────────────┐ ┌──────────────┐ ┌────────────┐ │
+│ │ body.py │ │ materials.py │ │ export.py │ │
+│ │ pad/pocket │ │ PBR mats │ │ STEP/STL │ │
+│ └──────────────┘ └──────────────┘ └────────────┘ │
+│ ┌──────────────┐ │
+│ │ session.py │ ← undo/redo, state management │
+│ └──────────────┘ │
+├──────────────────────────────────────────────────────┤
+│ freecad_macro_gen.py — generates FreeCAD macros │
+│ freecad_backend.py — invokes FreeCAD headless │
+├──────────────────────────────────────────────────────┤
+│ FreeCAD (freecadcmd) — the REAL software │
+│ OpenCASCADE — geometry kernel │
+└──────────────────────────────────────────────────────┘
+```
+
+## Data Model
+
+The CLI maintains project state as a JSON document:
+
+```json
+{
+ "version": "1.0",
+ "name": "my_project",
+ "units": "mm",
+ "parts": [
+ {
+ "id": 0,
+ "name": "Box",
+ "type": "box",
+ "params": {"length": 10, "width": 10, "height": 10},
+ "placement": {"position": [0, 0, 0], "rotation": [0, 0, 0]},
+ "material_index": null,
+ "visible": true
+ }
+ ],
+ "sketches": [],
+ "bodies": [],
+ "materials": [],
+ "metadata": {
+ "created": "2026-03-22T...",
+ "modified": "2026-03-22T...",
+ "software": "cli-anything-freecad 1.0.0"
+ }
+}
+```
+
+## Command Groups
+
+| Group | Commands |
+|------------|-------------------------------------------------------|
+| `document` | new, open, save, info, profiles |
+| `part` | add, remove, list, get, transform, boolean |
+| `sketch` | new, add-line, add-circle, add-rect, constrain, close |
+| `body` | new, pad, pocket, fillet, chamfer, list |
+| `material` | create, assign, list, set |
+| `export` | render, info, presets |
+| `session` | undo, redo, status, history |
+
+## Rendering Pipeline
+
+1. **Build JSON state** via CLI commands (document, part, sketch, body, material)
+2. **Generate FreeCAD macro** from JSON state (`freecad_macro_gen.py`)
+3. **Execute macro headlessly** via `freecadcmd script.py`
+4. **Export output** (STEP, IGES, STL, OBJ) from the generated `.FCStd` document
+5. **Verify output** (file exists, size > 0, correct format magic bytes)
+
+## FreeCAD Python API Reference
+
+```python
+import FreeCAD
+import Part
+
+# Document management
+doc = FreeCAD.newDocument("MyProject")
+doc.saveAs("/path/to/project.FCStd")
+
+# Primitives
+box = doc.addObject("Part::Box", "MyBox")
+box.Length = 10
+box.Width = 10
+box.Height = 10
+
+cyl = doc.addObject("Part::Cylinder", "MyCylinder")
+cyl.Radius = 5
+cyl.Height = 20
+
+sphere = doc.addObject("Part::Sphere", "MySphere")
+sphere.Radius = 10
+
+cone = doc.addObject("Part::Cone", "MyCone")
+cone.Radius1 = 10
+cone.Radius2 = 5
+cone.Height = 15
+
+torus = doc.addObject("Part::Torus", "MyTorus")
+torus.Radius1 = 10
+torus.Radius2 = 3
+
+# Boolean operations
+cut = doc.addObject("Part::Cut", "Cut")
+cut.Base = box
+cut.Tool = cyl
+
+fuse = doc.addObject("Part::Fuse", "Fuse")
+fuse.Base = box
+fuse.Tool = cyl
+
+common = doc.addObject("Part::Common", "Common")
+common.Base = box
+common.Tool = cyl
+
+# Placement
+import FreeCAD
+box.Placement = FreeCAD.Placement(
+ FreeCAD.Vector(x, y, z),
+ FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), angle_degrees)
+)
+
+# Export
+Part.export([box, cyl], "/path/to/output.step")
+Part.export([box], "/path/to/output.stl")
+
+# Recompute
+doc.recompute()
+```
+
+## Dependencies
+
+- **FreeCAD** (system package) — HARD DEPENDENCY
+ - Windows: Download from freecad.org
+ - Linux: `apt install freecad` or `snap install freecad`
+ - macOS: `brew install --cask freecad`
+- **Python 3.10+**
+- **click** >= 8.0 (CLI framework)
+- **prompt-toolkit** >= 3.0 (REPL)
diff --git a/freecad/agent-harness/cli_anything/freecad/README.md b/freecad/agent-harness/cli_anything/freecad/README.md
new file mode 100644
index 000000000..86d961a5f
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/README.md
@@ -0,0 +1,104 @@
+# cli-anything-freecad
+
+CLI harness for **FreeCAD** parametric 3D CAD modeler. Create, modify, and export
+3D models from the command line or via AI agents — no GUI needed.
+
+## Prerequisites
+
+**FreeCAD** must be installed on your system. The CLI generates FreeCAD Python
+macros and executes them headlessly via `freecadcmd`.
+
+- **Windows**: Download from [freecad.org](https://www.freecad.org/downloads.php)
+- **Linux**: `sudo apt install freecad` or `snap install freecad`
+- **macOS**: `brew install --cask freecad`
+
+Verify installation:
+```bash
+freecadcmd --version
+```
+
+## Installation
+
+```bash
+cd freecad/agent-harness
+pip install -e .
+```
+
+Verify:
+```bash
+cli-anything-freecad --help
+```
+
+## Quick Start
+
+### One-shot commands
+```bash
+# Create a new document
+cli-anything-freecad document new --name "MyPart" -o project.json
+
+# Add a box
+cli-anything-freecad -p project.json part add box --name "Base" -P length=20 -P width=15 -P height=5
+
+# Add a cylinder
+cli-anything-freecad -p project.json part add cylinder --name "Hole" -P radius=3 -P height=10 --position 10,7.5,0
+
+# Boolean cut (subtract cylinder from box)
+cli-anything-freecad -p project.json part boolean cut 0 1 --name "BaseWithHole"
+
+# Export to STEP
+cli-anything-freecad -p project.json export render output.step --preset step
+```
+
+### Interactive REPL
+```bash
+cli-anything-freecad
+# or with a project:
+cli-anything-freecad -p project.json
+```
+
+### JSON output for agents
+```bash
+cli-anything-freecad --json document new --name "AgentProject" -o project.json
+cli-anything-freecad --json -p project.json part add box
+cli-anything-freecad --json -p project.json export render output.step
+```
+
+## Command Groups
+
+| Group | Description |
+|-------|-------------|
+| `document` | Create, open, save, inspect documents |
+| `part` | Add/remove 3D primitives, transform, boolean ops |
+| `sketch` | Create 2D sketches with lines, circles, arcs, constraints |
+| `body` | PartDesign bodies — pad, pocket, fillet, chamfer, revolution |
+| `material` | Create and assign PBR materials |
+| `export` | Export to STEP, IGES, STL, OBJ, BREP, FCStd |
+| `session` | Undo/redo, status, history |
+
+## Supported Primitives
+
+Box, Cylinder, Sphere, Cone, Torus, Wedge
+
+## Supported Export Formats
+
+| Preset | Format | Description |
+|--------|--------|-------------|
+| `step` | .step | STEP AP214 (ISO 10303) — standard CAD exchange |
+| `iges` | .iges | IGES format |
+| `stl` | .stl | STL mesh (3D printing) |
+| `stl_fine` | .stl | Fine-mesh STL |
+| `obj` | .obj | Wavefront OBJ |
+| `brep` | .brep | OpenCASCADE BREP |
+| `fcstd` | .FCStd | Native FreeCAD document |
+
+## Running Tests
+
+```bash
+cd freecad/agent-harness
+python -m pytest cli_anything/freecad/tests/ -v -s
+```
+
+Force installed command testing:
+```bash
+CLI_ANYTHING_FORCE_INSTALLED=1 python -m pytest cli_anything/freecad/tests/ -v -s
+```
diff --git a/freecad/agent-harness/cli_anything/freecad/__init__.py b/freecad/agent-harness/cli_anything/freecad/__init__.py
new file mode 100644
index 000000000..dd7a93ebf
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/__init__.py
@@ -0,0 +1,3 @@
+"""cli-anything-freecad — CLI harness for FreeCAD parametric 3D CAD modeler."""
+
+__version__ = "1.0.0"
diff --git a/freecad/agent-harness/cli_anything/freecad/__main__.py b/freecad/agent-harness/cli_anything/freecad/__main__.py
new file mode 100644
index 000000000..c20bb702a
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/__main__.py
@@ -0,0 +1,6 @@
+"""Allow running as: python -m cli_anything.freecad"""
+
+from cli_anything.freecad.freecad_cli import main
+
+if __name__ == "__main__":
+ main()
diff --git a/freecad/agent-harness/cli_anything/freecad/core/__init__.py b/freecad/agent-harness/cli_anything/freecad/core/__init__.py
new file mode 100644
index 000000000..b84d679a8
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/__init__.py
@@ -0,0 +1 @@
+"""Core modules for FreeCAD CLI harness."""
diff --git a/freecad/agent-harness/cli_anything/freecad/core/assembly.py b/freecad/agent-harness/cli_anything/freecad/core/assembly.py
new file mode 100644
index 000000000..2c93e823d
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/assembly.py
@@ -0,0 +1,418 @@
+"""FreeCAD CLI - Assembly module.
+
+Manages assembly creation, component placement, constraints, solving,
+bill-of-materials generation, and exploded/collapsed views on a
+JSON-based project state.
+"""
+
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Set
+
+from .document import ensure_collection
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+VALID_CONSTRAINTS: Set[str] = {
+ "fixed", "coincident", "distance", "angle",
+ "parallel", "perpendicular", "tangent",
+ "revolute", "prismatic", "cylindrical",
+ "ball", "planar", "gear", "belt",
+}
+
+_COLLECTION_KEY = "assemblies"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _next_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for assemblies."""
+ items = project.get(_COLLECTION_KEY, [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str) -> str:
+ """Return a unique name derived from *base* inside the assemblies list."""
+ existing = {item["name"] for item in project.get(_COLLECTION_KEY, [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _validate_vec3(value: Any, label: str) -> List[float]:
+ """Validate that *value* is a list of exactly three numbers."""
+ if not isinstance(value, (list, tuple)):
+ raise ValueError(f"{label} must be a list of 3 numbers, got {type(value).__name__}")
+ if len(value) != 3:
+ raise ValueError(f"{label} must have exactly 3 elements, got {len(value)}")
+ try:
+ return [float(v) for v in value]
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} elements must be numeric: {exc}") from exc
+
+
+def _get_assembly(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Internal accessor with bounds checking."""
+ items = ensure_collection(project, _COLLECTION_KEY)
+ if not isinstance(index, int) or index < 0 or index >= len(items):
+ raise IndexError(
+ f"Assembly index {index} out of range (0..{len(items) - 1})"
+ )
+ return items[index]
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+def create_assembly(
+ project: Dict[str, Any],
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a new empty assembly and append it to the project.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ name : str or None
+ Human-readable label. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created assembly dictionary.
+ """
+ items = ensure_collection(project, _COLLECTION_KEY)
+
+ if name is None:
+ name = _unique_name(project, "Assembly")
+
+ assembly: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "components": [],
+ "constraints": [],
+ "solved": False,
+ }
+
+ items.append(assembly)
+ return assembly
+
+
+def add_part_to_assembly(
+ project: Dict[str, Any],
+ asm_index: int,
+ part_index: int,
+ transform: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a part reference to an assembly as a component.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ asm_index : int
+ Index of the target assembly.
+ part_index : int
+ Index of the part in ``project["parts"]``.
+ transform : list[float] or None
+ Optional ``[x, y, z]`` placement offset. Defaults to ``[0, 0, 0]``.
+
+ Returns
+ -------
+ dict
+ The newly created component entry.
+
+ Raises
+ ------
+ IndexError
+ If *asm_index* or *part_index* is out of range.
+ """
+ assembly = _get_assembly(project, asm_index)
+
+ parts = project.get("parts", [])
+ if not isinstance(part_index, int) or part_index < 0 or part_index >= len(parts):
+ raise IndexError(
+ f"Part index {part_index} out of range (0..{len(parts) - 1})"
+ )
+
+ if transform is not None:
+ transform = _validate_vec3(transform, "transform")
+ else:
+ transform = [0.0, 0.0, 0.0]
+
+ part = parts[part_index]
+ component: Dict[str, Any] = {
+ "part_index": part_index,
+ "transform": transform,
+ "name": part["name"],
+ }
+
+ assembly["components"].append(component)
+ assembly["solved"] = False
+ return component
+
+
+def remove_part_from_assembly(
+ project: Dict[str, Any],
+ asm_index: int,
+ component_index: int,
+) -> Dict[str, Any]:
+ """Remove a component from an assembly by its component index.
+
+ Returns the removed component dictionary.
+
+ Raises ``IndexError`` when either index is out of range.
+ """
+ assembly = _get_assembly(project, asm_index)
+ components = assembly["components"]
+
+ if not isinstance(component_index, int) or component_index < 0 or component_index >= len(components):
+ raise IndexError(
+ f"Component index {component_index} out of range "
+ f"(0..{len(components) - 1})"
+ )
+
+ assembly["solved"] = False
+ return components.pop(component_index)
+
+
+def list_assemblies(project: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return all assemblies in the project."""
+ return project.get(_COLLECTION_KEY, [])
+
+
+def get_assembly(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the assembly at *index* without removing it.
+
+ Raises ``IndexError`` when the index is out of range.
+ """
+ return _get_assembly(project, index)
+
+
+def add_assembly_constraint(
+ project: Dict[str, Any],
+ asm_index: int,
+ constraint_type: str,
+ component_indices: List[int],
+ **params: Any,
+) -> Dict[str, Any]:
+ """Add a constraint between components in an assembly.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ asm_index : int
+ Index of the target assembly.
+ constraint_type : str
+ One of :data:`VALID_CONSTRAINTS`.
+ component_indices : list[int]
+ Indices of components involved in the constraint.
+ **params
+ Extra parameters depending on the constraint type (e.g.
+ ``distance``, ``angle``, ``axis``).
+
+ Returns
+ -------
+ dict
+ The newly created constraint entry.
+
+ Raises
+ ------
+ ValueError
+ If *constraint_type* is unknown or *component_indices* is invalid.
+ IndexError
+ If *asm_index* or any component index is out of range.
+ """
+ if constraint_type not in VALID_CONSTRAINTS:
+ valid = ", ".join(sorted(VALID_CONSTRAINTS))
+ raise ValueError(
+ f"Unknown constraint_type '{constraint_type}'. Valid: {valid}"
+ )
+
+ assembly = _get_assembly(project, asm_index)
+
+ if not isinstance(component_indices, (list, tuple)) or len(component_indices) == 0:
+ raise ValueError("component_indices must be a non-empty list of integers")
+
+ num_components = len(assembly["components"])
+ for ci in component_indices:
+ if not isinstance(ci, int) or ci < 0 or ci >= num_components:
+ raise IndexError(
+ f"Component index {ci} out of range (0..{num_components - 1})"
+ )
+
+ constraint: Dict[str, Any] = {
+ "type": constraint_type,
+ "component_indices": list(component_indices),
+ "params": dict(params),
+ }
+
+ assembly["constraints"].append(constraint)
+ assembly["solved"] = False
+ return constraint
+
+
+def solve_assembly(
+ project: Dict[str, Any],
+ asm_index: int,
+) -> Dict[str, Any]:
+ """Mark the assembly as solved and return a DOF estimate.
+
+ In the CLI harness the actual constraint solving happens in the
+ generated FreeCAD macro. This function records the intent and
+ provides a rough degrees-of-freedom estimate.
+
+ Returns
+ -------
+ dict
+ ``{"solved": True, "dof": <int>}``
+ """
+ assembly = _get_assembly(project, asm_index)
+ assembly["solved"] = True
+
+ num_components = len(assembly["components"])
+ num_constraints = len(assembly["constraints"])
+ dof = max(0, 6 * num_components - num_constraints)
+
+ return {"solved": True, "dof": dof}
+
+
+def degrees_of_freedom(
+ project: Dict[str, Any],
+ asm_index: int,
+) -> Dict[str, Any]:
+ """Estimate the remaining degrees of freedom for an assembly.
+
+ Uses the simple formula ``6 * components - constraints``, clamped
+ to zero.
+
+ Returns
+ -------
+ dict
+ ``{"dof": <int>, "components": <int>, "constraints": <int>}``
+ """
+ assembly = _get_assembly(project, asm_index)
+
+ num_components = len(assembly["components"])
+ num_constraints = len(assembly["constraints"])
+ dof = max(0, 6 * num_components - num_constraints)
+
+ return {
+ "dof": dof,
+ "components": num_components,
+ "constraints": num_constraints,
+ }
+
+
+def generate_bom(
+ project: Dict[str, Any],
+ asm_index: int,
+) -> Dict[str, Any]:
+ """Generate a bill of materials for an assembly.
+
+ Returns
+ -------
+ dict
+ ``{"items": [{"name", "part_index", "quantity", "material"}], "total_parts": <int>}``
+ """
+ assembly = _get_assembly(project, asm_index)
+ parts = project.get("parts", [])
+ materials = project.get("materials", [])
+
+ # Count occurrences of each part_index
+ counts: Dict[int, int] = {}
+ for comp in assembly["components"]:
+ pi = comp["part_index"]
+ counts[pi] = counts.get(pi, 0) + 1
+
+ items: List[Dict[str, Any]] = []
+ for pi, qty in sorted(counts.items()):
+ part = parts[pi] if pi < len(parts) else {"name": f"Part_{pi}", "material_index": None}
+ mat_name = None
+ mi = part.get("material_index")
+ if mi is not None and mi < len(materials):
+ mat_name = materials[mi].get("name")
+
+ items.append({
+ "name": part["name"],
+ "part_index": pi,
+ "quantity": qty,
+ "material": mat_name,
+ })
+
+ return {
+ "items": items,
+ "total_parts": len(assembly["components"]),
+ }
+
+
+def explode_assembly(
+ project: Dict[str, Any],
+ asm_index: int,
+ factor: float = 2.0,
+) -> Dict[str, Any]:
+ """Move assembly components outward by *factor* for an exploded view.
+
+ Each component's transform is scaled by *factor* relative to the
+ assembly centroid.
+
+ Returns
+ -------
+ dict
+ ``{"exploded": True, "factor": <float>, "components": <int>}``
+ """
+ assembly = _get_assembly(project, asm_index)
+ components = assembly["components"]
+
+ if not components:
+ return {"exploded": True, "factor": factor, "components": 0}
+
+ # Compute centroid
+ cx = sum(c["transform"][0] for c in components) / len(components)
+ cy = sum(c["transform"][1] for c in components) / len(components)
+ cz = sum(c["transform"][2] for c in components) / len(components)
+
+ # Move each component outward
+ for comp in components:
+ t = comp["transform"]
+ comp["transform"] = [
+ cx + (t[0] - cx) * factor,
+ cy + (t[1] - cy) * factor,
+ cz + (t[2] - cz) * factor,
+ ]
+
+ return {"exploded": True, "factor": factor, "components": len(components)}
+
+
+def collapse_assembly(
+ project: Dict[str, Any],
+ asm_index: int,
+) -> Dict[str, Any]:
+ """Reset all component transforms to their origin positions.
+
+ If the assembly was previously solved, transforms are reset to
+ ``[0, 0, 0]``.
+
+ Returns
+ -------
+ dict
+ ``{"collapsed": True, "components": <int>}``
+ """
+ assembly = _get_assembly(project, asm_index)
+
+ for comp in assembly["components"]:
+ comp["transform"] = [0.0, 0.0, 0.0]
+
+ return {"collapsed": True, "components": len(assembly["components"])}
diff --git a/freecad/agent-harness/cli_anything/freecad/core/body.py b/freecad/agent-harness/cli_anything/freecad/core/body.py
new file mode 100644
index 000000000..c68683d05
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/body.py
@@ -0,0 +1,1918 @@
+"""
+PartDesign body module for the FreeCAD CLI harness.
+
+Provides creation of PartDesign bodies and additive/subtractive features
+such as pad, pocket, fillet, chamfer, and revolution.
+"""
+
+from typing import Any, Dict, List, Optional, Union
+
+
+# ---------------------------------------------------------------------------
+# Valid constants
+# ---------------------------------------------------------------------------
+
+VALID_FEATURE_TYPES = {
+ "pad", "pocket", "fillet", "chamfer", "revolution",
+ "additive_loft", "additive_pipe", "additive_helix",
+ "additive_box", "additive_cylinder", "additive_sphere",
+ "additive_cone", "additive_torus", "additive_wedge",
+ "groove", "subtractive_loft", "subtractive_pipe", "subtractive_helix",
+ "subtractive_box", "subtractive_cylinder", "subtractive_sphere",
+ "subtractive_cone", "subtractive_torus", "subtractive_wedge",
+ "draft", "thickness",
+ "linear_pattern", "polar_pattern", "mirrored", "multi_transform",
+ "hole", "datum_plane", "datum_line", "datum_point", "shape_binder",
+}
+VALID_REVOLUTION_AXES = {"X", "Y", "Z"}
+VALID_PATTERN_PLANES = {"XY", "XZ", "YZ"}
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _next_id(project: Dict[str, Any], collection_key: str = "bodies") -> int:
+ """Generate the next unique ID for a collection."""
+ items = project.get(collection_key, [])
+ existing_ids = [item.get("id", 0) for item in items]
+ return max(existing_ids, default=-1) + 1
+
+
+def _unique_name(project: Dict[str, Any], base_name: str, collection_key: str = "bodies") -> str:
+ """Generate a unique name within a collection."""
+ items = project.get(collection_key, [])
+ existing_names = {item.get("name", "") for item in items}
+ if base_name not in existing_names:
+ return base_name
+ counter = 1
+ while f"{base_name}.{counter:03d}" in existing_names:
+ counter += 1
+ return f"{base_name}.{counter:03d}"
+
+
+def _next_feature_id(body: Dict[str, Any]) -> int:
+ """Generate the next unique feature ID within a body."""
+ features = body.get("features", [])
+ existing_ids = [f.get("id", 0) for f in features]
+ return max(existing_ids, default=-1) + 1
+
+
+def _validate_project(project: Dict[str, Any]) -> None:
+ """Raise ``ValueError`` if *project* is not a valid dict with required collections."""
+ if not isinstance(project, dict):
+ raise ValueError("Project must be a dictionary")
+ if "bodies" not in project:
+ raise ValueError("Project is missing 'bodies' collection")
+ if not isinstance(project["bodies"], list):
+ raise ValueError("Project 'bodies' must be a list")
+
+
+def _get_body(project: Dict[str, Any], body_index: int) -> Dict[str, Any]:
+ """Return body at *body_index* or raise ``IndexError``."""
+ bodies = project["bodies"]
+ if body_index < 0 or body_index >= len(bodies):
+ raise IndexError(
+ f"Body index {body_index} out of range (0-{len(bodies) - 1})"
+ )
+ return bodies[body_index]
+
+
+def _validate_sketch_index(project: Dict[str, Any], sketch_index: int) -> Dict[str, Any]:
+ """Validate that a sketch index exists and return the sketch."""
+ sketches = project.get("sketches", [])
+ if not isinstance(sketches, list):
+ raise ValueError("Project 'sketches' must be a list")
+ if sketch_index < 0 or sketch_index >= len(sketches):
+ raise IndexError(
+ f"Sketch index {sketch_index} out of range (0-{len(sketches) - 1})"
+ )
+ return sketches[sketch_index]
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def create_body(
+ project: Dict[str, Any],
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a new PartDesign body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ name:
+ Optional body name. Auto-generated if ``None``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created body dictionary.
+ """
+ _validate_project(project)
+
+ base_name = name if name else "Body"
+ body_name = _unique_name(project, base_name)
+
+ body: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": body_name,
+ "features": [],
+ "base_sketch_index": None,
+ }
+
+ project["bodies"].append(body)
+ return body
+
+
+def pad(
+ project: Dict[str, Any],
+ body_index: int,
+ sketch_index: int,
+ length: float = 10.0,
+ symmetric: bool = False,
+ reversed: bool = False,
+) -> Dict[str, Any]:
+ """Add a pad (extrusion) feature to a body based on a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ sketch_index:
+ Index of the sketch to extrude.
+ length:
+ Extrusion length. Must be positive.
+ symmetric:
+ If ``True``, extrude symmetrically in both directions
+ (half the length each way).
+ reversed:
+ If ``True``, extrude in the opposite direction.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created pad feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+ sketch = _validate_sketch_index(project, sketch_index)
+
+ length = float(length)
+ if length <= 0:
+ raise ValueError(f"Pad length must be positive, got {length}")
+
+ # Set base sketch if this is the first feature
+ if body["base_sketch_index"] is None:
+ body["base_sketch_index"] = sketch_index
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "pad",
+ "sketch_index": sketch_index,
+ "sketch_name": sketch.get("name", f"Sketch {sketch_index}"),
+ "length": length,
+ "symmetric": bool(symmetric),
+ "reversed": bool(reversed),
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def pocket(
+ project: Dict[str, Any],
+ body_index: int,
+ sketch_index: int,
+ length: float = 5.0,
+ symmetric: bool = False,
+ reversed: bool = False,
+) -> Dict[str, Any]:
+ """Add a pocket (cut extrusion) feature to a body based on a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ sketch_index:
+ Index of the sketch defining the pocket profile.
+ length:
+ Cut depth. Must be positive.
+ symmetric:
+ If ``True``, cut symmetrically in both directions.
+ reversed:
+ If ``True``, cut in the opposite direction.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created pocket feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+ sketch = _validate_sketch_index(project, sketch_index)
+
+ length = float(length)
+ if length <= 0:
+ raise ValueError(f"Pocket length must be positive, got {length}")
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "pocket",
+ "sketch_index": sketch_index,
+ "sketch_name": sketch.get("name", f"Sketch {sketch_index}"),
+ "length": length,
+ "symmetric": bool(symmetric),
+ "reversed": bool(reversed),
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def fillet(
+ project: Dict[str, Any],
+ body_index: int,
+ radius: float = 1.0,
+ edges: Union[str, List[int]] = "all",
+) -> Dict[str, Any]:
+ """Add a fillet (rounded edge) feature to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ radius:
+ Fillet radius. Must be positive.
+ edges:
+ ``"all"`` to fillet every edge, or a list of edge indices.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created fillet feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ radius = float(radius)
+ if radius <= 0:
+ raise ValueError(f"Fillet radius must be positive, got {radius}")
+
+ if edges != "all":
+ if not isinstance(edges, (list, tuple)):
+ raise ValueError("Edges must be 'all' or a list of edge indices")
+ for idx in edges:
+ if not isinstance(idx, int) or idx < 0:
+ raise ValueError(f"Edge index must be a non-negative integer, got {idx!r}")
+ edges = list(edges)
+
+ if not body["features"]:
+ raise ValueError("Cannot add fillet to a body with no existing features")
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "fillet",
+ "radius": radius,
+ "edges": edges,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def chamfer(
+ project: Dict[str, Any],
+ body_index: int,
+ size: float = 1.0,
+ edges: Union[str, List[int]] = "all",
+) -> Dict[str, Any]:
+ """Add a chamfer (beveled edge) feature to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ size:
+ Chamfer size (distance). Must be positive.
+ edges:
+ ``"all"`` to chamfer every edge, or a list of edge indices.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created chamfer feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ size = float(size)
+ if size <= 0:
+ raise ValueError(f"Chamfer size must be positive, got {size}")
+
+ if edges != "all":
+ if not isinstance(edges, (list, tuple)):
+ raise ValueError("Edges must be 'all' or a list of edge indices")
+ for idx in edges:
+ if not isinstance(idx, int) or idx < 0:
+ raise ValueError(f"Edge index must be a non-negative integer, got {idx!r}")
+ edges = list(edges)
+
+ if not body["features"]:
+ raise ValueError("Cannot add chamfer to a body with no existing features")
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "chamfer",
+ "size": size,
+ "edges": edges,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def revolution(
+ project: Dict[str, Any],
+ body_index: int,
+ sketch_index: int,
+ angle: float = 360.0,
+ axis: str = "Z",
+ reversed: bool = False,
+) -> Dict[str, Any]:
+ """Add a revolution feature to a body based on a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ sketch_index:
+ Index of the sketch to revolve.
+ angle:
+ Revolution angle in degrees (0 exclusive, 360 inclusive).
+ axis:
+ Revolution axis: ``"X"``, ``"Y"``, or ``"Z"``.
+ reversed:
+ If ``True``, revolve in the opposite direction.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created revolution feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+ sketch = _validate_sketch_index(project, sketch_index)
+
+ angle = float(angle)
+ if angle <= 0 or angle > 360:
+ raise ValueError(f"Revolution angle must be in (0, 360], got {angle}")
+
+ axis = axis.upper()
+ if axis not in VALID_REVOLUTION_AXES:
+ raise ValueError(
+ f"Invalid revolution axis '{axis}'. Must be one of: {', '.join(sorted(VALID_REVOLUTION_AXES))}"
+ )
+
+ # Set base sketch if this is the first feature
+ if body["base_sketch_index"] is None:
+ body["base_sketch_index"] = sketch_index
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "revolution",
+ "sketch_index": sketch_index,
+ "sketch_name": sketch.get("name", f"Sketch {sketch_index}"),
+ "angle": angle,
+ "axis": axis,
+ "reversed": bool(reversed),
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def list_bodies(project: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return a summary list of all bodies in the project.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+
+ Returns
+ -------
+ List[Dict[str, Any]]
+ List of body summaries with index, id, name, feature count,
+ and base sketch index.
+ """
+ _validate_project(project)
+
+ result: List[Dict[str, Any]] = []
+ for i, body in enumerate(project["bodies"]):
+ result.append({
+ "index": i,
+ "id": body.get("id", i),
+ "name": body.get("name", f"Body {i}"),
+ "feature_count": len(body.get("features", [])),
+ "base_sketch_index": body.get("base_sketch_index"),
+ })
+ return result
+
+
+def get_body(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the full body dictionary at the given index.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ index:
+ Body index.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The complete body dictionary.
+ """
+ _validate_project(project)
+ return _get_body(project, index)
+
+
+# ---------------------------------------------------------------------------
+# Additive Features
+# ---------------------------------------------------------------------------
+
+
+def additive_loft(
+ project: Dict[str, Any],
+ body_index: int,
+ sketch_indices: List[int],
+ solid: bool = True,
+ ruled: bool = False,
+) -> Dict[str, Any]:
+ """Add a loft feature between two or more sketches.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ sketch_indices:
+ List of sketch indices defining loft cross-sections. Minimum 2.
+ solid:
+ If ``True``, create a solid loft.
+ ruled:
+ If ``True``, use ruled surfaces between sections.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created additive loft feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not isinstance(sketch_indices, (list, tuple)) or len(sketch_indices) < 2:
+ raise ValueError("Loft requires at least 2 sketch indices")
+
+ sketch_names: List[str] = []
+ for si in sketch_indices:
+ sk = _validate_sketch_index(project, si)
+ sketch_names.append(sk.get("name", f"Sketch {si}"))
+
+ if body["base_sketch_index"] is None:
+ body["base_sketch_index"] = sketch_indices[0]
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "additive_loft",
+ "sketch_indices": list(sketch_indices),
+ "sketch_names": sketch_names,
+ "solid": bool(solid),
+ "ruled": bool(ruled),
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def additive_pipe(
+ project: Dict[str, Any],
+ body_index: int,
+ profile_sketch_index: int,
+ path_sketch_index: int,
+) -> Dict[str, Any]:
+ """Add a pipe (sweep) feature along a path sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ profile_sketch_index:
+ Index of the sketch defining the sweep profile.
+ path_sketch_index:
+ Index of the sketch defining the sweep path.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created additive pipe feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ profile = _validate_sketch_index(project, profile_sketch_index)
+ path = _validate_sketch_index(project, path_sketch_index)
+
+ if body["base_sketch_index"] is None:
+ body["base_sketch_index"] = profile_sketch_index
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "additive_pipe",
+ "profile_sketch_index": profile_sketch_index,
+ "profile_sketch_name": profile.get("name", f"Sketch {profile_sketch_index}"),
+ "path_sketch_index": path_sketch_index,
+ "path_sketch_name": path.get("name", f"Sketch {path_sketch_index}"),
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def additive_helix(
+ project: Dict[str, Any],
+ body_index: int,
+ sketch_index: int,
+ pitch: float = 5.0,
+ height: float = 20.0,
+ turns: Optional[float] = None,
+) -> Dict[str, Any]:
+ """Add a helix extrusion feature.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ sketch_index:
+ Index of the sketch to extrude along the helix.
+ pitch:
+ Distance between helix turns. Must be positive.
+ height:
+ Total helix height. Must be positive.
+ turns:
+ Number of turns. If provided, overrides height
+ (``height = turns * pitch``).
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created additive helix feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+ sketch = _validate_sketch_index(project, sketch_index)
+
+ pitch = float(pitch)
+ if pitch <= 0:
+ raise ValueError(f"Pitch must be positive, got {pitch}")
+
+ if turns is not None:
+ turns = float(turns)
+ if turns <= 0:
+ raise ValueError(f"Turns must be positive, got {turns}")
+ height = turns * pitch
+ else:
+ height = float(height)
+ if height <= 0:
+ raise ValueError(f"Height must be positive, got {height}")
+ turns = height / pitch
+
+ if body["base_sketch_index"] is None:
+ body["base_sketch_index"] = sketch_index
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "additive_helix",
+ "sketch_index": sketch_index,
+ "sketch_name": sketch.get("name", f"Sketch {sketch_index}"),
+ "pitch": pitch,
+ "height": height,
+ "turns": turns,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def _additive_primitive(
+ project: Dict[str, Any],
+ body_index: int,
+ primitive_type: str,
+ params: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Internal helper to add an additive primitive feature."""
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": f"additive_{primitive_type}",
+ }
+ feature.update(params)
+
+ body["features"].append(feature)
+ return feature
+
+
+def additive_box(
+ project: Dict[str, Any],
+ body_index: int,
+ length: float = 10.0,
+ width: float = 10.0,
+ height: float = 10.0,
+) -> Dict[str, Any]:
+ """Add an additive box primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ length:
+ Box length (X). Must be positive.
+ width:
+ Box width (Y). Must be positive.
+ height:
+ Box height (Z). Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created additive box feature dictionary.
+ """
+ length, width, height = float(length), float(width), float(height)
+ for name, val in [("length", length), ("width", width), ("height", height)]:
+ if val <= 0:
+ raise ValueError(f"Box {name} must be positive, got {val}")
+ return _additive_primitive(project, body_index, "box", {
+ "length": length, "width": width, "height": height,
+ })
+
+
+def additive_cylinder(
+ project: Dict[str, Any],
+ body_index: int,
+ radius: float = 5.0,
+ height: float = 10.0,
+) -> Dict[str, Any]:
+ """Add an additive cylinder primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ radius:
+ Cylinder radius. Must be positive.
+ height:
+ Cylinder height. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created additive cylinder feature dictionary.
+ """
+ radius, height = float(radius), float(height)
+ if radius <= 0:
+ raise ValueError(f"Cylinder radius must be positive, got {radius}")
+ if height <= 0:
+ raise ValueError(f"Cylinder height must be positive, got {height}")
+ return _additive_primitive(project, body_index, "cylinder", {
+ "radius": radius, "height": height,
+ })
+
+
+def additive_sphere(
+ project: Dict[str, Any],
+ body_index: int,
+ radius: float = 5.0,
+) -> Dict[str, Any]:
+ """Add an additive sphere primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ radius:
+ Sphere radius. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created additive sphere feature dictionary.
+ """
+ radius = float(radius)
+ if radius <= 0:
+ raise ValueError(f"Sphere radius must be positive, got {radius}")
+ return _additive_primitive(project, body_index, "sphere", {"radius": radius})
+
+
+def additive_cone(
+ project: Dict[str, Any],
+ body_index: int,
+ radius1: float = 5.0,
+ radius2: float = 0.0,
+ height: float = 10.0,
+) -> Dict[str, Any]:
+ """Add an additive cone primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ radius1:
+ Bottom radius. Must be non-negative.
+ radius2:
+ Top radius. Must be non-negative.
+ height:
+ Cone height. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created additive cone feature dictionary.
+ """
+ radius1, radius2, height = float(radius1), float(radius2), float(height)
+ if radius1 < 0:
+ raise ValueError(f"Cone radius1 must be non-negative, got {radius1}")
+ if radius2 < 0:
+ raise ValueError(f"Cone radius2 must be non-negative, got {radius2}")
+ if height <= 0:
+ raise ValueError(f"Cone height must be positive, got {height}")
+ return _additive_primitive(project, body_index, "cone", {
+ "radius1": radius1, "radius2": radius2, "height": height,
+ })
+
+
+def additive_torus(
+ project: Dict[str, Any],
+ body_index: int,
+ radius1: float = 10.0,
+ radius2: float = 2.0,
+) -> Dict[str, Any]:
+ """Add an additive torus primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ radius1:
+ Major radius (center of tube to center of torus). Must be positive.
+ radius2:
+ Minor radius (tube radius). Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created additive torus feature dictionary.
+ """
+ radius1, radius2 = float(radius1), float(radius2)
+ if radius1 <= 0:
+ raise ValueError(f"Torus major radius must be positive, got {radius1}")
+ if radius2 <= 0:
+ raise ValueError(f"Torus minor radius must be positive, got {radius2}")
+ return _additive_primitive(project, body_index, "torus", {
+ "radius1": radius1, "radius2": radius2,
+ })
+
+
+def additive_wedge(
+ project: Dict[str, Any],
+ body_index: int,
+ xmin: float = 0.0,
+ xmax: float = 10.0,
+ ymin: float = 0.0,
+ ymax: float = 10.0,
+ zmin: float = 0.0,
+ zmax: float = 10.0,
+ x2min: float = 2.0,
+ x2max: float = 8.0,
+ z2min: float = 2.0,
+ z2max: float = 8.0,
+) -> Dict[str, Any]:
+ """Add an additive wedge primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ xmin, xmax, ymin, ymax, zmin, zmax:
+ Bounding box extents.
+ x2min, x2max, z2min, z2max:
+ Top face extents (for the tapered wedge shape).
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created additive wedge feature dictionary.
+ """
+ return _additive_primitive(project, body_index, "wedge", {
+ "xmin": float(xmin), "xmax": float(xmax),
+ "ymin": float(ymin), "ymax": float(ymax),
+ "zmin": float(zmin), "zmax": float(zmax),
+ "x2min": float(x2min), "x2max": float(x2max),
+ "z2min": float(z2min), "z2max": float(z2max),
+ })
+
+
+# ---------------------------------------------------------------------------
+# Subtractive Features
+# ---------------------------------------------------------------------------
+
+
+def groove(
+ project: Dict[str, Any],
+ body_index: int,
+ sketch_index: int,
+ angle: float = 360.0,
+ axis: str = "Z",
+ reversed: bool = False,
+) -> Dict[str, Any]:
+ """Add a groove (subtractive revolution) feature to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ sketch_index:
+ Index of the sketch to revolve as a cut.
+ angle:
+ Revolution angle in degrees (0 exclusive, 360 inclusive).
+ axis:
+ Revolution axis: ``"X"``, ``"Y"``, or ``"Z"``.
+ reversed:
+ If ``True``, revolve in the opposite direction.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created groove feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+ sketch = _validate_sketch_index(project, sketch_index)
+
+ angle = float(angle)
+ if angle <= 0 or angle > 360:
+ raise ValueError(f"Groove angle must be in (0, 360], got {angle}")
+
+ axis = axis.upper()
+ if axis not in VALID_REVOLUTION_AXES:
+ raise ValueError(
+ f"Invalid groove axis '{axis}'. Must be one of: {', '.join(sorted(VALID_REVOLUTION_AXES))}"
+ )
+
+ if not body["features"]:
+ raise ValueError("Cannot add groove to a body with no existing features")
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "groove",
+ "sketch_index": sketch_index,
+ "sketch_name": sketch.get("name", f"Sketch {sketch_index}"),
+ "angle": angle,
+ "axis": axis,
+ "reversed": bool(reversed),
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def subtractive_loft(
+ project: Dict[str, Any],
+ body_index: int,
+ sketch_indices: List[int],
+ solid: bool = True,
+ ruled: bool = False,
+) -> Dict[str, Any]:
+ """Add a subtractive loft feature between two or more sketches.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ sketch_indices:
+ List of sketch indices defining loft cross-sections. Minimum 2.
+ solid:
+ If ``True``, create a solid loft cut.
+ ruled:
+ If ``True``, use ruled surfaces between sections.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created subtractive loft feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not isinstance(sketch_indices, (list, tuple)) or len(sketch_indices) < 2:
+ raise ValueError("Loft requires at least 2 sketch indices")
+
+ if not body["features"]:
+ raise ValueError("Cannot add subtractive loft to a body with no existing features")
+
+ sketch_names: List[str] = []
+ for si in sketch_indices:
+ sk = _validate_sketch_index(project, si)
+ sketch_names.append(sk.get("name", f"Sketch {si}"))
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "subtractive_loft",
+ "sketch_indices": list(sketch_indices),
+ "sketch_names": sketch_names,
+ "solid": bool(solid),
+ "ruled": bool(ruled),
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def subtractive_pipe(
+ project: Dict[str, Any],
+ body_index: int,
+ profile_sketch_index: int,
+ path_sketch_index: int,
+) -> Dict[str, Any]:
+ """Add a subtractive pipe (sweep cut) feature along a path sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ profile_sketch_index:
+ Index of the sketch defining the cut profile.
+ path_sketch_index:
+ Index of the sketch defining the sweep path.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created subtractive pipe feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not body["features"]:
+ raise ValueError("Cannot add subtractive pipe to a body with no existing features")
+
+ profile = _validate_sketch_index(project, profile_sketch_index)
+ path = _validate_sketch_index(project, path_sketch_index)
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "subtractive_pipe",
+ "profile_sketch_index": profile_sketch_index,
+ "profile_sketch_name": profile.get("name", f"Sketch {profile_sketch_index}"),
+ "path_sketch_index": path_sketch_index,
+ "path_sketch_name": path.get("name", f"Sketch {path_sketch_index}"),
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def subtractive_helix(
+ project: Dict[str, Any],
+ body_index: int,
+ sketch_index: int,
+ pitch: float = 5.0,
+ height: float = 20.0,
+ turns: Optional[float] = None,
+) -> Dict[str, Any]:
+ """Add a subtractive helix feature.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ sketch_index:
+ Index of the sketch to extrude along the helix as a cut.
+ pitch:
+ Distance between helix turns. Must be positive.
+ height:
+ Total helix height. Must be positive.
+ turns:
+ Number of turns. If provided, overrides height.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created subtractive helix feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+ sketch = _validate_sketch_index(project, sketch_index)
+
+ if not body["features"]:
+ raise ValueError("Cannot add subtractive helix to a body with no existing features")
+
+ pitch = float(pitch)
+ if pitch <= 0:
+ raise ValueError(f"Pitch must be positive, got {pitch}")
+
+ if turns is not None:
+ turns = float(turns)
+ if turns <= 0:
+ raise ValueError(f"Turns must be positive, got {turns}")
+ height = turns * pitch
+ else:
+ height = float(height)
+ if height <= 0:
+ raise ValueError(f"Height must be positive, got {height}")
+ turns = height / pitch
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "subtractive_helix",
+ "sketch_index": sketch_index,
+ "sketch_name": sketch.get("name", f"Sketch {sketch_index}"),
+ "pitch": pitch,
+ "height": height,
+ "turns": turns,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def _subtractive_primitive(
+ project: Dict[str, Any],
+ body_index: int,
+ primitive_type: str,
+ params: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Internal helper to add a subtractive primitive feature."""
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not body["features"]:
+ raise ValueError(
+ f"Cannot add subtractive {primitive_type} to a body with no existing features"
+ )
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": f"subtractive_{primitive_type}",
+ }
+ feature.update(params)
+
+ body["features"].append(feature)
+ return feature
+
+
+def subtractive_box(
+ project: Dict[str, Any],
+ body_index: int,
+ length: float = 10.0,
+ width: float = 10.0,
+ height: float = 10.0,
+) -> Dict[str, Any]:
+ """Add a subtractive box primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ length:
+ Box length (X). Must be positive.
+ width:
+ Box width (Y). Must be positive.
+ height:
+ Box height (Z). Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created subtractive box feature dictionary.
+ """
+ length, width, height = float(length), float(width), float(height)
+ for name, val in [("length", length), ("width", width), ("height", height)]:
+ if val <= 0:
+ raise ValueError(f"Box {name} must be positive, got {val}")
+ return _subtractive_primitive(project, body_index, "box", {
+ "length": length, "width": width, "height": height,
+ })
+
+
+def subtractive_cylinder(
+ project: Dict[str, Any],
+ body_index: int,
+ radius: float = 5.0,
+ height: float = 10.0,
+) -> Dict[str, Any]:
+ """Add a subtractive cylinder primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ radius:
+ Cylinder radius. Must be positive.
+ height:
+ Cylinder height. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created subtractive cylinder feature dictionary.
+ """
+ radius, height = float(radius), float(height)
+ if radius <= 0:
+ raise ValueError(f"Cylinder radius must be positive, got {radius}")
+ if height <= 0:
+ raise ValueError(f"Cylinder height must be positive, got {height}")
+ return _subtractive_primitive(project, body_index, "cylinder", {
+ "radius": radius, "height": height,
+ })
+
+
+def subtractive_sphere(
+ project: Dict[str, Any],
+ body_index: int,
+ radius: float = 5.0,
+) -> Dict[str, Any]:
+ """Add a subtractive sphere primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ radius:
+ Sphere radius. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created subtractive sphere feature dictionary.
+ """
+ radius = float(radius)
+ if radius <= 0:
+ raise ValueError(f"Sphere radius must be positive, got {radius}")
+ return _subtractive_primitive(project, body_index, "sphere", {"radius": radius})
+
+
+def subtractive_cone(
+ project: Dict[str, Any],
+ body_index: int,
+ radius1: float = 5.0,
+ radius2: float = 0.0,
+ height: float = 10.0,
+) -> Dict[str, Any]:
+ """Add a subtractive cone primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ radius1:
+ Bottom radius. Must be non-negative.
+ radius2:
+ Top radius. Must be non-negative.
+ height:
+ Cone height. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created subtractive cone feature dictionary.
+ """
+ radius1, radius2, height = float(radius1), float(radius2), float(height)
+ if radius1 < 0:
+ raise ValueError(f"Cone radius1 must be non-negative, got {radius1}")
+ if radius2 < 0:
+ raise ValueError(f"Cone radius2 must be non-negative, got {radius2}")
+ if height <= 0:
+ raise ValueError(f"Cone height must be positive, got {height}")
+ return _subtractive_primitive(project, body_index, "cone", {
+ "radius1": radius1, "radius2": radius2, "height": height,
+ })
+
+
+def subtractive_torus(
+ project: Dict[str, Any],
+ body_index: int,
+ radius1: float = 10.0,
+ radius2: float = 2.0,
+) -> Dict[str, Any]:
+ """Add a subtractive torus primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ radius1:
+ Major radius. Must be positive.
+ radius2:
+ Minor radius. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created subtractive torus feature dictionary.
+ """
+ radius1, radius2 = float(radius1), float(radius2)
+ if radius1 <= 0:
+ raise ValueError(f"Torus major radius must be positive, got {radius1}")
+ if radius2 <= 0:
+ raise ValueError(f"Torus minor radius must be positive, got {radius2}")
+ return _subtractive_primitive(project, body_index, "torus", {
+ "radius1": radius1, "radius2": radius2,
+ })
+
+
+def subtractive_wedge(
+ project: Dict[str, Any],
+ body_index: int,
+ xmin: float = 0.0,
+ xmax: float = 10.0,
+ ymin: float = 0.0,
+ ymax: float = 10.0,
+ zmin: float = 0.0,
+ zmax: float = 10.0,
+ x2min: float = 2.0,
+ x2max: float = 8.0,
+ z2min: float = 2.0,
+ z2max: float = 8.0,
+) -> Dict[str, Any]:
+ """Add a subtractive wedge primitive to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ xmin, xmax, ymin, ymax, zmin, zmax:
+ Bounding box extents.
+ x2min, x2max, z2min, z2max:
+ Top face extents.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created subtractive wedge feature dictionary.
+ """
+ return _subtractive_primitive(project, body_index, "wedge", {
+ "xmin": float(xmin), "xmax": float(xmax),
+ "ymin": float(ymin), "ymax": float(ymax),
+ "zmin": float(zmin), "zmax": float(zmax),
+ "x2min": float(x2min), "x2max": float(x2max),
+ "z2min": float(z2min), "z2max": float(z2max),
+ })
+
+
+# ---------------------------------------------------------------------------
+# Dress-up Features
+# ---------------------------------------------------------------------------
+
+
+def draft_feature(
+ project: Dict[str, Any],
+ body_index: int,
+ angle: float,
+ faces: Union[str, List[int]] = "all",
+ pull_direction: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a draft (taper) feature to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ angle:
+ Draft angle in degrees. Must be positive.
+ faces:
+ ``"all"`` to draft every face, or a list of face indices.
+ pull_direction:
+ Pull direction vector ``[x, y, z]``. Defaults to ``[0, 0, 1]``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created draft feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not body["features"]:
+ raise ValueError("Cannot add draft to a body with no existing features")
+
+ angle = float(angle)
+ if angle <= 0:
+ raise ValueError(f"Draft angle must be positive, got {angle}")
+
+ if pull_direction is None:
+ pull_direction = [0, 0, 1]
+ if not isinstance(pull_direction, (list, tuple)) or len(pull_direction) != 3:
+ raise ValueError("pull_direction must be a list of 3 numbers")
+ pull_direction = [float(v) for v in pull_direction]
+
+ if faces != "all":
+ if not isinstance(faces, (list, tuple)):
+ raise ValueError("Faces must be 'all' or a list of face indices")
+ faces = list(faces)
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "draft",
+ "angle": angle,
+ "faces": faces,
+ "pull_direction": pull_direction,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def thickness_feature(
+ project: Dict[str, Any],
+ body_index: int,
+ thickness: float,
+ faces: Union[str, List[int]] = "all",
+ join: str = "arc",
+) -> Dict[str, Any]:
+ """Add a thickness (shell) feature to a body.
+
+ Hollows out the solid, leaving walls of the specified thickness.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ thickness:
+ Wall thickness. Must be positive.
+ faces:
+ ``"all"`` to shell all faces, or a list of face indices to
+ remove (open faces).
+ join:
+ Join type for corners: ``"arc"``, ``"tangent"``, or
+ ``"intersection"``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created thickness feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not body["features"]:
+ raise ValueError("Cannot add thickness to a body with no existing features")
+
+ thickness = float(thickness)
+ if thickness <= 0:
+ raise ValueError(f"Thickness must be positive, got {thickness}")
+
+ valid_joins = {"arc", "tangent", "intersection"}
+ join = join.lower()
+ if join not in valid_joins:
+ raise ValueError(
+ f"Invalid join type '{join}'. Must be one of: {', '.join(sorted(valid_joins))}"
+ )
+
+ if faces != "all":
+ if not isinstance(faces, (list, tuple)):
+ raise ValueError("Faces must be 'all' or a list of face indices")
+ faces = list(faces)
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "thickness",
+ "thickness": thickness,
+ "faces": faces,
+ "join": join,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+# ---------------------------------------------------------------------------
+# Pattern Features
+# ---------------------------------------------------------------------------
+
+
+def linear_pattern(
+ project: Dict[str, Any],
+ body_index: int,
+ direction: Optional[List[float]] = None,
+ length: float = 50.0,
+ occurrences: int = 3,
+) -> Dict[str, Any]:
+ """Add a linear pattern feature to a body.
+
+ Repeats the last feature along a direction.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ direction:
+ Pattern direction vector ``[x, y, z]``. Defaults to ``[1, 0, 0]``.
+ length:
+ Total pattern length. Must be positive.
+ occurrences:
+ Number of occurrences (including the original). Must be >= 2.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created linear pattern feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not body["features"]:
+ raise ValueError("Cannot add linear pattern to a body with no existing features")
+
+ if direction is None:
+ direction = [1, 0, 0]
+ if not isinstance(direction, (list, tuple)) or len(direction) != 3:
+ raise ValueError("Direction must be a list of 3 numbers")
+ direction = [float(v) for v in direction]
+
+ length = float(length)
+ if length <= 0:
+ raise ValueError(f"Pattern length must be positive, got {length}")
+
+ occurrences = int(occurrences)
+ if occurrences < 2:
+ raise ValueError(f"Occurrences must be at least 2, got {occurrences}")
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "linear_pattern",
+ "direction": direction,
+ "length": length,
+ "occurrences": occurrences,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def polar_pattern(
+ project: Dict[str, Any],
+ body_index: int,
+ axis: str = "Z",
+ angle: float = 360.0,
+ occurrences: int = 6,
+) -> Dict[str, Any]:
+ """Add a polar (circular) pattern feature to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ axis:
+ Rotation axis: ``"X"``, ``"Y"``, or ``"Z"``.
+ angle:
+ Total angular span in degrees. Must be in (0, 360].
+ occurrences:
+ Number of occurrences (including the original). Must be >= 2.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created polar pattern feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not body["features"]:
+ raise ValueError("Cannot add polar pattern to a body with no existing features")
+
+ axis = axis.upper()
+ if axis not in VALID_REVOLUTION_AXES:
+ raise ValueError(
+ f"Invalid axis '{axis}'. Must be one of: {', '.join(sorted(VALID_REVOLUTION_AXES))}"
+ )
+
+ angle = float(angle)
+ if angle <= 0 or angle > 360:
+ raise ValueError(f"Pattern angle must be in (0, 360], got {angle}")
+
+ occurrences = int(occurrences)
+ if occurrences < 2:
+ raise ValueError(f"Occurrences must be at least 2, got {occurrences}")
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "polar_pattern",
+ "axis": axis,
+ "angle": angle,
+ "occurrences": occurrences,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def mirrored_feature(
+ project: Dict[str, Any],
+ body_index: int,
+ plane: str = "XY",
+) -> Dict[str, Any]:
+ """Add a mirrored feature to a body.
+
+ Mirrors the last feature across the specified plane.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ plane:
+ Mirror plane: ``"XY"``, ``"XZ"``, or ``"YZ"``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created mirrored feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not body["features"]:
+ raise ValueError("Cannot add mirror to a body with no existing features")
+
+ plane = plane.upper()
+ if plane not in VALID_PATTERN_PLANES:
+ raise ValueError(
+ f"Invalid mirror plane '{plane}'. Must be one of: {', '.join(sorted(VALID_PATTERN_PLANES))}"
+ )
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "mirrored",
+ "plane": plane,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def multi_transform(
+ project: Dict[str, Any],
+ body_index: int,
+ transformations: List[Dict[str, Any]],
+) -> Dict[str, Any]:
+ """Add a multi-transform feature combining multiple pattern operations.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ transformations:
+ List of transformation dictionaries, each describing a pattern
+ operation (e.g. ``{"type": "linear_pattern", "direction": [1,0,0],
+ "length": 50, "occurrences": 3}``).
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created multi-transform feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if not body["features"]:
+ raise ValueError("Cannot add multi-transform to a body with no existing features")
+
+ if not isinstance(transformations, (list, tuple)) or len(transformations) == 0:
+ raise ValueError("Transformations must be a non-empty list of pattern dicts")
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "multi_transform",
+ "transformations": list(transformations),
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+# ---------------------------------------------------------------------------
+# Other Features
+# ---------------------------------------------------------------------------
+
+
+def hole_feature(
+ project: Dict[str, Any],
+ body_index: int,
+ sketch_index: int,
+ diameter: float = 5.0,
+ depth: float = 10.0,
+ threaded: bool = False,
+ thread_pitch: Optional[float] = None,
+) -> Dict[str, Any]:
+ """Add a hole feature to a body based on a sketch with point positions.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ sketch_index:
+ Index of the sketch containing hole center points.
+ diameter:
+ Hole diameter. Must be positive.
+ depth:
+ Hole depth. Must be positive.
+ threaded:
+ If ``True``, create a threaded hole.
+ thread_pitch:
+ Thread pitch (only used when *threaded* is ``True``).
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created hole feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+ sketch = _validate_sketch_index(project, sketch_index)
+
+ if not body["features"]:
+ raise ValueError("Cannot add hole to a body with no existing features")
+
+ diameter = float(diameter)
+ if diameter <= 0:
+ raise ValueError(f"Hole diameter must be positive, got {diameter}")
+
+ depth = float(depth)
+ if depth <= 0:
+ raise ValueError(f"Hole depth must be positive, got {depth}")
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "hole",
+ "sketch_index": sketch_index,
+ "sketch_name": sketch.get("name", f"Sketch {sketch_index}"),
+ "diameter": diameter,
+ "depth": depth,
+ "threaded": bool(threaded),
+ }
+
+ if threaded and thread_pitch is not None:
+ thread_pitch = float(thread_pitch)
+ if thread_pitch <= 0:
+ raise ValueError(f"Thread pitch must be positive, got {thread_pitch}")
+ feature["thread_pitch"] = thread_pitch
+
+ body["features"].append(feature)
+ return feature
+
+
+def datum_plane(
+ project: Dict[str, Any],
+ body_index: int,
+ offset: float = 0.0,
+ reference: str = "XY",
+) -> Dict[str, Any]:
+ """Add a datum plane to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ offset:
+ Offset distance from the reference plane.
+ reference:
+ Reference plane: ``"XY"``, ``"XZ"``, or ``"YZ"``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created datum plane feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ reference = reference.upper()
+ if reference not in VALID_PATTERN_PLANES:
+ raise ValueError(
+ f"Invalid reference plane '{reference}'. "
+ f"Must be one of: {', '.join(sorted(VALID_PATTERN_PLANES))}"
+ )
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "datum_plane",
+ "offset": float(offset),
+ "reference": reference,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def datum_line(
+ project: Dict[str, Any],
+ body_index: int,
+ point: Optional[List[float]] = None,
+ direction: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a datum line to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ point:
+ Base point ``[x, y, z]``. Defaults to ``[0, 0, 0]``.
+ direction:
+ Direction vector ``[x, y, z]``. Defaults to ``[0, 0, 1]``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created datum line feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if point is None:
+ point = [0, 0, 0]
+ if not isinstance(point, (list, tuple)) or len(point) != 3:
+ raise ValueError("Point must be a list of 3 numbers")
+ point = [float(v) for v in point]
+
+ if direction is None:
+ direction = [0, 0, 1]
+ if not isinstance(direction, (list, tuple)) or len(direction) != 3:
+ raise ValueError("Direction must be a list of 3 numbers")
+ direction = [float(v) for v in direction]
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "datum_line",
+ "point": point,
+ "direction": direction,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def datum_point(
+ project: Dict[str, Any],
+ body_index: int,
+ position: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a datum point to a body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ position:
+ Point position ``[x, y, z]``. Defaults to ``[0, 0, 0]``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created datum point feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+
+ if position is None:
+ position = [0, 0, 0]
+ if not isinstance(position, (list, tuple)) or len(position) != 3:
+ raise ValueError("Position must be a list of 3 numbers")
+ position = [float(v) for v in position]
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "datum_point",
+ "position": position,
+ }
+
+ body["features"].append(feature)
+ return feature
+
+
+def shape_binder(
+ project: Dict[str, Any],
+ body_index: int,
+ source_body_index: int,
+ feature_ref: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Add a shape binder referencing geometry from another body.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ body_index:
+ Index of the target body.
+ source_body_index:
+ Index of the source body containing the geometry to bind.
+ feature_ref:
+ Optional feature reference identifier in the source body
+ (e.g. ``"Pad"``). If ``None``, binds the entire shape.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created shape binder feature dictionary.
+ """
+ _validate_project(project)
+ body = _get_body(project, body_index)
+ _get_body(project, source_body_index) # validate source exists
+
+ if body_index == source_body_index:
+ raise ValueError("Shape binder source and target bodies must be different")
+
+ feature: Dict[str, Any] = {
+ "id": _next_feature_id(body),
+ "type": "shape_binder",
+ "source_body_index": source_body_index,
+ "feature_ref": feature_ref,
+ }
+
+ body["features"].append(feature)
+ return feature
diff --git a/freecad/agent-harness/cli_anything/freecad/core/cam.py b/freecad/agent-harness/cli_anything/freecad/core/cam.py
new file mode 100644
index 000000000..cd1d6ca83
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/cam.py
@@ -0,0 +1,501 @@
+"""FreeCAD CLI - CAM/CNC module.
+
+Manages CAM jobs, stock definitions, tool configurations, machining
+operations (profile, pocket, drilling, facing), G-code generation,
+simulation, and export on a JSON-based project state.
+"""
+
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Set
+
+from .document import ensure_collection
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+VALID_STOCK_TYPES: Set[str] = {"box", "cylinder", "from_part"}
+VALID_TOOL_TYPES: Set[str] = {"endmill", "ballnose", "drill", "chamfer", "vbit", "facemill"}
+
+_COLLECTION_KEY = "cam_jobs"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _next_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for CAM jobs."""
+ items = project.get(_COLLECTION_KEY, [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str) -> str:
+ """Return a unique name derived from *base* inside the jobs list."""
+ existing = {item["name"] for item in project.get(_COLLECTION_KEY, [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _get_job(project: Dict[str, Any], job_index: int) -> Dict[str, Any]:
+ """Internal accessor with bounds checking."""
+ items = ensure_collection(project, _COLLECTION_KEY)
+ if not isinstance(job_index, int) or job_index < 0 or job_index >= len(items):
+ raise IndexError(
+ f"Job index {job_index} out of range (0..{len(items) - 1})"
+ )
+ return items[job_index]
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+def new_job(
+ project: Dict[str, Any],
+ part_index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a new CAM job for a part and append it to the project.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ part_index : int
+ Index of the source part in ``project["parts"]``.
+ name : str or None
+ Human-readable label. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created job dictionary.
+
+ Raises
+ ------
+ IndexError
+ If *part_index* is out of range.
+ """
+ items = ensure_collection(project, _COLLECTION_KEY)
+
+ parts = project.get("parts", [])
+ if not isinstance(part_index, int) or part_index < 0 or part_index >= len(parts):
+ raise IndexError(
+ f"Part index {part_index} out of range (0..{len(parts) - 1})"
+ )
+
+ if name is None:
+ name = _unique_name(project, "Job")
+
+ job: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "source_part_index": part_index,
+ "stock": None,
+ "tools": [],
+ "operations": [],
+ "gcode": None,
+ }
+
+ items.append(job)
+ return job
+
+
+def set_stock(
+ project: Dict[str, Any],
+ job_index: int,
+ stock_type: str = "box",
+ extra_x: float = 2.0,
+ extra_y: float = 2.0,
+ extra_z: float = 2.0,
+) -> Dict[str, Any]:
+ """Define the raw stock material for a CAM job.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ job_index : int
+ Index of the target job.
+ stock_type : str
+ Stock shape type (``"box"``, ``"cylinder"``, ``"from_part"``).
+ extra_x : float
+ Extra material on the X axis (each side).
+ extra_y : float
+ Extra material on the Y axis (each side).
+ extra_z : float
+ Extra material on the Z axis (each side).
+
+ Returns
+ -------
+ dict
+ The stock definition.
+
+ Raises
+ ------
+ ValueError
+ If *stock_type* is unknown.
+ """
+ if stock_type not in VALID_STOCK_TYPES:
+ valid = ", ".join(sorted(VALID_STOCK_TYPES))
+ raise ValueError(f"Unknown stock_type '{stock_type}'. Valid: {valid}")
+
+ job = _get_job(project, job_index)
+
+ stock: Dict[str, Any] = {
+ "type": stock_type,
+ "extra_x": float(extra_x),
+ "extra_y": float(extra_y),
+ "extra_z": float(extra_z),
+ }
+
+ job["stock"] = stock
+ return stock
+
+
+def add_profile_op(
+ project: Dict[str, Any],
+ job_index: int,
+ faces: str = "all",
+ depth: Optional[float] = None,
+ step_down: float = 1.0,
+) -> Dict[str, Any]:
+ """Add a profile (contour) machining operation.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ job_index : int
+ Index of the target job.
+ faces : str
+ Face selection (``"all"`` or specific face references).
+ depth : float or None
+ Total cut depth. When *None*, derived from part geometry.
+ step_down : float
+ Depth of cut per pass.
+
+ Returns
+ -------
+ dict
+ The operation entry.
+ """
+ job = _get_job(project, job_index)
+
+ op: Dict[str, Any] = {
+ "type": "profile",
+ "faces": faces,
+ "depth": float(depth) if depth is not None else None,
+ "step_down": float(step_down),
+ }
+
+ job["operations"].append(op)
+ return op
+
+
+def add_pocket_op(
+ project: Dict[str, Any],
+ job_index: int,
+ faces: str = "all",
+ depth: Optional[float] = None,
+ step_down: float = 1.0,
+ step_over: float = 0.5,
+) -> Dict[str, Any]:
+ """Add a pocket machining operation.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ job_index : int
+ Index of the target job.
+ faces : str
+ Face selection (``"all"`` or specific face references).
+ depth : float or None
+ Total pocket depth. When *None*, derived from part geometry.
+ step_down : float
+ Depth of cut per pass.
+ step_over : float
+ Lateral step-over as a fraction of tool diameter (0.0 to 1.0).
+
+ Returns
+ -------
+ dict
+ The operation entry.
+ """
+ job = _get_job(project, job_index)
+
+ op: Dict[str, Any] = {
+ "type": "pocket",
+ "faces": faces,
+ "depth": float(depth) if depth is not None else None,
+ "step_down": float(step_down),
+ "step_over": float(step_over),
+ }
+
+ job["operations"].append(op)
+ return op
+
+
+def add_drilling_op(
+ project: Dict[str, Any],
+ job_index: int,
+ holes: str = "all",
+ depth: Optional[float] = None,
+ peck_depth: Optional[float] = None,
+) -> Dict[str, Any]:
+ """Add a drilling operation.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ job_index : int
+ Index of the target job.
+ holes : str
+ Hole selection (``"all"`` or specific hole references).
+ depth : float or None
+ Total drill depth. When *None*, derived from part geometry.
+ peck_depth : float or None
+ Peck drilling increment. When *None*, drilling is continuous.
+
+ Returns
+ -------
+ dict
+ The operation entry.
+ """
+ job = _get_job(project, job_index)
+
+ op: Dict[str, Any] = {
+ "type": "drilling",
+ "holes": holes,
+ "depth": float(depth) if depth is not None else None,
+ "peck_depth": float(peck_depth) if peck_depth is not None else None,
+ }
+
+ job["operations"].append(op)
+ return op
+
+
+def add_facing_op(
+ project: Dict[str, Any],
+ job_index: int,
+ depth: float = 1.0,
+ step_over: float = 0.5,
+) -> Dict[str, Any]:
+ """Add a facing (surface levelling) operation.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ job_index : int
+ Index of the target job.
+ depth : float
+ Total material to remove from the top surface.
+ step_over : float
+ Lateral step-over as a fraction of tool diameter (0.0 to 1.0).
+
+ Returns
+ -------
+ dict
+ The operation entry.
+ """
+ job = _get_job(project, job_index)
+
+ op: Dict[str, Any] = {
+ "type": "facing",
+ "depth": float(depth),
+ "step_over": float(step_over),
+ }
+
+ job["operations"].append(op)
+ return op
+
+
+def set_tool(
+ project: Dict[str, Any],
+ job_index: int,
+ tool_number: int = 1,
+ diameter: float = 6.0,
+ flutes: int = 2,
+ type: str = "endmill",
+) -> Dict[str, Any]:
+ """Define or replace a cutting tool in a CAM job.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ job_index : int
+ Index of the target job.
+ tool_number : int
+ Tool number in the tool table (T1, T2, etc.).
+ diameter : float
+ Tool diameter in project units.
+ flutes : int
+ Number of cutting flutes.
+ type : str
+ Tool type (``"endmill"``, ``"ballnose"``, ``"drill"``, etc.).
+
+ Returns
+ -------
+ dict
+ The tool entry.
+
+ Raises
+ ------
+ ValueError
+ If *type* is unknown.
+ """
+ if type not in VALID_TOOL_TYPES:
+ valid = ", ".join(sorted(VALID_TOOL_TYPES))
+ raise ValueError(f"Unknown tool type '{type}'. Valid: {valid}")
+
+ job = _get_job(project, job_index)
+
+ tool: Dict[str, Any] = {
+ "tool_number": int(tool_number),
+ "diameter": float(diameter),
+ "flutes": int(flutes),
+ "type": type,
+ }
+
+ # Replace existing tool with same number, or append
+ for i, existing in enumerate(job["tools"]):
+ if existing["tool_number"] == tool_number:
+ job["tools"][i] = tool
+ return tool
+
+ job["tools"].append(tool)
+ return tool
+
+
+def generate_gcode(
+ project: Dict[str, Any],
+ job_index: int,
+) -> Dict[str, Any]:
+ """Record metadata for G-code generation.
+
+ The actual G-code generation is performed by the generated FreeCAD
+ macro. This function validates the job setup and stores generation
+ metadata.
+
+ Returns
+ -------
+ dict
+ G-code generation metadata.
+
+ Raises
+ ------
+ ValueError
+ If the job is missing required setup (stock, tools, operations).
+ """
+ job = _get_job(project, job_index)
+
+ if job["stock"] is None:
+ raise ValueError("Job has no stock defined (call set_stock first)")
+
+ if not job["tools"]:
+ raise ValueError("Job has no tools defined (call set_tool first)")
+
+ if not job["operations"]:
+ raise ValueError("Job has no operations defined")
+
+ job["gcode"] = {
+ "status": "pending",
+ "operations_count": len(job["operations"]),
+ "tools_count": len(job["tools"]),
+ }
+
+ return job["gcode"]
+
+
+def simulate_job(
+ project: Dict[str, Any],
+ job_index: int,
+) -> Dict[str, Any]:
+ """Simulate a CAM job and return estimated metrics.
+
+ This is a rough estimation based on the number and type of
+ operations. Actual simulation runs inside FreeCAD.
+
+ Returns
+ -------
+ dict
+ Simulation summary with estimated time and material removal.
+ """
+ job = _get_job(project, job_index)
+
+ if not job["operations"]:
+ raise ValueError("Job has no operations to simulate")
+
+ # Rough time estimation per operation type (seconds)
+ time_estimates = {
+ "profile": 120.0,
+ "pocket": 300.0,
+ "drilling": 60.0,
+ "facing": 180.0,
+ }
+
+ total_time = 0.0
+ for op in job["operations"]:
+ total_time += time_estimates.get(op["type"], 120.0)
+
+ return {
+ "job_name": job["name"],
+ "operations_count": len(job["operations"]),
+ "tools_used": len(job["tools"]),
+ "estimated_time_seconds": total_time,
+ "material_removal": "estimated",
+ }
+
+
+def export_gcode(
+ project: Dict[str, Any],
+ job_index: int,
+ path: str,
+) -> Dict[str, Any]:
+ """Record metadata for exporting G-code to a file.
+
+ The actual export is performed by the generated FreeCAD macro.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ job_index : int
+ Index of the target job.
+ path : str
+ Output file path for the G-code.
+
+ Returns
+ -------
+ dict
+ Export metadata.
+
+ Raises
+ ------
+ ValueError
+ If *path* is invalid.
+ """
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError("Path must be a non-empty string")
+
+ job = _get_job(project, job_index)
+
+ return {
+ "action": "export_gcode",
+ "job_name": job["name"],
+ "job_index": job_index,
+ "path": path.strip(),
+ "format": "gcode",
+ }
diff --git a/freecad/agent-harness/cli_anything/freecad/core/document.py b/freecad/agent-harness/cli_anything/freecad/core/document.py
new file mode 100644
index 000000000..67bc7b91b
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/document.py
@@ -0,0 +1,306 @@
+"""
+Document and project management for the FreeCAD CLI harness.
+
+Provides creation, loading, saving, and inspection of JSON-based
+FreeCAD project files, along with a set of predefined unit/workflow profiles.
+"""
+
+import json
+import os
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+
+SOFTWARE_VERSION = "cli-anything-freecad 1.0.0"
+PROJECT_SCHEMA_VERSION = "1.0"
+
+# ---------------------------------------------------------------------------
+# Profiles
+# ---------------------------------------------------------------------------
+
+PROFILES: Dict[str, Dict[str, Any]] = {
+ "default": {
+ "description": "Default profile with millimetre units",
+ "units": "mm",
+ },
+ "metric_small": {
+ "description": "Metric profile for small parts",
+ "units": "mm",
+ },
+ "metric_large": {
+ "description": "Metric profile for architectural / large-scale work",
+ "units": "m",
+ },
+ "imperial": {
+ "description": "Imperial profile with inch units",
+ "units": "in",
+ },
+ "print3d": {
+ "description": "Profile oriented for 3D printing workflows",
+ "units": "mm",
+ },
+ "cnc": {
+ "description": "Precision-focused profile for CNC machining",
+ "units": "mm",
+ },
+}
+
+VALID_UNITS = {"mm", "m", "in"}
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _now_iso() -> str:
+ """Return the current local time as an ISO-8601 string."""
+ return datetime.now().isoformat()
+
+
+# All collection keys that can exist in a project. The first four are
+# required for backward compatibility; the rest are lazily initialised.
+_REQUIRED_COLLECTIONS = ("parts", "sketches", "bodies", "materials")
+_OPTIONAL_COLLECTIONS = (
+ "assemblies", "meshes", "techdraw_pages", "draft_objects",
+ "measurements", "surfaces", "fem_analyses", "cam_jobs", "spreadsheets",
+)
+ALL_COLLECTIONS = _REQUIRED_COLLECTIONS + _OPTIONAL_COLLECTIONS
+
+
+def ensure_collection(project: Dict[str, Any], key: str) -> list:
+ """Return ``project[key]``, creating it as ``[]`` if absent."""
+ if key not in project:
+ project[key] = []
+ return project[key]
+
+
+def _validate_project(project: Dict[str, Any]) -> None:
+ """Raise ``ValueError`` if *project* is missing required keys or has bad types."""
+ required_keys = {"version", "name", "units", "parts", "sketches", "bodies", "materials", "metadata"}
+ missing = required_keys - set(project.keys())
+ if missing:
+ raise ValueError(f"Project is missing required keys: {', '.join(sorted(missing))}")
+
+ if not isinstance(project["name"], str) or not project["name"]:
+ raise ValueError("Project 'name' must be a non-empty string")
+
+ if project["units"] not in VALID_UNITS:
+ raise ValueError(f"Invalid units '{project['units']}'. Must be one of: {', '.join(sorted(VALID_UNITS))}")
+
+ for collection in _REQUIRED_COLLECTIONS:
+ if not isinstance(project[collection], list):
+ raise ValueError(f"Project '{collection}' must be a list")
+
+ # Optional collections: validate type if present, but don't require
+ for collection in _OPTIONAL_COLLECTIONS:
+ if collection in project and not isinstance(project[collection], list):
+ raise ValueError(f"Project '{collection}' must be a list")
+
+ if not isinstance(project.get("metadata"), dict):
+ raise ValueError("Project 'metadata' must be a dict")
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def create_document(
+ name: str = "Untitled",
+ units: str = "mm",
+ profile: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a new project document.
+
+ Parameters
+ ----------
+ name:
+ Human-readable project name.
+ units:
+ Unit system (``"mm"``, ``"m"``, or ``"in"``). Overridden by
+ *profile* when a profile is supplied.
+ profile:
+ Optional profile key from :data:`PROFILES`. When given, the
+ profile's ``units`` value takes precedence over the *units*
+ argument.
+
+ Returns
+ -------
+ Dict[str, Any]
+ A new project dictionary ready for use.
+
+ Raises
+ ------
+ ValueError
+ If *name* is empty, *units* is invalid, or *profile* is unknown.
+ """
+ if not isinstance(name, str) or not name.strip():
+ raise ValueError("Document name must be a non-empty string")
+
+ if profile is not None:
+ if profile not in PROFILES:
+ raise ValueError(
+ f"Unknown profile '{profile}'. Available profiles: {', '.join(sorted(PROFILES))}"
+ )
+ units = PROFILES[profile]["units"]
+
+ if units not in VALID_UNITS:
+ raise ValueError(f"Invalid units '{units}'. Must be one of: {', '.join(sorted(VALID_UNITS))}")
+
+ now = _now_iso()
+
+ project: Dict[str, Any] = {
+ "version": PROJECT_SCHEMA_VERSION,
+ "name": name.strip(),
+ "units": units,
+ "parts": [],
+ "sketches": [],
+ "bodies": [],
+ "materials": [],
+ "assemblies": [],
+ "meshes": [],
+ "techdraw_pages": [],
+ "draft_objects": [],
+ "measurements": [],
+ "surfaces": [],
+ "fem_analyses": [],
+ "cam_jobs": [],
+ "spreadsheets": [],
+ "metadata": {
+ "created": now,
+ "modified": now,
+ "software": SOFTWARE_VERSION,
+ },
+ }
+ return project
+
+
+def open_document(path: str) -> Dict[str, Any]:
+ """Load a project document from a JSON file.
+
+ Parameters
+ ----------
+ path:
+ Filesystem path to the ``.json`` project file.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The validated project dictionary.
+
+ Raises
+ ------
+ FileNotFoundError
+ If *path* does not exist.
+ ValueError
+ If the file cannot be parsed or fails validation.
+ """
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError("Path must be a non-empty string")
+
+ if not os.path.isfile(path):
+ raise FileNotFoundError(f"Project file not found: {path}")
+
+ try:
+ with open(path, "r", encoding="utf-8") as fh:
+ project = json.load(fh)
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"Failed to parse project file: {exc}") from exc
+
+ if not isinstance(project, dict):
+ raise ValueError("Project file must contain a JSON object at the top level")
+
+ _validate_project(project)
+ return project
+
+
+def save_document(project: Dict[str, Any], path: str) -> str:
+ """Save a project document to a JSON file.
+
+ The ``metadata.modified`` timestamp is updated automatically before
+ writing.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary to persist.
+ path:
+ Destination file path.
+
+ Returns
+ -------
+ str
+ The absolute path of the saved file.
+
+ Raises
+ ------
+ ValueError
+ If the project fails validation or *path* is invalid.
+ OSError
+ If the file cannot be written.
+ """
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError("Path must be a non-empty string")
+
+ _validate_project(project)
+
+ project["metadata"]["modified"] = _now_iso()
+
+ dir_name = os.path.dirname(path)
+ if dir_name:
+ os.makedirs(dir_name, exist_ok=True)
+
+ with open(path, "w", encoding="utf-8") as fh:
+ json.dump(project, fh, indent=2, ensure_ascii=False)
+
+ return os.path.abspath(path)
+
+
+def get_document_info(project: Dict[str, Any]) -> Dict[str, Any]:
+ """Return a concise summary of a project document.
+
+ Parameters
+ ----------
+ project:
+ A valid project dictionary.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Summary containing name, units, and collection counts.
+
+ Raises
+ ------
+ ValueError
+ If the project fails validation.
+ """
+ _validate_project(project)
+
+ info = {
+ "name": project["name"],
+ "units": project["units"],
+ "version": project["version"],
+ }
+ for col in ALL_COLLECTIONS:
+ info[f"{col}_count"] = len(project.get(col, []))
+ info["metadata"] = project.get("metadata", {})
+ return info
+
+
+def list_profiles() -> List[Dict[str, Any]]:
+ """Return a list of available project profiles.
+
+ Each entry contains the profile ``name``, ``units``, and
+ ``description``.
+
+ Returns
+ -------
+ List[Dict[str, Any]]
+ """
+ return [
+ {
+ "name": key,
+ "units": value["units"],
+ "description": value["description"],
+ }
+ for key, value in PROFILES.items()
+ ]
diff --git a/freecad/agent-harness/cli_anything/freecad/core/draft.py b/freecad/agent-harness/cli_anything/freecad/core/draft.py
new file mode 100644
index 000000000..1abb75c9e
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/draft.py
@@ -0,0 +1,1251 @@
+"""FreeCAD CLI - Draft 2D workbench module.
+
+Provides creation, annotation, transformation, array, copy, and modification
+functions for 2D drafting objects. All objects are stored in
+``project["draft_objects"]`` via
+:func:`~cli_anything.freecad.core.document.ensure_collection`.
+"""
+
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Union
+
+from cli_anything.freecad.core.document import ensure_collection
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _next_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for draft objects."""
+ items = project.get("draft_objects", [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str) -> str:
+ """Return a unique name derived from *base* inside ``project["draft_objects"]``."""
+ existing = {item["name"] for item in project.get("draft_objects", [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _validate_vec3(value: Any, label: str) -> List[float]:
+ """Validate that *value* is a list of exactly three numbers."""
+ if not isinstance(value, (list, tuple)):
+ raise ValueError(f"{label} must be a list of 3 numbers, got {type(value).__name__}")
+ if len(value) != 3:
+ raise ValueError(f"{label} must have exactly 3 elements, got {len(value)}")
+ try:
+ return [float(v) for v in value]
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} elements must be numeric: {exc}") from exc
+
+
+def _validate_vec2(value: Any, label: str) -> List[float]:
+ """Validate that *value* is a list of exactly two numbers."""
+ if not isinstance(value, (list, tuple)):
+ raise ValueError(f"{label} must be a list of 2 numbers, got {type(value).__name__}")
+ if len(value) != 2:
+ raise ValueError(f"{label} must have exactly 2 elements, got {len(value)}")
+ try:
+ return [float(v) for v in value]
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} elements must be numeric: {exc}") from exc
+
+
+def _get_draft(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the draft object at *index*, raising ``IndexError`` if out of range."""
+ objs = project.get("draft_objects", [])
+ if not isinstance(index, int) or index < 0 or index >= len(objs):
+ raise IndexError(
+ f"Draft object index {index} out of range (0..{len(objs) - 1})"
+ )
+ return objs[index]
+
+
+def _make_draft(
+ project: Dict[str, Any],
+ obj_type: str,
+ name: Optional[str],
+ properties: Dict[str, Any],
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a draft object, append it, and return it."""
+ objs = ensure_collection(project, "draft_objects")
+
+ if name is None:
+ name = _unique_name(project, obj_type.capitalize())
+
+ pos = _validate_vec3(position, "position") if position is not None else [0.0, 0.0, 0.0]
+ rot = _validate_vec3(rotation, "rotation") if rotation is not None else [0.0, 0.0, 0.0]
+
+ draft_obj: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": obj_type,
+ "properties": properties,
+ "placement": {
+ "position": pos,
+ "rotation": rot,
+ },
+ "visible": True,
+ }
+
+ objs.append(draft_obj)
+ return draft_obj
+
+
+# ---------------------------------------------------------------------------
+# Creation functions (10)
+# ---------------------------------------------------------------------------
+
+
+def draft_wire(
+ project: Dict[str, Any],
+ points: List[List[float]],
+ closed: bool = False,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a polyline (wire) from a list of 3D points.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ points : list[list[float]]
+ Ordered list of ``[x, y, z]`` vertices.
+ closed : bool
+ Whether to close the wire (default ``False``).
+ name : str or None
+ Label for the object.
+ position, rotation : list[float] or None
+ Placement overrides.
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ if not isinstance(points, (list, tuple)) or len(points) < 2:
+ raise ValueError("wire requires at least 2 points")
+ validated = [_validate_vec3(p, f"points[{i}]") for i, p in enumerate(points)]
+ return _make_draft(project, "wire", name, {
+ "points": validated,
+ "closed": bool(closed),
+ }, position, rotation)
+
+
+def draft_rectangle(
+ project: Dict[str, Any],
+ length: float = 10.0,
+ height: float = 10.0,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a 2D rectangle.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ length : float
+ X-dimension (default ``10``).
+ height : float
+ Y-dimension (default ``10``).
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ if length <= 0 or height <= 0:
+ raise ValueError("length and height must be positive numbers")
+ return _make_draft(project, "rectangle", name, {
+ "length": float(length),
+ "height": float(height),
+ }, position, rotation)
+
+
+def draft_circle(
+ project: Dict[str, Any],
+ radius: float = 5.0,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a 2D circle.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ radius : float
+ Circle radius (default ``5``).
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ if radius <= 0:
+ raise ValueError("radius must be a positive number")
+ return _make_draft(project, "circle", name, {
+ "radius": float(radius),
+ }, position, rotation)
+
+
+def draft_ellipse(
+ project: Dict[str, Any],
+ major_radius: float = 10.0,
+ minor_radius: float = 5.0,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a 2D ellipse.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ major_radius : float
+ Semi-major axis (default ``10``).
+ minor_radius : float
+ Semi-minor axis (default ``5``).
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ if major_radius <= 0 or minor_radius <= 0:
+ raise ValueError("major_radius and minor_radius must be positive")
+ if minor_radius > major_radius:
+ raise ValueError("minor_radius must not exceed major_radius")
+ return _make_draft(project, "ellipse", name, {
+ "major_radius": float(major_radius),
+ "minor_radius": float(minor_radius),
+ }, position, rotation)
+
+
+def draft_polygon(
+ project: Dict[str, Any],
+ sides: int = 6,
+ radius: float = 5.0,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a regular polygon.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ sides : int
+ Number of sides (default ``6``). Must be >= 3.
+ radius : float
+ Circumscribed radius (default ``5``).
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ if not isinstance(sides, int) or sides < 3:
+ raise ValueError("sides must be an integer >= 3")
+ if radius <= 0:
+ raise ValueError("radius must be a positive number")
+ return _make_draft(project, "polygon", name, {
+ "sides": sides,
+ "radius": float(radius),
+ }, position, rotation)
+
+
+def draft_bspline(
+ project: Dict[str, Any],
+ points: List[List[float]],
+ closed: bool = False,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a B-spline curve through a list of points.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ points : list[list[float]]
+ Control / through-points (minimum 2).
+ closed : bool
+ Whether to close the spline (default ``False``).
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ if not isinstance(points, (list, tuple)) or len(points) < 2:
+ raise ValueError("bspline requires at least 2 points")
+ validated = [_validate_vec3(p, f"points[{i}]") for i, p in enumerate(points)]
+ return _make_draft(project, "bspline", name, {
+ "points": validated,
+ "closed": bool(closed),
+ }, position, rotation)
+
+
+def draft_bezier(
+ project: Dict[str, Any],
+ points: List[List[float]],
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a Bezier curve from control points.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ points : list[list[float]]
+ Control points (minimum 2).
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ if not isinstance(points, (list, tuple)) or len(points) < 2:
+ raise ValueError("bezier requires at least 2 control points")
+ validated = [_validate_vec3(p, f"points[{i}]") for i, p in enumerate(points)]
+ return _make_draft(project, "bezier", name, {
+ "points": validated,
+ }, position, rotation)
+
+
+def draft_point(
+ project: Dict[str, Any],
+ point: Optional[List[float]] = None,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a single draft point.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ point : list[float] or None
+ ``[x, y, z]`` coordinate. Defaults to ``[0, 0, 0]``.
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ pt = _validate_vec3(point, "point") if point is not None else [0.0, 0.0, 0.0]
+ return _make_draft(project, "point", name, {
+ "point": pt,
+ }, position, rotation)
+
+
+def draft_text(
+ project: Dict[str, Any],
+ text: str,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a draft text annotation.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ text : str
+ The text content to display.
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ if not isinstance(text, str) or not text.strip():
+ raise ValueError("text must be a non-empty string")
+ return _make_draft(project, "text", name, {
+ "text": text.strip(),
+ }, position, rotation)
+
+
+def draft_shapestring(
+ project: Dict[str, Any],
+ text: str,
+ font_file: str,
+ size: float = 10.0,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a ShapeString (text extruded into wire outlines).
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ text : str
+ The text content.
+ font_file : str
+ Path to the TrueType font file.
+ size : float
+ Font height (default ``10``).
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ if not isinstance(text, str) or not text.strip():
+ raise ValueError("text must be a non-empty string")
+ if not isinstance(font_file, str) or not font_file.strip():
+ raise ValueError("font_file must be a non-empty string")
+ if size <= 0:
+ raise ValueError("size must be a positive number")
+ return _make_draft(project, "shapestring", name, {
+ "text": text.strip(),
+ "font_file": font_file.strip(),
+ "size": float(size),
+ }, position, rotation)
+
+
+# ---------------------------------------------------------------------------
+# Annotation functions (3)
+# ---------------------------------------------------------------------------
+
+
+def draft_dimension(
+ project: Dict[str, Any],
+ start: List[float],
+ end: List[float],
+ dim_line: Optional[List[float]] = None,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a linear dimension annotation.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ start : list[float]
+ ``[x, y, z]`` start point.
+ end : list[float]
+ ``[x, y, z]`` end point.
+ dim_line : list[float] or None
+ Point through which the dimension line passes.
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ s = _validate_vec3(start, "start")
+ e = _validate_vec3(end, "end")
+ dl = _validate_vec3(dim_line, "dim_line") if dim_line is not None else [0.0, 0.0, 0.0]
+ return _make_draft(project, "dimension", name, {
+ "start": s,
+ "end": e,
+ "dim_line": dl,
+ }, position, rotation)
+
+
+def draft_label(
+ project: Dict[str, Any],
+ target_point: List[float],
+ text: str = "",
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Create a label annotation pointing to *target_point*.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ target_point : list[float]
+ ``[x, y, z]`` point the label arrow targets.
+ text : str
+ Label text content.
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ tp = _validate_vec3(target_point, "target_point")
+ return _make_draft(project, "label", name, {
+ "target_point": tp,
+ "text": text,
+ }, position, rotation)
+
+
+def draft_hatch(
+ project: Dict[str, Any],
+ target_index: int,
+ pattern: str = "ANSI31",
+ scale: float = 1.0,
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Apply a hatch pattern to a draft object face.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ target_index : int
+ Index of the draft object to hatch.
+ pattern : str
+ Hatch pattern name (default ``"ANSI31"``).
+ scale : float
+ Pattern scale factor (default ``1``).
+
+ Returns
+ -------
+ dict
+ The newly created draft object.
+ """
+ _get_draft(project, target_index) # validate
+ if scale <= 0:
+ raise ValueError("scale must be a positive number")
+ return _make_draft(project, "hatch", name, {
+ "target_index": target_index,
+ "pattern": pattern,
+ "scale": float(scale),
+ }, position, rotation)
+
+
+# ---------------------------------------------------------------------------
+# Transform functions (5)
+# ---------------------------------------------------------------------------
+
+
+def draft_move(
+ project: Dict[str, Any],
+ index: int,
+ vector: List[float],
+ copy: bool = False,
+) -> Dict[str, Any]:
+ """Move a draft object by *vector*, optionally creating a copy.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object.
+ vector : list[float]
+ ``[dx, dy, dz]`` translation vector.
+ copy : bool
+ If ``True`` create a moved copy instead of modifying in-place.
+
+ Returns
+ -------
+ dict
+ The moved (or copied) draft object.
+ """
+ obj = _get_draft(project, index)
+ vec = _validate_vec3(vector, "vector")
+
+ if copy:
+ new_obj = deepcopy(obj)
+ new_obj["id"] = _next_id(project)
+ new_obj["name"] = _unique_name(project, f"{obj['name']}_Copy")
+ pos = new_obj["placement"]["position"]
+ new_obj["placement"]["position"] = [pos[i] + vec[i] for i in range(3)]
+ ensure_collection(project, "draft_objects").append(new_obj)
+ return new_obj
+
+ pos = obj["placement"]["position"]
+ obj["placement"]["position"] = [pos[i] + vec[i] for i in range(3)]
+ return obj
+
+
+def draft_rotate(
+ project: Dict[str, Any],
+ index: int,
+ angle: float,
+ axis: Optional[List[float]] = None,
+ center: Optional[List[float]] = None,
+ copy: bool = False,
+) -> Dict[str, Any]:
+ """Rotate a draft object by *angle* degrees around *axis*.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object.
+ angle : float
+ Rotation angle in degrees.
+ axis : list[float] or None
+ Rotation axis (default Z-axis ``[0, 0, 1]``).
+ center : list[float] or None
+ Center of rotation (default origin).
+ copy : bool
+ If ``True`` create a rotated copy.
+
+ Returns
+ -------
+ dict
+ The rotated (or copied) draft object.
+ """
+ obj = _get_draft(project, index)
+ ax = _validate_vec3(axis, "axis") if axis is not None else [0.0, 0.0, 1.0]
+ ctr = _validate_vec3(center, "center") if center is not None else [0.0, 0.0, 0.0]
+
+ if copy:
+ new_obj = deepcopy(obj)
+ new_obj["id"] = _next_id(project)
+ new_obj["name"] = _unique_name(project, f"{obj['name']}_Copy")
+ rot = new_obj["placement"]["rotation"]
+ new_obj["placement"]["rotation"] = [rot[0], rot[1], rot[2] + float(angle)]
+ ensure_collection(project, "draft_objects").append(new_obj)
+ return new_obj
+
+ obj["placement"]["rotation"] = [
+ obj["placement"]["rotation"][0],
+ obj["placement"]["rotation"][1],
+ obj["placement"]["rotation"][2] + float(angle),
+ ]
+ return obj
+
+
+def draft_scale(
+ project: Dict[str, Any],
+ index: int,
+ scale: Union[float, List[float]] = 2.0,
+ center: Optional[List[float]] = None,
+ copy: bool = False,
+) -> Dict[str, Any]:
+ """Scale a draft object.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object.
+ scale : float or list[float]
+ Uniform scale factor, or ``[sx, sy, sz]`` anisotropic scale.
+ center : list[float] or None
+ Center of scaling (default origin).
+ copy : bool
+ If ``True`` create a scaled copy.
+
+ Returns
+ -------
+ dict
+ The scaled (or copied) draft object.
+ """
+ obj = _get_draft(project, index)
+ ctr = _validate_vec3(center, "center") if center is not None else [0.0, 0.0, 0.0]
+
+ if isinstance(scale, (int, float)):
+ if scale == 0:
+ raise ValueError("scale must be non-zero")
+ scale_vec = [float(scale)] * 3
+ else:
+ scale_vec = _validate_vec3(scale, "scale")
+ if any(s == 0 for s in scale_vec):
+ raise ValueError("scale components must be non-zero")
+
+ if copy:
+ new_obj = deepcopy(obj)
+ new_obj["id"] = _next_id(project)
+ new_obj["name"] = _unique_name(project, f"{obj['name']}_Scaled")
+ new_obj["properties"]["_scale"] = scale_vec
+ new_obj["properties"]["_scale_center"] = ctr
+ ensure_collection(project, "draft_objects").append(new_obj)
+ return new_obj
+
+ obj["properties"]["_scale"] = scale_vec
+ obj["properties"]["_scale_center"] = ctr
+ return obj
+
+
+def draft_mirror(
+ project: Dict[str, Any],
+ index: int,
+ point: Optional[List[float]] = None,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a mirrored copy of a draft object.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object to mirror.
+ point : list[float] or None
+ Mirror reference point (default origin).
+ name : str or None
+ Label for the mirrored copy.
+
+ Returns
+ -------
+ dict
+ The newly created mirrored draft object.
+ """
+ obj = _get_draft(project, index)
+ pt = _validate_vec3(point, "point") if point is not None else [0.0, 0.0, 0.0]
+
+ new_obj = deepcopy(obj)
+ new_obj["id"] = _next_id(project)
+ if name is None:
+ name = _unique_name(project, f"{obj['name']}_Mirror")
+ new_obj["name"] = name
+ new_obj["properties"]["_mirror_point"] = pt
+
+ ensure_collection(project, "draft_objects").append(new_obj)
+ return new_obj
+
+
+def draft_offset(
+ project: Dict[str, Any],
+ index: int,
+ distance: float = 1.0,
+ copy: bool = True,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Offset a draft object by *distance*.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object.
+ distance : float
+ Offset distance (default ``1``).
+ copy : bool
+ If ``True`` (default) create an offset copy.
+ name : str or None
+ Label for the offset copy.
+
+ Returns
+ -------
+ dict
+ The offset draft object.
+ """
+ obj = _get_draft(project, index)
+ if distance == 0:
+ raise ValueError("distance must be non-zero")
+
+ if copy:
+ new_obj = deepcopy(obj)
+ new_obj["id"] = _next_id(project)
+ if name is None:
+ name = _unique_name(project, f"{obj['name']}_Offset")
+ new_obj["name"] = name
+ new_obj["properties"]["_offset_distance"] = float(distance)
+ ensure_collection(project, "draft_objects").append(new_obj)
+ return new_obj
+
+ obj["properties"]["_offset_distance"] = float(distance)
+ return obj
+
+
+# ---------------------------------------------------------------------------
+# Array functions (3)
+# ---------------------------------------------------------------------------
+
+
+def draft_array_linear(
+ project: Dict[str, Any],
+ index: int,
+ x_count: int = 2,
+ y_count: int = 1,
+ x_interval: float = 20.0,
+ y_interval: float = 20.0,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a linear (rectangular) array of a draft object.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the source draft object.
+ x_count : int
+ Number of copies along X (default ``2``).
+ y_count : int
+ Number of copies along Y (default ``1``).
+ x_interval : float
+ Spacing along X (default ``20``).
+ y_interval : float
+ Spacing along Y (default ``20``).
+
+ Returns
+ -------
+ dict
+ The newly created array draft object.
+ """
+ obj = _get_draft(project, index)
+ if x_count < 1 or y_count < 1:
+ raise ValueError("x_count and y_count must be >= 1")
+ return _make_draft(project, "array_linear", name, {
+ "source_id": obj["id"],
+ "x_count": int(x_count),
+ "y_count": int(y_count),
+ "x_interval": float(x_interval),
+ "y_interval": float(y_interval),
+ })
+
+
+def draft_array_polar(
+ project: Dict[str, Any],
+ index: int,
+ count: int = 6,
+ angle: float = 360.0,
+ center: Optional[List[float]] = None,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a polar (circular) array of a draft object.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the source draft object.
+ count : int
+ Number of copies (default ``6``).
+ angle : float
+ Total sweep angle in degrees (default ``360``).
+ center : list[float] or None
+ Center of the array (default origin).
+
+ Returns
+ -------
+ dict
+ The newly created array draft object.
+ """
+ obj = _get_draft(project, index)
+ if count < 2:
+ raise ValueError("count must be >= 2")
+ ctr = _validate_vec3(center, "center") if center is not None else [0.0, 0.0, 0.0]
+ return _make_draft(project, "array_polar", name, {
+ "source_id": obj["id"],
+ "count": int(count),
+ "angle": float(angle),
+ "center": ctr,
+ })
+
+
+def draft_array_path(
+ project: Dict[str, Any],
+ index: int,
+ path_index: int,
+ count: int = 4,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create an array of a draft object along a path.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the source draft object.
+ path_index : int
+ Index of the path draft object (wire, bspline, etc.).
+ count : int
+ Number of copies along the path (default ``4``).
+
+ Returns
+ -------
+ dict
+ The newly created array draft object.
+ """
+ obj = _get_draft(project, index)
+ path_obj = _get_draft(project, path_index)
+ if count < 2:
+ raise ValueError("count must be >= 2")
+ return _make_draft(project, "array_path", name, {
+ "source_id": obj["id"],
+ "path_id": path_obj["id"],
+ "count": int(count),
+ })
+
+
+# ---------------------------------------------------------------------------
+# Copy functions (2)
+# ---------------------------------------------------------------------------
+
+
+def draft_copy(
+ project: Dict[str, Any],
+ index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a simple copy of a draft object.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object to copy.
+ name : str or None
+ Label for the copy.
+
+ Returns
+ -------
+ dict
+ The newly created copy.
+ """
+ obj = _get_draft(project, index)
+ new_obj = deepcopy(obj)
+ new_obj["id"] = _next_id(project)
+ if name is None:
+ name = _unique_name(project, f"{obj['name']}_Copy")
+ new_obj["name"] = name
+
+ ensure_collection(project, "draft_objects").append(new_obj)
+ return new_obj
+
+
+def draft_clone(
+ project: Dict[str, Any],
+ index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a clone (linked copy) of a draft object.
+
+ Unlike :func:`draft_copy`, a clone maintains a parametric reference
+ to the source object.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the source draft object.
+ name : str or None
+ Label for the clone.
+
+ Returns
+ -------
+ dict
+ The newly created clone draft object.
+ """
+ obj = _get_draft(project, index)
+ if name is None:
+ name = _unique_name(project, f"{obj['name']}_Clone")
+ return _make_draft(project, "clone", name, {
+ "source_id": obj["id"],
+ })
+
+
+# ---------------------------------------------------------------------------
+# Modify functions (7)
+# ---------------------------------------------------------------------------
+
+
+def draft_upgrade(
+ project: Dict[str, Any],
+ index: int,
+) -> Dict[str, Any]:
+ """Upgrade a draft object (e.g. wires -> face).
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object to upgrade.
+
+ Returns
+ -------
+ dict
+ The updated draft object.
+ """
+ obj = _get_draft(project, index)
+ obj["properties"]["_upgraded"] = True
+ return obj
+
+
+def draft_downgrade(
+ project: Dict[str, Any],
+ index: int,
+) -> Dict[str, Any]:
+ """Downgrade a draft object (e.g. face -> wires).
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object to downgrade.
+
+ Returns
+ -------
+ dict
+ The updated draft object.
+ """
+ obj = _get_draft(project, index)
+ obj["properties"]["_downgraded"] = True
+ return obj
+
+
+def draft_trim(
+ project: Dict[str, Any],
+ index: int,
+ point: List[float],
+) -> Dict[str, Any]:
+ """Trim a draft object at the given point.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object to trim.
+ point : list[float]
+ ``[x, y, z]`` trim location.
+
+ Returns
+ -------
+ dict
+ The updated draft object.
+ """
+ obj = _get_draft(project, index)
+ pt = _validate_vec3(point, "point")
+ obj["properties"]["_trim_point"] = pt
+ return obj
+
+
+def draft_join(
+ project: Dict[str, Any],
+ indices: List[int],
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Join multiple draft wires into one.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ indices : list[int]
+ Indices of the draft objects to join.
+ name : str or None
+ Label for the joined result.
+
+ Returns
+ -------
+ dict
+ The newly created joined draft object.
+
+ Raises
+ ------
+ ValueError
+ If fewer than two indices are provided.
+ """
+ if not isinstance(indices, (list, tuple)) or len(indices) < 2:
+ raise ValueError("At least two draft object indices are required for join")
+ source_ids = []
+ for idx in indices:
+ obj = _get_draft(project, idx)
+ source_ids.append(obj["id"])
+ return _make_draft(project, "join", name, {
+ "source_ids": source_ids,
+ })
+
+
+def draft_extrude(
+ project: Dict[str, Any],
+ index: int,
+ vector: Optional[List[float]] = None,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Extrude a 2D draft object into a 3D solid along *vector*.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object to extrude.
+ vector : list[float] or None
+ Extrusion direction and magnitude (default ``[0, 0, 10]``).
+ name : str or None
+ Label for the extruded result.
+
+ Returns
+ -------
+ dict
+ The newly created extrusion draft object.
+ """
+ obj = _get_draft(project, index)
+ vec = _validate_vec3(vector, "vector") if vector is not None else [0.0, 0.0, 10.0]
+ return _make_draft(project, "extrude", name, {
+ "source_id": obj["id"],
+ "vector": vec,
+ })
+
+
+def draft_fillet_2d(
+ project: Dict[str, Any],
+ index: int,
+ radius: float = 1.0,
+) -> Dict[str, Any]:
+ """Apply a 2D fillet (rounding) to the vertices of a draft object.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object.
+ radius : float
+ Fillet radius (default ``1``).
+
+ Returns
+ -------
+ dict
+ The updated draft object.
+ """
+ if radius <= 0:
+ raise ValueError("radius must be a positive number")
+ obj = _get_draft(project, index)
+ obj["properties"]["_fillet_radius"] = float(radius)
+ return obj
+
+
+def draft_to_sketch(
+ project: Dict[str, Any],
+ index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Convert a draft object to a sketch in ``project["sketches"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object to convert.
+ name : str or None
+ Label for the resulting sketch.
+
+ Returns
+ -------
+ dict
+ The newly created sketch entry.
+ """
+ obj = _get_draft(project, index)
+ sketches = ensure_collection(project, "sketches")
+
+ if name is None:
+ base = f"{obj['name']}_Sketch"
+ existing = {s["name"] for s in sketches}
+ if base in existing:
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ base = f"{base}_{counter}"
+ name = base
+
+ sketch_id = max((s["id"] for s in sketches), default=0) + 1
+
+ sketch: Dict[str, Any] = {
+ "id": sketch_id,
+ "name": name,
+ "type": "from_draft",
+ "source_draft_id": obj["id"],
+ "elements": [],
+ "constraints": [],
+ }
+
+ sketches.append(sketch)
+ return sketch
+
+
+# ---------------------------------------------------------------------------
+# Manage functions (3)
+# ---------------------------------------------------------------------------
+
+
+def list_draft_objects(project: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return all draft objects in the project.
+
+ Parameters
+ ----------
+ project : dict
+ The project state dictionary.
+
+ Returns
+ -------
+ list[dict]
+ List of draft object dictionaries.
+ """
+ return project.get("draft_objects", [])
+
+
+def get_draft_object(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the draft object at *index* without removing it.
+
+ Parameters
+ ----------
+ project : dict
+ The project state dictionary.
+ index : int
+ Index of the draft object.
+
+ Returns
+ -------
+ dict
+ The draft object dictionary.
+ """
+ return _get_draft(project, index)
+
+
+def remove_draft_object(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Remove and return the draft object at *index*.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the draft object to remove.
+
+ Returns
+ -------
+ dict
+ The removed draft object.
+ """
+ objs = project.get("draft_objects", [])
+ if not isinstance(index, int) or index < 0 or index >= len(objs):
+ raise IndexError(
+ f"Draft object index {index} out of range (0..{len(objs) - 1})"
+ )
+ return objs.pop(index)
diff --git a/freecad/agent-harness/cli_anything/freecad/core/export.py b/freecad/agent-harness/cli_anything/freecad/core/export.py
new file mode 100644
index 000000000..1317e94a8
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/export.py
@@ -0,0 +1,391 @@
+"""
+Export module for the FreeCAD CLI harness.
+
+Handles rendering and exporting FreeCAD projects using the real FreeCAD
+headless backend, including generating macro scripts from project JSON
+state and converting to various CAD/mesh output formats.
+"""
+
+from __future__ import annotations
+
+import os
+import struct
+import zipfile
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from cli_anything.freecad.utils.freecad_macro_gen import generate_macro
+from cli_anything.freecad.utils import freecad_backend
+
+# ---------------------------------------------------------------------------
+# Export preset definitions
+# ---------------------------------------------------------------------------
+
+EXPORT_PRESETS: Dict[str, Dict[str, Any]] = {
+ "step": {
+ "format": "step",
+ "description": "STEP AP214 (ISO 10303)",
+ },
+ "iges": {
+ "format": "iges",
+ "description": "IGES format",
+ },
+ "stl": {
+ "format": "stl",
+ "description": "STL mesh (3D printing)",
+ },
+ "stl_fine": {
+ "format": "stl",
+ "mesh_deviation": 0.01,
+ "description": "Fine STL mesh",
+ },
+ "obj": {
+ "format": "obj",
+ "description": "Wavefront OBJ",
+ },
+ "brep": {
+ "format": "brep",
+ "description": "OpenCASCADE BREP",
+ },
+ "fcstd": {
+ "format": "fcstd",
+ "description": "Native FreeCAD document",
+ },
+ "dxf": {
+ "format": "dxf",
+ "description": "AutoCAD DXF format",
+ },
+ "svg": {
+ "format": "svg",
+ "description": "Scalable Vector Graphics",
+ },
+ "gltf": {
+ "format": "gltf",
+ "description": "GL Transmission Format",
+ },
+ "3mf": {
+ "format": "3mf",
+ "description": "3D Manufacturing Format",
+ },
+ "ply": {
+ "format": "ply",
+ "description": "Polygon File Format",
+ },
+ "off": {
+ "format": "off",
+ "description": "Object File Format",
+ },
+ "amf": {
+ "format": "amf",
+ "description": "Additive Manufacturing Format",
+ },
+ "pdf": {
+ "format": "pdf",
+ "description": "PDF via TechDraw",
+ },
+ "png": {
+ "format": "png",
+ "description": "Rendered PNG image",
+ },
+ "jpg": {
+ "format": "jpg",
+ "description": "Rendered JPG image",
+ },
+}
+
+# Map format names to canonical file extensions
+_FORMAT_EXTENSIONS: Dict[str, str] = {
+ "step": ".step",
+ "iges": ".iges",
+ "stl": ".stl",
+ "obj": ".obj",
+ "brep": ".brep",
+ "fcstd": ".FCStd",
+ "dxf": ".dxf",
+ "svg": ".svg",
+ "gltf": ".gltf",
+ "3mf": ".3mf",
+ "ply": ".ply",
+ "off": ".off",
+ "amf": ".amf",
+ "pdf": ".pdf",
+ "png": ".png",
+ "jpg": ".jpg",
+}
+
+
+# ---------------------------------------------------------------------------
+# Format validation helpers
+# ---------------------------------------------------------------------------
+
+
+def _validate_step(path: str) -> bool:
+ """Check that *path* starts with the ISO-10303-21 header marker."""
+ try:
+ with open(path, "r", encoding="utf-8", errors="ignore") as fh:
+ header = fh.read(64)
+ return header.strip().startswith("ISO-10303-21")
+ except OSError:
+ return False
+
+
+def _validate_stl(path: str) -> bool:
+ """Check for ASCII STL (``solid`` keyword) or valid binary STL header.
+
+ A binary STL has an 80-byte header followed by a 4-byte little-endian
+ triangle count. An ASCII STL starts with the word ``solid``.
+ """
+ try:
+ with open(path, "rb") as fh:
+ head = fh.read(80)
+ if not head:
+ return False
+ # ASCII STL check
+ text_head = head.decode("ascii", errors="ignore").strip().lower()
+ if text_head.startswith("solid"):
+ return True
+ # Binary STL: 80-byte header + 4-byte uint32 triangle count
+ with open(path, "rb") as fh:
+ fh.seek(80)
+ count_bytes = fh.read(4)
+ if len(count_bytes) == 4:
+ _tri_count = struct.unpack("<I", count_bytes)[0]
+ return True
+ return False
+ except OSError:
+ return False
+
+
+def _validate_iges(path: str) -> bool:
+ """Check for IGES header markers in the first few lines.
+
+ IGES files have fixed-width 80-column records. The 73rd column of
+ the first record should contain ``S`` (Start section).
+ """
+ try:
+ with open(path, "r", encoding="utf-8", errors="ignore") as fh:
+ first_line = fh.readline()
+ if not first_line:
+ return False
+ # The 73rd character (index 72) should be 'S' for the start section
+ if len(first_line) >= 73 and first_line[72] == "S":
+ return True
+ # Fallback: look for common IGES keywords
+ upper = first_line.upper()
+ return "IGES" in upper or "INITIAL GRAPHICS" in upper
+ except OSError:
+ return False
+
+
+def _validate_dxf(path: str) -> bool:
+ """Check that *path* contains DXF section markers."""
+ try:
+ with open(path, "r", encoding="utf-8", errors="ignore") as fh:
+ header = fh.read(256)
+ return "0\nSECTION" in header or "AutoCAD" in header
+ except OSError:
+ return False
+
+
+def _validate_svg(path: str) -> bool:
+ """Check that *path* contains SVG or XML markers."""
+ try:
+ with open(path, "r", encoding="utf-8", errors="ignore") as fh:
+ header = fh.read(256)
+ return "<svg" in header.lower() or "<?xml" in header.lower()
+ except OSError:
+ return False
+
+
+def _validate_pdf(path: str) -> bool:
+ """Check that *path* starts with the ``%PDF-`` header."""
+ try:
+ with open(path, "rb") as fh:
+ header = fh.read(8)
+ return header.startswith(b"%PDF-")
+ except OSError:
+ return False
+
+
+def _validate_gltf(path: str) -> bool:
+ """Check for glTF binary magic bytes or JSON with ``asset`` key."""
+ try:
+ with open(path, "rb") as fh:
+ magic = fh.read(4)
+ # Binary glTF magic: "glTF"
+ if magic == b"glTF":
+ return True
+ # JSON-based glTF
+ with open(path, "r", encoding="utf-8", errors="ignore") as fh:
+ header = fh.read(512)
+ return '"asset"' in header
+ except OSError:
+ return False
+
+
+def _validate_3mf(path: str) -> bool:
+ """Check that *path* is a ZIP archive containing ``3D/3dmodel.model``."""
+ try:
+ if not zipfile.is_zipfile(path):
+ return False
+ with zipfile.ZipFile(path, "r") as zf:
+ return "3D/3dmodel.model" in zf.namelist()
+ except (OSError, zipfile.BadZipFile):
+ return False
+
+
+_FORMAT_VALIDATORS: Dict[str, Any] = {
+ "step": _validate_step,
+ "iges": _validate_iges,
+ "stl": _validate_stl,
+ "dxf": _validate_dxf,
+ "svg": _validate_svg,
+ "pdf": _validate_pdf,
+ "gltf": _validate_gltf,
+ "3mf": _validate_3mf,
+}
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def export_project(
+ project: dict,
+ output_path: str,
+ preset: str = "step",
+ overwrite: bool = False,
+) -> Dict[str, Any]:
+ """Export a FreeCAD project to a CAD/mesh file.
+
+ 1. Generates a FreeCAD macro script via :func:`generate_macro`.
+ 2. Calls :func:`freecad_backend.run_macro` to execute it headlessly.
+ 3. Verifies the output file exists and has the correct format.
+
+ Parameters
+ ----------
+ project : dict
+ The project JSON state containing parts, bodies, and placements.
+ output_path : str
+ Destination file path for the exported geometry.
+ preset : str
+ Name of an export preset (see ``EXPORT_PRESETS``).
+ overwrite : bool
+ If *False* (default), raise ``FileExistsError`` when *output_path*
+ already exists.
+
+ Returns
+ -------
+ dict
+ ``{"output": str, "format": str, "file_size": int,
+ "method": "freecad-headless"}``
+
+ Raises
+ ------
+ FileExistsError
+ If *output_path* exists and *overwrite* is False.
+ ValueError
+ If *preset* is not a known preset name.
+ RuntimeError
+ If the macro execution fails or the output file is missing/invalid.
+ """
+ output_path = os.path.abspath(output_path)
+
+ if not overwrite and os.path.exists(output_path):
+ raise FileExistsError(
+ f"Output file already exists: {output_path}. "
+ "Set overwrite=True to replace it."
+ )
+
+ if preset not in EXPORT_PRESETS:
+ raise ValueError(
+ f"Unknown export preset '{preset}'. "
+ f"Available presets: {', '.join(sorted(EXPORT_PRESETS))}"
+ )
+
+ preset_config = EXPORT_PRESETS[preset]
+ export_format = preset_config["format"]
+
+ # Ensure output directory exists
+ os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
+
+ # Generate the FreeCAD macro script
+ macro_content = generate_macro(project, output_path, export_format=export_format)
+
+ # Execute via the headless backend
+ result = freecad_backend.export_headless(
+ macro_content, output_path, timeout=120,
+ )
+
+ # Verify the output file
+ if not os.path.isfile(output_path):
+ raise RuntimeError(
+ f"Export failed: output file was not created at {output_path}. "
+ f"Backend result: {result}"
+ )
+
+ # Run format-specific validation if available
+ validator = _FORMAT_VALIDATORS.get(export_format)
+ if validator and not validator(output_path):
+ raise RuntimeError(
+ f"Export produced an invalid {export_format.upper()} file at "
+ f"{output_path}. The file header does not match the expected format."
+ )
+
+ ext = _FORMAT_EXTENSIONS.get(export_format, f".{export_format}")
+ file_size = os.path.getsize(output_path)
+
+ return {
+ "output": output_path,
+ "format": ext.lstrip("."),
+ "file_size": file_size,
+ "method": "freecad-headless",
+ }
+
+
+def get_export_info(project: dict) -> Dict[str, Any]:
+ """Return a summary of what will be exported from *project*.
+
+ Parameters
+ ----------
+ project : dict
+ The project JSON state.
+
+ Returns
+ -------
+ dict
+ Summary with keys ``part_count``, ``body_count``,
+ ``boolean_op_count``, ``available_presets``, and ``part_names``.
+ """
+ parts = project.get("parts", [])
+ bodies = project.get("bodies", [])
+ boolean_ops = project.get("boolean_ops", [])
+
+ part_names = [p.get("name", "Unnamed") for p in parts]
+
+ return {
+ "part_count": len(parts),
+ "body_count": len(bodies),
+ "boolean_op_count": len(boolean_ops),
+ "part_names": part_names,
+ "available_presets": list(EXPORT_PRESETS.keys()),
+ }
+
+
+def list_presets() -> List[Dict[str, str]]:
+ """Return a list of available export presets with descriptions.
+
+ Returns
+ -------
+ list[dict]
+ Each entry has ``name``, ``format``, and ``description`` keys.
+ """
+ return [
+ {
+ "name": name,
+ "format": cfg["format"],
+ "description": cfg["description"],
+ }
+ for name, cfg in EXPORT_PRESETS.items()
+ ]
diff --git a/freecad/agent-harness/cli_anything/freecad/core/fem.py b/freecad/agent-harness/cli_anything/freecad/core/fem.py
new file mode 100644
index 000000000..fa86a7f82
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/fem.py
@@ -0,0 +1,555 @@
+"""FreeCAD CLI - FEM (Finite Element Method) analysis module.
+
+Manages FEM analyses, boundary constraints (fixed, force, pressure,
+displacement, temperature, heat flux), material assignment, meshing,
+solving, and result export on a JSON-based project state.
+"""
+
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Set
+
+from .document import ensure_collection
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+VALID_ELEMENT_TYPES: Set[str] = {"Tet4", "Tet10", "Hex8", "Hex20", "Tri3", "Tri6"}
+VALID_SOLVERS: Set[str] = {"calculix", "elmer", "z88"}
+VALID_EXPORT_FORMATS: Set[str] = {"vtk", "csv", "json"}
+
+_COLLECTION_KEY = "fem_analyses"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _next_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for FEM analyses."""
+ items = project.get(_COLLECTION_KEY, [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str) -> str:
+ """Return a unique name derived from *base* inside the analyses list."""
+ existing = {item["name"] for item in project.get(_COLLECTION_KEY, [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _validate_vec3(value: Any, label: str) -> List[float]:
+ """Validate that *value* is a list of exactly three numbers."""
+ if not isinstance(value, (list, tuple)):
+ raise ValueError(f"{label} must be a list of 3 numbers, got {type(value).__name__}")
+ if len(value) != 3:
+ raise ValueError(f"{label} must have exactly 3 elements, got {len(value)}")
+ try:
+ return [float(v) for v in value]
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} elements must be numeric: {exc}") from exc
+
+
+def _get_analysis(project: Dict[str, Any], ai: int) -> Dict[str, Any]:
+ """Internal accessor with bounds checking.
+
+ Parameters
+ ----------
+ ai : int
+ Analysis index.
+ """
+ items = ensure_collection(project, _COLLECTION_KEY)
+ if not isinstance(ai, int) or ai < 0 or ai >= len(items):
+ raise IndexError(
+ f"Analysis index {ai} out of range (0..{len(items) - 1})"
+ )
+ return items[ai]
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+def new_analysis(
+ project: Dict[str, Any],
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a new FEM analysis and append it to the project.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ name : str or None
+ Human-readable label. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created analysis dictionary.
+ """
+ items = ensure_collection(project, _COLLECTION_KEY)
+
+ if name is None:
+ name = _unique_name(project, "FEMAnalysis")
+
+ analysis: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "constraints": [],
+ "material_index": None,
+ "mesh_params": None,
+ "solver": None,
+ "results": None,
+ }
+
+ items.append(analysis)
+ return analysis
+
+
+def add_fixed_constraint(
+ project: Dict[str, Any],
+ ai: int,
+ references: List[Any],
+) -> Dict[str, Any]:
+ """Add a fixed (zero-displacement) boundary constraint.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ references : list
+ Geometry references (faces, edges, vertices) to fix.
+
+ Returns
+ -------
+ dict
+ The constraint entry.
+ """
+ analysis = _get_analysis(project, ai)
+
+ constraint: Dict[str, Any] = {
+ "type": "fixed",
+ "references": list(references),
+ }
+
+ analysis["constraints"].append(constraint)
+ return constraint
+
+
+def add_force_constraint(
+ project: Dict[str, Any],
+ ai: int,
+ references: List[Any],
+ magnitude: float,
+ direction: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a force constraint to the analysis.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ references : list
+ Geometry references where the force is applied.
+ magnitude : float
+ Force magnitude in Newtons.
+ direction : list[float] or None
+ Force direction vector ``[x, y, z]``. Defaults to ``[0, 0, -1]``.
+
+ Returns
+ -------
+ dict
+ The constraint entry.
+ """
+ analysis = _get_analysis(project, ai)
+
+ if direction is not None:
+ direction = _validate_vec3(direction, "direction")
+ else:
+ direction = [0.0, 0.0, -1.0]
+
+ constraint: Dict[str, Any] = {
+ "type": "force",
+ "references": list(references),
+ "magnitude": float(magnitude),
+ "direction": direction,
+ }
+
+ analysis["constraints"].append(constraint)
+ return constraint
+
+
+def add_pressure_constraint(
+ project: Dict[str, Any],
+ ai: int,
+ references: List[Any],
+ pressure: float,
+) -> Dict[str, Any]:
+ """Add a pressure constraint to the analysis.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ references : list
+ Geometry references (faces) where pressure is applied.
+ pressure : float
+ Pressure value in MPa.
+
+ Returns
+ -------
+ dict
+ The constraint entry.
+ """
+ analysis = _get_analysis(project, ai)
+
+ constraint: Dict[str, Any] = {
+ "type": "pressure",
+ "references": list(references),
+ "pressure": float(pressure),
+ }
+
+ analysis["constraints"].append(constraint)
+ return constraint
+
+
+def add_displacement_constraint(
+ project: Dict[str, Any],
+ ai: int,
+ references: List[Any],
+ displacement: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a prescribed displacement constraint.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ references : list
+ Geometry references where the displacement is prescribed.
+ displacement : list[float] or None
+ Displacement vector ``[dx, dy, dz]``. Defaults to ``[0, 0, 0]``.
+
+ Returns
+ -------
+ dict
+ The constraint entry.
+ """
+ analysis = _get_analysis(project, ai)
+
+ if displacement is not None:
+ displacement = _validate_vec3(displacement, "displacement")
+ else:
+ displacement = [0.0, 0.0, 0.0]
+
+ constraint: Dict[str, Any] = {
+ "type": "displacement",
+ "references": list(references),
+ "displacement": displacement,
+ }
+
+ analysis["constraints"].append(constraint)
+ return constraint
+
+
+def add_temperature_constraint(
+ project: Dict[str, Any],
+ ai: int,
+ references: List[Any],
+ temperature: float,
+) -> Dict[str, Any]:
+ """Add a temperature boundary constraint.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ references : list
+ Geometry references where temperature is fixed.
+ temperature : float
+ Temperature value in Kelvin.
+
+ Returns
+ -------
+ dict
+ The constraint entry.
+ """
+ analysis = _get_analysis(project, ai)
+
+ constraint: Dict[str, Any] = {
+ "type": "temperature",
+ "references": list(references),
+ "temperature": float(temperature),
+ }
+
+ analysis["constraints"].append(constraint)
+ return constraint
+
+
+def add_heatflux_constraint(
+ project: Dict[str, Any],
+ ai: int,
+ references: List[Any],
+ flux: float,
+) -> Dict[str, Any]:
+ """Add a heat flux boundary constraint.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ references : list
+ Geometry references where the heat flux is applied.
+ flux : float
+ Heat flux value in W/m^2.
+
+ Returns
+ -------
+ dict
+ The constraint entry.
+ """
+ analysis = _get_analysis(project, ai)
+
+ constraint: Dict[str, Any] = {
+ "type": "heatflux",
+ "references": list(references),
+ "flux": float(flux),
+ }
+
+ analysis["constraints"].append(constraint)
+ return constraint
+
+
+def set_fem_material(
+ project: Dict[str, Any],
+ ai: int,
+ material_index: int,
+) -> Dict[str, Any]:
+ """Assign a material from the project's materials list to an analysis.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ material_index : int
+ Index into ``project["materials"]``.
+
+ Returns
+ -------
+ dict
+ The updated analysis dictionary.
+
+ Raises
+ ------
+ IndexError
+ If *material_index* is out of range.
+ """
+ analysis = _get_analysis(project, ai)
+
+ materials = project.get("materials", [])
+ if not isinstance(material_index, int) or material_index < 0 or material_index >= len(materials):
+ raise IndexError(
+ f"Material index {material_index} out of range (0..{len(materials) - 1})"
+ )
+
+ analysis["material_index"] = material_index
+ return analysis
+
+
+def generate_fem_mesh(
+ project: Dict[str, Any],
+ ai: int,
+ max_size: Optional[float] = None,
+ min_size: Optional[float] = None,
+ element_type: str = "Tet10",
+) -> Dict[str, Any]:
+ """Configure mesh generation parameters for an analysis.
+
+ The actual mesh generation is performed by the generated FreeCAD
+ macro. This function stores the meshing parameters.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ max_size : float or None
+ Maximum element size. When *None*, FreeCAD uses automatic sizing.
+ min_size : float or None
+ Minimum element size. When *None*, FreeCAD uses automatic sizing.
+ element_type : str
+ Element type (e.g. ``"Tet4"``, ``"Tet10"``, ``"Hex8"``).
+
+ Returns
+ -------
+ dict
+ The mesh parameters dictionary.
+
+ Raises
+ ------
+ ValueError
+ If *element_type* is unknown.
+ """
+ if element_type not in VALID_ELEMENT_TYPES:
+ valid = ", ".join(sorted(VALID_ELEMENT_TYPES))
+ raise ValueError(
+ f"Unknown element_type '{element_type}'. Valid: {valid}"
+ )
+
+ analysis = _get_analysis(project, ai)
+
+ mesh_params: Dict[str, Any] = {
+ "max_size": float(max_size) if max_size is not None else None,
+ "min_size": float(min_size) if min_size is not None else None,
+ "element_type": element_type,
+ }
+
+ analysis["mesh_params"] = mesh_params
+ return mesh_params
+
+
+def solve_fem(
+ project: Dict[str, Any],
+ ai: int,
+ solver: str = "calculix",
+) -> Dict[str, Any]:
+ """Configure the FEM solver for an analysis.
+
+ The actual solving is performed by the generated FreeCAD macro.
+ This function stores the solver configuration and validates that
+ the analysis has the minimum required setup.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ solver : str
+ Solver backend name (``"calculix"``, ``"elmer"``, ``"z88"``).
+
+ Returns
+ -------
+ dict
+ Solver configuration summary.
+
+ Raises
+ ------
+ ValueError
+ If *solver* is unknown or the analysis is missing constraints
+ or mesh parameters.
+ """
+ if solver not in VALID_SOLVERS:
+ valid = ", ".join(sorted(VALID_SOLVERS))
+ raise ValueError(f"Unknown solver '{solver}'. Valid: {valid}")
+
+ analysis = _get_analysis(project, ai)
+
+ if not analysis["constraints"]:
+ raise ValueError("Analysis has no constraints defined")
+
+ if analysis["mesh_params"] is None:
+ raise ValueError(
+ "Mesh parameters must be set before solving "
+ "(call generate_fem_mesh first)"
+ )
+
+ analysis["solver"] = solver
+ analysis["results"] = {
+ "status": "pending",
+ "solver": solver,
+ "constraints_count": len(analysis["constraints"]),
+ }
+
+ return analysis["results"]
+
+
+def get_fem_results(
+ project: Dict[str, Any],
+ ai: int,
+) -> Dict[str, Any]:
+ """Return the results of an analysis.
+
+ Returns
+ -------
+ dict
+ The results dictionary, or a status indicator if not yet solved.
+ """
+ analysis = _get_analysis(project, ai)
+
+ if analysis["results"] is None:
+ return {"status": "not_run", "message": "Analysis has not been solved yet"}
+
+ return analysis["results"]
+
+
+def export_fem_results(
+ project: Dict[str, Any],
+ ai: int,
+ path: str,
+ format: str = "vtk",
+) -> Dict[str, Any]:
+ """Record metadata for exporting FEM results.
+
+ The actual export is performed by the generated FreeCAD macro.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ ai : int
+ Analysis index.
+ path : str
+ Output file path.
+ format : str
+ Export format (``"vtk"``, ``"csv"``, ``"json"``).
+
+ Returns
+ -------
+ dict
+ Export metadata.
+
+ Raises
+ ------
+ ValueError
+ If *format* is unknown or *path* is invalid.
+ """
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError("Path must be a non-empty string")
+
+ if format not in VALID_EXPORT_FORMATS:
+ valid = ", ".join(sorted(VALID_EXPORT_FORMATS))
+ raise ValueError(f"Unknown format '{format}'. Valid: {valid}")
+
+ analysis = _get_analysis(project, ai)
+
+ return {
+ "action": "export_fem_results",
+ "analysis_name": analysis["name"],
+ "analysis_index": ai,
+ "path": path.strip(),
+ "format": format,
+ }
diff --git a/freecad/agent-harness/cli_anything/freecad/core/import_mod.py b/freecad/agent-harness/cli_anything/freecad/core/import_mod.py
new file mode 100644
index 000000000..5c70c3a4e
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/import_mod.py
@@ -0,0 +1,596 @@
+"""FreeCAD CLI - Import module.
+
+Provides functions for importing geometry files in various formats into
+the project state. Depending on the format, imported geometry is added
+to ``project["parts"]``, ``project["meshes"]``, or
+``project["draft_objects"]``.
+
+Named ``import_mod`` to avoid collision with the Python ``import`` keyword.
+"""
+
+import os
+from typing import Any, Dict, Optional, Set
+
+from cli_anything.freecad.core.document import ensure_collection
+
+# ---------------------------------------------------------------------------
+# Format classification
+# ---------------------------------------------------------------------------
+
+#: Formats that produce solid/BREP parts.
+PART_FORMATS: Set[str] = {"step", "stp", "iges", "igs", "brep", "brp"}
+
+#: Formats that produce triangle meshes.
+MESH_FORMATS: Set[str] = {"stl", "obj", "ply", "off", "3mf", "amf", "gltf", "glb"}
+
+#: Formats that produce 2D draft / mixed objects.
+DRAFT_FORMATS: Set[str] = {"dxf", "svg"}
+
+#: Extension -> canonical format name mapping.
+EXT_MAP: Dict[str, str] = {
+ ".step": "step",
+ ".stp": "step",
+ ".iges": "iges",
+ ".igs": "iges",
+ ".stl": "stl",
+ ".obj": "obj",
+ ".dxf": "dxf",
+ ".svg": "svg",
+ ".brep": "brep",
+ ".brp": "brep",
+ ".3mf": "3mf",
+ ".ply": "ply",
+ ".off": "off",
+ ".gltf": "gltf",
+ ".glb": "gltf",
+}
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _validate_path(path: str, label: str = "path") -> str:
+ """Validate that *path* is a non-empty string and return it stripped."""
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError(f"{label} must be a non-empty string")
+ return path.strip()
+
+
+def _detect_format(path: str) -> str:
+ """Detect the canonical format from a file extension.
+
+ Returns
+ -------
+ str
+ The canonical format key (e.g. ``"step"``, ``"stl"``).
+
+ Raises
+ ------
+ ValueError
+ If the extension is not recognised.
+ """
+ ext = os.path.splitext(path)[1].lower()
+ if ext not in EXT_MAP:
+ raise ValueError(
+ f"Cannot detect format from extension '{ext}'. "
+ f"Supported extensions: {', '.join(sorted(EXT_MAP))}"
+ )
+ return EXT_MAP[ext]
+
+
+def _next_part_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for parts."""
+ items = project.get("parts", [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _next_mesh_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for meshes."""
+ items = project.get("meshes", [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _next_draft_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for draft objects."""
+ items = project.get("draft_objects", [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str, key: str) -> str:
+ """Return a unique name derived from *base* inside ``project[key]``."""
+ existing = {item["name"] for item in project.get(key, [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _default_name(path: str, name: Optional[str], project: Dict[str, Any], key: str) -> str:
+ """Derive a name from *path* if *name* is None, then make it unique."""
+ if name is not None:
+ return name
+ base = os.path.splitext(os.path.basename(path))[0]
+ return _unique_name(project, base, key)
+
+
+# ---------------------------------------------------------------------------
+# Internal import builders
+# ---------------------------------------------------------------------------
+
+
+def _import_as_part(
+ project: Dict[str, Any],
+ path: str,
+ fmt: str,
+ name: Optional[str] = None,
+ import_params: Optional[Dict[str, Any]] = None,
+) -> Dict[str, Any]:
+ """Create an imported part entry in ``project["parts"]``."""
+ parts = ensure_collection(project, "parts")
+ label = _default_name(path, name, project, "parts")
+
+ part: Dict[str, Any] = {
+ "id": _next_part_id(project),
+ "name": label,
+ "type": "imported",
+ "params": {
+ "source_path": path,
+ "source_format": fmt,
+ "import_params": import_params or {},
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ parts.append(part)
+ return part
+
+
+def _import_as_mesh(
+ project: Dict[str, Any],
+ path: str,
+ fmt: str,
+ name: Optional[str] = None,
+ import_params: Optional[Dict[str, Any]] = None,
+) -> Dict[str, Any]:
+ """Create an imported mesh entry in ``project["meshes"]``."""
+ meshes = ensure_collection(project, "meshes")
+ label = _default_name(path, name, project, "meshes")
+
+ mesh: Dict[str, Any] = {
+ "id": _next_mesh_id(project),
+ "name": label,
+ "source": path,
+ "format": fmt,
+ "vertices_count": 0,
+ "faces_count": 0,
+ "operations_applied": [],
+ }
+
+ meshes.append(mesh)
+ return mesh
+
+
+def _import_as_draft(
+ project: Dict[str, Any],
+ path: str,
+ fmt: str,
+ name: Optional[str] = None,
+ import_params: Optional[Dict[str, Any]] = None,
+) -> Dict[str, Any]:
+ """Create an imported draft object entry in ``project["draft_objects"]``."""
+ objs = ensure_collection(project, "draft_objects")
+ label = _default_name(path, name, project, "draft_objects")
+
+ draft_obj: Dict[str, Any] = {
+ "id": _next_draft_id(project),
+ "name": label,
+ "type": "imported",
+ "properties": {
+ "source_path": path,
+ "source_format": fmt,
+ "import_params": import_params or {},
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "visible": True,
+ }
+
+ objs.append(draft_obj)
+ return draft_obj
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def import_file(
+ project: Dict[str, Any],
+ path: str,
+ format: Optional[str] = None,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import a file, auto-detecting the format from its extension.
+
+ Depending on the detected format the imported geometry is placed in
+ ``project["parts"]``, ``project["meshes"]``, or
+ ``project["draft_objects"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Filesystem path to the file.
+ format : str or None
+ Explicit format override. When *None* the format is detected
+ from the file extension.
+ name : str or None
+ Label for the imported object. Derived from filename when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created import entry.
+
+ Raises
+ ------
+ ValueError
+ If the format cannot be detected or is unsupported.
+ """
+ path = _validate_path(path)
+ fmt = format.lower() if format else _detect_format(path)
+
+ if fmt in PART_FORMATS or fmt in {"step", "iges", "brep"}:
+ return _import_as_part(project, path, fmt, name)
+ elif fmt in MESH_FORMATS:
+ return _import_as_mesh(project, path, fmt, name)
+ elif fmt in DRAFT_FORMATS:
+ return _import_as_draft(project, path, fmt, name)
+ else:
+ raise ValueError(
+ f"Unsupported format '{fmt}'. Supported: "
+ f"{', '.join(sorted(PART_FORMATS | MESH_FORMATS | DRAFT_FORMATS))}"
+ )
+
+
+def import_step(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import a STEP file into ``project["parts"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the STEP file.
+ name : str or None
+ Label for the imported part.
+
+ Returns
+ -------
+ dict
+ The newly created part entry.
+ """
+ path = _validate_path(path)
+ return _import_as_part(project, path, "step", name)
+
+
+def import_iges(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import an IGES file into ``project["parts"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the IGES file.
+ name : str or None
+ Label for the imported part.
+
+ Returns
+ -------
+ dict
+ The newly created part entry.
+ """
+ path = _validate_path(path)
+ return _import_as_part(project, path, "iges", name)
+
+
+def import_stl(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import an STL file into ``project["meshes"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the STL file.
+ name : str or None
+ Label for the imported mesh.
+
+ Returns
+ -------
+ dict
+ The newly created mesh entry.
+ """
+ path = _validate_path(path)
+ return _import_as_mesh(project, path, "stl", name)
+
+
+def import_obj(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import an OBJ file into ``project["meshes"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the OBJ file.
+ name : str or None
+ Label for the imported mesh.
+
+ Returns
+ -------
+ dict
+ The newly created mesh entry.
+ """
+ path = _validate_path(path)
+ return _import_as_mesh(project, path, "obj", name)
+
+
+def import_dxf(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import a DXF file into ``project["draft_objects"]`` or ``project["parts"]``.
+
+ DXF files primarily contain 2D geometry and are imported as draft
+ objects by default.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the DXF file.
+ name : str or None
+ Label for the imported object.
+
+ Returns
+ -------
+ dict
+ The newly created draft object entry.
+ """
+ path = _validate_path(path)
+ return _import_as_draft(project, path, "dxf", name)
+
+
+def import_svg(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import an SVG file into ``project["draft_objects"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the SVG file.
+ name : str or None
+ Label for the imported object.
+
+ Returns
+ -------
+ dict
+ The newly created draft object entry.
+ """
+ path = _validate_path(path)
+ return _import_as_draft(project, path, "svg", name)
+
+
+def import_brep(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import a BREP file into ``project["parts"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the BREP file.
+ name : str or None
+ Label for the imported part.
+
+ Returns
+ -------
+ dict
+ The newly created part entry.
+ """
+ path = _validate_path(path)
+ return _import_as_part(project, path, "brep", name)
+
+
+def import_3mf(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import a 3MF file into ``project["meshes"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the 3MF file.
+ name : str or None
+ Label for the imported mesh.
+
+ Returns
+ -------
+ dict
+ The newly created mesh entry.
+ """
+ path = _validate_path(path)
+ return _import_as_mesh(project, path, "3mf", name)
+
+
+def import_ply(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import a PLY file into ``project["meshes"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the PLY file.
+ name : str or None
+ Label for the imported mesh.
+
+ Returns
+ -------
+ dict
+ The newly created mesh entry.
+ """
+ path = _validate_path(path)
+ return _import_as_mesh(project, path, "ply", name)
+
+
+def import_off(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import an OFF file into ``project["meshes"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the OFF file.
+ name : str or None
+ Label for the imported mesh.
+
+ Returns
+ -------
+ dict
+ The newly created mesh entry.
+ """
+ path = _validate_path(path)
+ return _import_as_mesh(project, path, "off", name)
+
+
+def import_gltf(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import a glTF/GLB file into ``project["meshes"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Path to the glTF or GLB file.
+ name : str or None
+ Label for the imported mesh.
+
+ Returns
+ -------
+ dict
+ The newly created mesh entry.
+ """
+ path = _validate_path(path)
+ return _import_as_mesh(project, path, "gltf", name)
+
+
+def import_info(path: str) -> Dict[str, Any]:
+ """Preview file metadata without modifying any project.
+
+ Returns information about the file including size, detected format,
+ and estimated object count. Does **not** require a project dict.
+
+ Parameters
+ ----------
+ path : str
+ Filesystem path to the file.
+
+ Returns
+ -------
+ dict
+ Metadata dictionary with keys ``path``, ``format``,
+ ``size_bytes``, ``exists``, and ``estimated_objects``.
+
+ Raises
+ ------
+ ValueError
+ If *path* is empty or the format is unrecognised.
+ """
+ path = _validate_path(path)
+ fmt = _detect_format(path)
+
+ exists = os.path.isfile(path)
+ size = os.path.getsize(path) if exists else 0
+
+ # Classify destination
+ if fmt in PART_FORMATS:
+ target = "parts"
+ elif fmt in MESH_FORMATS:
+ target = "meshes"
+ elif fmt in DRAFT_FORMATS:
+ target = "draft_objects"
+ else:
+ target = "unknown"
+
+ return {
+ "path": path,
+ "format": fmt,
+ "size_bytes": size,
+ "exists": exists,
+ "estimated_objects": 1,
+ "target_collection": target,
+ }
diff --git a/freecad/agent-harness/cli_anything/freecad/core/materials.py b/freecad/agent-harness/cli_anything/freecad/core/materials.py
new file mode 100644
index 000000000..3abb6a749
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/materials.py
@@ -0,0 +1,647 @@
+"""
+Materials module for the FreeCAD CLI harness.
+
+Provides material creation, assignment, and management with a library of
+physically-based rendering presets for common engineering materials.
+"""
+
+import json
+from typing import Any, Dict, List, Optional
+
+
+# ---------------------------------------------------------------------------
+# Material presets
+# ---------------------------------------------------------------------------
+
+PRESETS: Dict[str, Dict[str, Any]] = {
+ "steel": {
+ "color": [0.7, 0.7, 0.75, 1.0],
+ "metallic": 0.9,
+ "roughness": 0.3,
+ },
+ "aluminum": {
+ "color": [0.8, 0.8, 0.85, 1.0],
+ "metallic": 0.9,
+ "roughness": 0.2,
+ },
+ "copper": {
+ "color": [0.72, 0.45, 0.2, 1.0],
+ "metallic": 1.0,
+ "roughness": 0.25,
+ },
+ "brass": {
+ "color": [0.78, 0.68, 0.35, 1.0],
+ "metallic": 0.9,
+ "roughness": 0.3,
+ },
+ "plastic_white": {
+ "color": [0.95, 0.95, 0.95, 1.0],
+ "metallic": 0.0,
+ "roughness": 0.4,
+ },
+ "plastic_black": {
+ "color": [0.1, 0.1, 0.1, 1.0],
+ "metallic": 0.0,
+ "roughness": 0.5,
+ },
+ "wood": {
+ "color": [0.55, 0.35, 0.15, 1.0],
+ "metallic": 0.0,
+ "roughness": 0.7,
+ },
+ "glass": {
+ "color": [0.85, 0.9, 0.95, 0.3],
+ "metallic": 0.0,
+ "roughness": 0.05,
+ },
+ "rubber": {
+ "color": [0.15, 0.15, 0.15, 1.0],
+ "metallic": 0.0,
+ "roughness": 0.9,
+ },
+ "gold": {
+ "color": [1.0, 0.84, 0.0, 1.0],
+ "metallic": 1.0,
+ "roughness": 0.1,
+ },
+ "titanium": {
+ "color": [0.75, 0.75, 0.78, 1.0],
+ "metallic": 0.9,
+ "roughness": 0.25,
+ "density": 4507,
+ "youngs_modulus": 116,
+ "poisson_ratio": 0.34,
+ "yield_strength": 880,
+ "ultimate_strength": 950,
+ },
+ "stainless_steel": {
+ "color": [0.75, 0.75, 0.77, 1.0],
+ "metallic": 0.95,
+ "roughness": 0.2,
+ "density": 8000,
+ "youngs_modulus": 193,
+ "poisson_ratio": 0.29,
+ "yield_strength": 205,
+ "ultimate_strength": 515,
+ },
+ "cast_iron": {
+ "color": [0.4, 0.4, 0.42, 1.0],
+ "metallic": 0.85,
+ "roughness": 0.6,
+ "density": 7200,
+ "youngs_modulus": 170,
+ "poisson_ratio": 0.26,
+ },
+ "carbon_fiber": {
+ "color": [0.1, 0.1, 0.12, 1.0],
+ "metallic": 0.3,
+ "roughness": 0.15,
+ "density": 1600,
+ "youngs_modulus": 230,
+ },
+ "nylon": {
+ "color": [0.9, 0.88, 0.82, 1.0],
+ "metallic": 0.0,
+ "roughness": 0.5,
+ "density": 1150,
+ "youngs_modulus": 2.7,
+ },
+ "abs": {
+ "color": [0.95, 0.95, 0.9, 1.0],
+ "metallic": 0.0,
+ "roughness": 0.45,
+ "density": 1040,
+ "youngs_modulus": 2.3,
+ },
+ "pla": {
+ "color": [0.9, 0.9, 0.85, 1.0],
+ "metallic": 0.0,
+ "roughness": 0.4,
+ "density": 1240,
+ "youngs_modulus": 3.5,
+ },
+ "petg": {
+ "color": [0.85, 0.88, 0.92, 1.0],
+ "metallic": 0.05,
+ "roughness": 0.35,
+ "density": 1270,
+ "youngs_modulus": 2.2,
+ },
+ "concrete": {
+ "color": [0.7, 0.7, 0.68, 1.0],
+ "metallic": 0.0,
+ "roughness": 0.9,
+ "density": 2400,
+ "youngs_modulus": 30,
+ },
+ "granite": {
+ "color": [0.55, 0.5, 0.48, 1.0],
+ "metallic": 0.1,
+ "roughness": 0.7,
+ "density": 2700,
+ "youngs_modulus": 70,
+ },
+ "marble": {
+ "color": [0.92, 0.9, 0.88, 1.0],
+ "metallic": 0.05,
+ "roughness": 0.3,
+ "density": 2700,
+ "youngs_modulus": 70,
+ },
+}
+
+# Valid material properties and their constraints
+MATERIAL_PROPS: Dict[str, Dict[str, Any]] = {
+ "color": {"type": "color4", "description": "Base color [R, G, B, A] (0.0-1.0)"},
+ "metallic": {"type": "float", "min": 0.0, "max": 1.0, "description": "Metallic factor"},
+ "roughness": {"type": "float", "min": 0.0, "max": 1.0, "description": "Roughness factor"},
+ "name": {"type": "str", "description": "Material display name"},
+ "density": {"type": "float", "min": 0.0, "description": "Density (kg/m^3)"},
+ "youngs_modulus": {"type": "float", "min": 0.0, "description": "Young's modulus (GPa)"},
+ "poisson_ratio": {"type": "float", "min": 0.0, "max": 0.5, "description": "Poisson's ratio"},
+ "thermal_conductivity": {"type": "float", "min": 0.0, "description": "Thermal conductivity (W/(m*K))"},
+ "specific_heat": {"type": "float", "min": 0.0, "description": "Specific heat capacity (J/(kg*K))"},
+ "yield_strength": {"type": "float", "min": 0.0, "description": "Yield strength (MPa)"},
+ "ultimate_strength": {"type": "float", "min": 0.0, "description": "Ultimate tensile strength (MPa)"},
+}
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _next_id(project: Dict[str, Any]) -> int:
+ """Generate the next unique material ID."""
+ materials = project.get("materials", [])
+ existing_ids = [m.get("id", 0) for m in materials]
+ return max(existing_ids, default=-1) + 1
+
+
+def _unique_name(project: Dict[str, Any], base_name: str) -> str:
+ """Generate a unique material name."""
+ materials = project.get("materials", [])
+ existing_names = {m.get("name", "") for m in materials}
+ if base_name not in existing_names:
+ return base_name
+ counter = 1
+ while f"{base_name}.{counter:03d}" in existing_names:
+ counter += 1
+ return f"{base_name}.{counter:03d}"
+
+
+def _validate_project(project: Dict[str, Any]) -> None:
+ """Raise ``ValueError`` if *project* is not a valid dict with a materials list."""
+ if not isinstance(project, dict):
+ raise ValueError("Project must be a dictionary")
+ if "materials" not in project:
+ raise ValueError("Project is missing 'materials' collection")
+ if not isinstance(project["materials"], list):
+ raise ValueError("Project 'materials' must be a list")
+
+
+def _get_material(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return material at *index* or raise ``IndexError``."""
+ materials = project["materials"]
+ if index < 0 or index >= len(materials):
+ raise IndexError(
+ f"Material index {index} out of range (0-{len(materials) - 1})"
+ )
+ return materials[index]
+
+
+def _validate_color(color: List[float]) -> List[float]:
+ """Validate and return a color as a list of 4 floats in [0, 1]."""
+ if not isinstance(color, (list, tuple)):
+ raise ValueError(f"Color must be a list, got {type(color).__name__}")
+ if len(color) < 3:
+ raise ValueError(f"Color must have at least 3 components [R, G, B], got {len(color)}")
+ if len(color) == 3:
+ color = list(color) + [1.0]
+ if len(color) > 4:
+ raise ValueError(f"Color must have at most 4 components [R, G, B, A], got {len(color)}")
+ result: List[float] = []
+ for i, c in enumerate(color):
+ try:
+ val = float(c)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"Color component {i} must be numeric: {exc}") from exc
+ if not 0.0 <= val <= 1.0:
+ raise ValueError(f"Color component {i} must be 0.0-1.0, got {val}")
+ result.append(val)
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def create_material(
+ project: Dict[str, Any],
+ name: str = "Material",
+ preset: Optional[str] = None,
+ color: Optional[List[float]] = None,
+ metallic: float = 0.0,
+ roughness: float = 0.5,
+ **kwargs: Any,
+) -> Dict[str, Any]:
+ """Create a new material, optionally based on a preset.
+
+ When *preset* is given, its ``color``, ``metallic``, and ``roughness``
+ values are used as defaults. Explicit *color*, *metallic*, and
+ *roughness* arguments override the preset values.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ name:
+ Material display name.
+ preset:
+ Optional preset key from :data:`PRESETS`.
+ color:
+ Base color ``[R, G, B, A]`` with components in ``[0, 1]``.
+ metallic:
+ Metallic factor ``[0, 1]``.
+ roughness:
+ Roughness factor ``[0, 1]``.
+ **kwargs:
+ Optional engineering properties: ``density``, ``youngs_modulus``,
+ ``poisson_ratio``, ``thermal_conductivity``, ``specific_heat``,
+ ``yield_strength``, ``ultimate_strength``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created material dictionary.
+
+ Raises
+ ------
+ ValueError
+ If the preset is unknown, colour is invalid, or numeric values are
+ out of range.
+ """
+ _validate_project(project)
+
+ # Resolve preset defaults
+ preset_data: Dict[str, Any] = {}
+ if preset is not None:
+ if preset not in PRESETS:
+ raise ValueError(
+ f"Unknown preset '{preset}'. Available presets: {', '.join(sorted(PRESETS))}"
+ )
+ preset_data = PRESETS[preset]
+ # Use preset name as the material name if caller left the default
+ if name == "Material":
+ name = preset.replace("_", " ").title()
+
+ # Determine final values (explicit args override preset)
+ final_color: List[float]
+ if color is not None:
+ final_color = _validate_color(color)
+ elif "color" in preset_data:
+ final_color = list(preset_data["color"])
+ else:
+ final_color = [0.8, 0.8, 0.8, 1.0]
+
+ final_metallic = metallic
+ if preset_data and metallic == 0.0 and "metallic" in preset_data:
+ # Only use preset metallic when caller left the default
+ final_metallic = preset_data["metallic"]
+ final_metallic = float(final_metallic)
+
+ final_roughness = roughness
+ if preset_data and roughness == 0.5 and "roughness" in preset_data:
+ final_roughness = preset_data["roughness"]
+ final_roughness = float(final_roughness)
+
+ if not 0.0 <= final_metallic <= 1.0:
+ raise ValueError(f"Metallic must be 0.0-1.0, got {final_metallic}")
+ if not 0.0 <= final_roughness <= 1.0:
+ raise ValueError(f"Roughness must be 0.0-1.0, got {final_roughness}")
+
+ mat_name = _unique_name(project, name)
+
+ mat: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": mat_name,
+ "preset": preset,
+ "color": final_color,
+ "metallic": final_metallic,
+ "roughness": final_roughness,
+ "assigned_to": [],
+ }
+
+ # Engineering properties from preset (as defaults) and kwargs (overrides)
+ _ENG_PROPS = (
+ "density", "youngs_modulus", "poisson_ratio",
+ "thermal_conductivity", "specific_heat",
+ "yield_strength", "ultimate_strength",
+ )
+ for ep in _ENG_PROPS:
+ value = kwargs.get(ep)
+ if value is None and preset_data:
+ value = preset_data.get(ep)
+ if value is not None:
+ value = float(value)
+ spec = MATERIAL_PROPS.get(ep, {})
+ if spec.get("min") is not None and value < spec["min"]:
+ raise ValueError(
+ f"Property '{ep}' minimum is {spec['min']}, got {value}"
+ )
+ if spec.get("max") is not None and value > spec["max"]:
+ raise ValueError(
+ f"Property '{ep}' maximum is {spec['max']}, got {value}"
+ )
+ mat[ep] = value
+
+ project["materials"].append(mat)
+ return mat
+
+
+def assign_material(
+ project: Dict[str, Any],
+ material_index: int,
+ part_index: int,
+) -> Dict[str, Any]:
+ """Assign a material to a part.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ material_index:
+ Index of the material in ``project["materials"]``.
+ part_index:
+ Index of the part in ``project["parts"]``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Assignment summary with material and part names/IDs.
+
+ Raises
+ ------
+ IndexError
+ If either index is out of range.
+ """
+ _validate_project(project)
+
+ mat = _get_material(project, material_index)
+
+ parts = project.get("parts", [])
+ if not isinstance(parts, list):
+ raise ValueError("Project 'parts' must be a list")
+ if part_index < 0 or part_index >= len(parts):
+ raise IndexError(
+ f"Part index {part_index} out of range (0-{len(parts) - 1})"
+ )
+
+ part = parts[part_index]
+
+ # Record the assignment on the material
+ if part_index not in mat.get("assigned_to", []):
+ mat.setdefault("assigned_to", []).append(part_index)
+
+ # Record the material on the part
+ part["material_id"] = mat["id"]
+ part["material_index"] = material_index
+
+ return {
+ "material": mat["name"],
+ "material_id": mat["id"],
+ "part": part.get("name", f"Part {part_index}"),
+ "part_id": part.get("id", part_index),
+ }
+
+
+def list_materials(project: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return a summary list of all materials in the project.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+
+ Returns
+ -------
+ List[Dict[str, Any]]
+ List of material summaries.
+ """
+ _validate_project(project)
+
+ result: List[Dict[str, Any]] = []
+ for i, mat in enumerate(project["materials"]):
+ result.append({
+ "index": i,
+ "id": mat.get("id", i),
+ "name": mat.get("name", f"Material {i}"),
+ "preset": mat.get("preset"),
+ "color": mat.get("color", [0.8, 0.8, 0.8, 1.0]),
+ "metallic": mat.get("metallic", 0.0),
+ "roughness": mat.get("roughness", 0.5),
+ "assigned_to": mat.get("assigned_to", []),
+ })
+ return result
+
+
+def get_material(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the full material dictionary at the given index.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ index:
+ Material index.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The complete material dictionary.
+ """
+ _validate_project(project)
+ return _get_material(project, index)
+
+
+def set_material_property(
+ project: Dict[str, Any],
+ index: int,
+ prop: str,
+ value: Any,
+) -> None:
+ """Set a single property on a material.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ index:
+ Material index.
+ prop:
+ Property name. One of ``"color"``, ``"metallic"``, ``"roughness"``,
+ or ``"name"``.
+ value:
+ New value. Type depends on the property.
+
+ Raises
+ ------
+ IndexError
+ If *index* is out of range.
+ ValueError
+ If *prop* is unknown or *value* is invalid.
+ """
+ _validate_project(project)
+ mat = _get_material(project, index)
+
+ if prop not in MATERIAL_PROPS:
+ raise ValueError(
+ f"Unknown material property: '{prop}'. "
+ f"Valid properties: {', '.join(sorted(MATERIAL_PROPS))}"
+ )
+
+ spec = MATERIAL_PROPS[prop]
+ ptype = spec["type"]
+
+ if ptype == "float":
+ value = float(value)
+ if "min" in spec and value < spec["min"]:
+ raise ValueError(f"Property '{prop}' minimum is {spec['min']}, got {value}")
+ if "max" in spec and value > spec["max"]:
+ raise ValueError(f"Property '{prop}' maximum is {spec['max']}, got {value}")
+ mat[prop] = value
+ elif ptype == "color4":
+ if isinstance(value, str):
+ value = [float(x.strip()) for x in value.split(",")]
+ mat[prop] = _validate_color(value)
+ elif ptype == "str":
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError(f"Property '{prop}' must be a non-empty string")
+ mat[prop] = value.strip()
+ else:
+ mat[prop] = value
+
+
+def list_presets() -> List[Dict[str, Any]]:
+ """Return a list of all available material presets.
+
+ Returns
+ -------
+ List[Dict[str, Any]]
+ Each entry contains the preset ``name``, ``color``, ``metallic``,
+ ``roughness``, and any engineering properties.
+ """
+ results: List[Dict[str, Any]] = []
+ for key, value in PRESETS.items():
+ entry: Dict[str, Any] = {
+ "name": key,
+ "color": list(value["color"]),
+ "metallic": value["metallic"],
+ "roughness": value["roughness"],
+ }
+ for ep in (
+ "density", "youngs_modulus", "poisson_ratio",
+ "thermal_conductivity", "specific_heat",
+ "yield_strength", "ultimate_strength",
+ ):
+ if ep in value:
+ entry[ep] = value[ep]
+ results.append(entry)
+ return results
+
+
+def import_material(project: Dict[str, Any], path: str) -> Dict[str, Any]:
+ """Load a material from a JSON file and add it to the project.
+
+ The JSON file should contain keys such as ``name``, ``color``,
+ ``metallic``, ``roughness``, and optional engineering properties.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ path:
+ Path to a JSON file describing the material.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created material dictionary.
+
+ Raises
+ ------
+ FileNotFoundError
+ If *path* does not exist.
+ ValueError
+ If the JSON is invalid or material properties are out of range.
+ """
+ _validate_project(project)
+
+ with open(path, "r", encoding="utf-8") as fh:
+ data = json.load(fh)
+
+ if not isinstance(data, dict):
+ raise ValueError(f"Material JSON must be an object, got {type(data).__name__}")
+
+ # Extract recognised kwargs for create_material
+ create_kwargs: Dict[str, Any] = {}
+ for ep in (
+ "density", "youngs_modulus", "poisson_ratio",
+ "thermal_conductivity", "specific_heat",
+ "yield_strength", "ultimate_strength",
+ ):
+ if ep in data:
+ create_kwargs[ep] = data[ep]
+
+ return create_material(
+ project,
+ name=data.get("name", "Imported Material"),
+ preset=data.get("preset"),
+ color=data.get("color"),
+ metallic=float(data.get("metallic", 0.0)),
+ roughness=float(data.get("roughness", 0.5)),
+ **create_kwargs,
+ )
+
+
+def export_material(project: Dict[str, Any], index: int, path: str) -> Dict[str, Any]:
+ """Save a material to a JSON file.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ index:
+ Material index.
+ path:
+ Destination file path.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Summary with ``path`` and ``material_name``.
+
+ Raises
+ ------
+ IndexError
+ If *index* is out of range.
+ """
+ _validate_project(project)
+ mat = _get_material(project, index)
+
+ # Build a clean export dict (omit internal bookkeeping)
+ export_data: Dict[str, Any] = {}
+ for key in (
+ "name", "color", "metallic", "roughness", "preset",
+ "density", "youngs_modulus", "poisson_ratio",
+ "thermal_conductivity", "specific_heat",
+ "yield_strength", "ultimate_strength",
+ ):
+ if key in mat:
+ export_data[key] = mat[key]
+
+ with open(path, "w", encoding="utf-8") as fh:
+ json.dump(export_data, fh, indent=2)
+
+ return {"path": path, "material_name": mat.get("name", f"Material {index}")}
diff --git a/freecad/agent-harness/cli_anything/freecad/core/measure.py b/freecad/agent-harness/cli_anything/freecad/core/measure.py
new file mode 100644
index 000000000..ab492c39c
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/measure.py
@@ -0,0 +1,646 @@
+"""FreeCAD CLI - Measurement and geometry analysis module.
+
+Computes measurements from part/body geometry stored in the JSON project
+state. For simple primitives (box, cylinder, sphere, cone, torus) the
+module implements exact mathematical formulas. More complex shapes store
+measurement requests that are resolved via macro execution.
+"""
+
+import math
+from typing import Any, Dict, List, Optional
+
+from cli_anything.freecad.core.document import ensure_collection
+from cli_anything.freecad.core.parts import PRIMITIVES, get_part
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _next_measurement_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for measurements."""
+ items = project.get("measurements", [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _store_measurement(
+ project: Dict[str, Any],
+ kind: str,
+ result: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Wrap *result* in a measurement record and append to the project."""
+ measurements = ensure_collection(project, "measurements")
+ record: Dict[str, Any] = {
+ "id": _next_measurement_id(project),
+ "kind": kind,
+ **result,
+ }
+ measurements.append(record)
+ return record
+
+
+def _get_position(part: Dict[str, Any]) -> List[float]:
+ """Return the placement position of a part as ``[x, y, z]``."""
+ return list(part["placement"]["position"])
+
+
+def _bbox_center(part: Dict[str, Any]) -> List[float]:
+ """Estimate the bounding-box centre of a part from its position and params."""
+ pos = _get_position(part)
+ p = part["params"]
+ t = part["type"]
+
+ if t == "box":
+ return [
+ pos[0] + p["length"] / 2.0,
+ pos[1] + p["width"] / 2.0,
+ pos[2] + p["height"] / 2.0,
+ ]
+ elif t == "cylinder":
+ r = p["radius"]
+ return [
+ pos[0] + r,
+ pos[1] + r,
+ pos[2] + p["height"] / 2.0,
+ ]
+ elif t == "sphere":
+ r = p["radius"]
+ return [pos[0] + r, pos[1] + r, pos[2] + r]
+ elif t == "cone":
+ r = max(p["radius1"], p["radius2"])
+ return [
+ pos[0] + r,
+ pos[1] + r,
+ pos[2] + p["height"] / 2.0,
+ ]
+ elif t == "torus":
+ R = p["radius1"]
+ r = p["radius2"]
+ return [
+ pos[0] + R + r,
+ pos[1] + R + r,
+ pos[2] + r,
+ ]
+ elif t == "wedge":
+ return [
+ pos[0] + (p["xmin"] + p["xmax"]) / 2.0,
+ pos[1] + (p["ymin"] + p["ymax"]) / 2.0,
+ pos[2] + (p["zmin"] + p["zmax"]) / 2.0,
+ ]
+ # Boolean or unknown — fall back to placement position
+ return pos
+
+
+# ---------------------------------------------------------------------------
+# Volume / area formulas
+# ---------------------------------------------------------------------------
+
+def _compute_volume(part: Dict[str, Any]) -> Optional[float]:
+ """Compute volume from primitive parameters. Returns *None* for unknowns."""
+ p = part["params"]
+ t = part["type"]
+
+ if t == "box":
+ return p["length"] * p["width"] * p["height"]
+ elif t == "cylinder":
+ return math.pi * p["radius"] ** 2 * p["height"]
+ elif t == "sphere":
+ return (4.0 / 3.0) * math.pi * p["radius"] ** 3
+ elif t == "cone":
+ r1, r2, h = p["radius1"], p["radius2"], p["height"]
+ return (1.0 / 3.0) * math.pi * h * (r1 ** 2 + r1 * r2 + r2 ** 2)
+ elif t == "torus":
+ R, r = p["radius1"], p["radius2"]
+ return 2.0 * math.pi ** 2 * R * r ** 2
+ elif t == "wedge":
+ # Approximate as bounding box (exact wedge needs more info)
+ dx = p["xmax"] - p["xmin"]
+ dy = p["ymax"] - p["ymin"]
+ dz = p["zmax"] - p["zmin"]
+ return dx * dy * dz
+ return None
+
+
+def _compute_area(part: Dict[str, Any]) -> Optional[float]:
+ """Compute surface area from primitive parameters. Returns *None* for unknowns."""
+ p = part["params"]
+ t = part["type"]
+
+ if t == "box":
+ l, w, h = p["length"], p["width"], p["height"]
+ return 2.0 * (l * w + w * h + l * h)
+ elif t == "cylinder":
+ r, h = p["radius"], p["height"]
+ return 2.0 * math.pi * r * (r + h)
+ elif t == "sphere":
+ return 4.0 * math.pi * p["radius"] ** 2
+ elif t == "cone":
+ r1, r2, h = p["radius1"], p["radius2"], p["height"]
+ slant = math.sqrt((r1 - r2) ** 2 + h ** 2)
+ return (
+ math.pi * r1 ** 2
+ + math.pi * r2 ** 2
+ + math.pi * (r1 + r2) * slant
+ )
+ elif t == "torus":
+ R, r = p["radius1"], p["radius2"]
+ return 4.0 * math.pi ** 2 * R * r
+ elif t == "wedge":
+ dx = p["xmax"] - p["xmin"]
+ dy = p["ymax"] - p["ymin"]
+ dz = p["zmax"] - p["zmin"]
+ return 2.0 * (dx * dy + dy * dz + dx * dz)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Inertia helpers
+# ---------------------------------------------------------------------------
+
+def _compute_inertia(part: Dict[str, Any]) -> Optional[Dict[str, float]]:
+ """Estimate principal moments of inertia (Ixx, Iyy, Izz) assuming unit density."""
+ p = part["params"]
+ t = part["type"]
+ vol = _compute_volume(part)
+ if vol is None:
+ return None
+ m = vol # unit density
+
+ if t == "box":
+ l, w, h = p["length"], p["width"], p["height"]
+ return {
+ "Ixx": m * (w ** 2 + h ** 2) / 12.0,
+ "Iyy": m * (l ** 2 + h ** 2) / 12.0,
+ "Izz": m * (l ** 2 + w ** 2) / 12.0,
+ }
+ elif t == "cylinder":
+ r, h = p["radius"], p["height"]
+ return {
+ "Ixx": m * (3.0 * r ** 2 + h ** 2) / 12.0,
+ "Iyy": m * (3.0 * r ** 2 + h ** 2) / 12.0,
+ "Izz": m * r ** 2 / 2.0,
+ }
+ elif t == "sphere":
+ r = p["radius"]
+ I = 2.0 * m * r ** 2 / 5.0
+ return {"Ixx": I, "Iyy": I, "Izz": I}
+ elif t == "cone":
+ r1, r2, h = p["radius1"], p["radius2"], p["height"]
+ # Approximate using average radius
+ r_avg = (r1 + r2) / 2.0
+ return {
+ "Ixx": m * (3.0 * r_avg ** 2 + h ** 2) / 12.0,
+ "Iyy": m * (3.0 * r_avg ** 2 + h ** 2) / 12.0,
+ "Izz": m * r_avg ** 2 / 2.0,
+ }
+ elif t == "torus":
+ R, r = p["radius1"], p["radius2"]
+ Ixx = m * (5.0 * r ** 2 + 4.0 * R ** 2) / 8.0
+ return {
+ "Ixx": Ixx,
+ "Iyy": Ixx,
+ "Izz": m * (3.0 * r ** 2 + 4.0 * R ** 2) / 4.0,
+ }
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+def measure_distance(
+ project: Dict[str, Any], index1: int, index2: int
+) -> Dict[str, Any]:
+ """Measure the Euclidean distance between two parts (bounding-box centres).
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index1 : int
+ Index of the first part in ``project["parts"]``.
+ index2 : int
+ Index of the second part in ``project["parts"]``.
+
+ Returns
+ -------
+ dict
+ Measurement record with ``distance`` value and axis deltas.
+ """
+ part1 = get_part(project, index1)
+ part2 = get_part(project, index2)
+
+ c1 = _bbox_center(part1)
+ c2 = _bbox_center(part2)
+
+ dx = c2[0] - c1[0]
+ dy = c2[1] - c1[1]
+ dz = c2[2] - c1[2]
+ dist = math.sqrt(dx ** 2 + dy ** 2 + dz ** 2)
+
+ return _store_measurement(project, "distance", {
+ "part1_index": index1,
+ "part2_index": index2,
+ "distance": round(dist, 6),
+ "delta": [round(dx, 6), round(dy, 6), round(dz, 6)],
+ })
+
+
+def measure_length(
+ project: Dict[str, Any], index: int, edge_ref: Optional[str] = None
+) -> Dict[str, Any]:
+ """Estimate the length of a part edge.
+
+ For primitives without an explicit *edge_ref*, the longest dimension
+ is returned as an estimate.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ index : int
+ Index of the part in ``project["parts"]``.
+ edge_ref : str or None
+ Optional edge reference (e.g. ``"Edge1"``). When supplied the
+ measurement is stored as a deferred request.
+
+ Returns
+ -------
+ dict
+ Measurement record with ``length`` value.
+ """
+ part = get_part(project, index)
+ p = part["params"]
+ t = part["type"]
+ length: Optional[float] = None
+
+ if edge_ref is not None:
+ # Deferred — requires macro execution
+ return _store_measurement(project, "length", {
+ "part_index": index,
+ "edge_ref": edge_ref,
+ "length": None,
+ "deferred": True,
+ })
+
+ if t == "box":
+ length = max(p["length"], p["width"], p["height"])
+ elif t == "cylinder":
+ length = p["height"]
+ elif t == "sphere":
+ length = 2.0 * p["radius"]
+ elif t == "cone":
+ length = p["height"]
+ elif t == "torus":
+ length = 2.0 * math.pi * p["radius1"]
+ elif t == "wedge":
+ length = max(
+ p["xmax"] - p["xmin"],
+ p["ymax"] - p["ymin"],
+ p["zmax"] - p["zmin"],
+ )
+
+ return _store_measurement(project, "length", {
+ "part_index": index,
+ "edge_ref": edge_ref,
+ "length": round(length, 6) if length is not None else None,
+ "deferred": length is None,
+ })
+
+
+def measure_angle(
+ project: Dict[str, Any], index1: int, index2: int
+) -> Dict[str, Any]:
+ """Measure the angle between two parts based on their centre vectors from the origin.
+
+ The angle is computed between the vectors from the world origin to
+ each part's bounding-box centre. Returns 0.0 when either vector is
+ zero-length.
+
+ Returns
+ -------
+ dict
+ Measurement record with ``angle_deg`` value.
+ """
+ part1 = get_part(project, index1)
+ part2 = get_part(project, index2)
+
+ c1 = _bbox_center(part1)
+ c2 = _bbox_center(part2)
+
+ mag1 = math.sqrt(sum(v ** 2 for v in c1))
+ mag2 = math.sqrt(sum(v ** 2 for v in c2))
+
+ if mag1 == 0.0 or mag2 == 0.0:
+ angle_deg = 0.0
+ else:
+ dot = sum(a * b for a, b in zip(c1, c2))
+ cos_val = max(-1.0, min(1.0, dot / (mag1 * mag2)))
+ angle_deg = math.degrees(math.acos(cos_val))
+
+ return _store_measurement(project, "angle", {
+ "part1_index": index1,
+ "part2_index": index2,
+ "angle_deg": round(angle_deg, 6),
+ })
+
+
+def measure_area(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Estimate the surface area of a part from its primitive parameters.
+
+ Returns
+ -------
+ dict
+ Measurement record with ``area`` value (or *None* for unsupported types).
+ """
+ part = get_part(project, index)
+ area = _compute_area(part)
+
+ return _store_measurement(project, "area", {
+ "part_index": index,
+ "area": round(area, 6) if area is not None else None,
+ "deferred": area is None,
+ })
+
+
+def measure_volume(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Estimate the volume of a part from its primitive parameters.
+
+ Formulas used:
+ - box: V = l * w * h
+ - cylinder: V = pi * r^2 * h
+ - sphere: V = 4/3 * pi * r^3
+ - cone: V = 1/3 * pi * h * (r1^2 + r1*r2 + r2^2)
+ - torus: V = 2 * pi^2 * R * r^2
+
+ Returns
+ -------
+ dict
+ Measurement record with ``volume`` value (or *None* for unsupported types).
+ """
+ part = get_part(project, index)
+ volume = _compute_volume(part)
+
+ return _store_measurement(project, "volume", {
+ "part_index": index,
+ "volume": round(volume, 6) if volume is not None else None,
+ "deferred": volume is None,
+ })
+
+
+def measure_radius(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the radius of a cylindrical, spherical, or toroidal part.
+
+ For cones, the larger of ``radius1`` / ``radius2`` is returned.
+
+ Returns
+ -------
+ dict
+ Measurement record with ``radius`` value.
+
+ Raises
+ ------
+ ValueError
+ If the part type has no meaningful radius.
+ """
+ part = get_part(project, index)
+ p = part["params"]
+ t = part["type"]
+
+ if t == "cylinder":
+ radius = p["radius"]
+ elif t == "sphere":
+ radius = p["radius"]
+ elif t == "cone":
+ radius = max(p["radius1"], p["radius2"])
+ elif t == "torus":
+ radius = p["radius2"]
+ else:
+ raise ValueError(
+ f"Part type '{t}' has no meaningful radius. "
+ f"Supported: cylinder, sphere, cone, torus"
+ )
+
+ return _store_measurement(project, "radius", {
+ "part_index": index,
+ "radius": round(radius, 6),
+ })
+
+
+def measure_diameter(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the diameter of a cylindrical, spherical, or toroidal part.
+
+ Returns
+ -------
+ dict
+ Measurement record with ``diameter`` value.
+
+ Raises
+ ------
+ ValueError
+ If the part type has no meaningful diameter.
+ """
+ part = get_part(project, index)
+ p = part["params"]
+ t = part["type"]
+
+ if t == "cylinder":
+ diameter = 2.0 * p["radius"]
+ elif t == "sphere":
+ diameter = 2.0 * p["radius"]
+ elif t == "cone":
+ diameter = 2.0 * max(p["radius1"], p["radius2"])
+ elif t == "torus":
+ diameter = 2.0 * p["radius2"]
+ else:
+ raise ValueError(
+ f"Part type '{t}' has no meaningful diameter. "
+ f"Supported: cylinder, sphere, cone, torus"
+ )
+
+ return _store_measurement(project, "diameter", {
+ "part_index": index,
+ "diameter": round(diameter, 6),
+ })
+
+
+def measure_position(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the placement position of a part.
+
+ Returns
+ -------
+ dict
+ Measurement record with ``position`` ``[x, y, z]``.
+ """
+ part = get_part(project, index)
+ pos = _get_position(part)
+
+ return _store_measurement(project, "position", {
+ "part_index": index,
+ "position": pos,
+ })
+
+
+def measure_center_of_mass(
+ project: Dict[str, Any], index: int
+) -> Dict[str, Any]:
+ """Estimate the centre of mass (geometric centre for simple shapes).
+
+ For uniform-density primitives the centre of mass coincides with the
+ bounding-box centre.
+
+ Returns
+ -------
+ dict
+ Measurement record with ``center_of_mass`` ``[x, y, z]``.
+ """
+ part = get_part(project, index)
+ com = _bbox_center(part)
+
+ return _store_measurement(project, "center_of_mass", {
+ "part_index": index,
+ "center_of_mass": [round(v, 6) for v in com],
+ })
+
+
+def measure_bounding_box(
+ project: Dict[str, Any], index: int
+) -> Dict[str, Any]:
+ """Compute the axis-aligned bounding box of a part.
+
+ The bounding box is derived from the part's position and primitive
+ parameters.
+
+ Returns
+ -------
+ dict
+ Measurement record with ``min``, ``max``, and ``size`` vectors.
+ """
+ part = get_part(project, index)
+ pos = _get_position(part)
+ p = part["params"]
+ t = part["type"]
+
+ if t == "box":
+ bb_min = pos[:]
+ bb_max = [
+ pos[0] + p["length"],
+ pos[1] + p["width"],
+ pos[2] + p["height"],
+ ]
+ elif t == "cylinder":
+ r = p["radius"]
+ bb_min = [pos[0] - r, pos[1] - r, pos[2]]
+ bb_max = [pos[0] + r, pos[1] + r, pos[2] + p["height"]]
+ elif t == "sphere":
+ r = p["radius"]
+ bb_min = [pos[0] - r, pos[1] - r, pos[2] - r]
+ bb_max = [pos[0] + r, pos[1] + r, pos[2] + r]
+ elif t == "cone":
+ r = max(p["radius1"], p["radius2"])
+ bb_min = [pos[0] - r, pos[1] - r, pos[2]]
+ bb_max = [pos[0] + r, pos[1] + r, pos[2] + p["height"]]
+ elif t == "torus":
+ R, r = p["radius1"], p["radius2"]
+ outer = R + r
+ bb_min = [pos[0] - outer, pos[1] - outer, pos[2] - r]
+ bb_max = [pos[0] + outer, pos[1] + outer, pos[2] + r]
+ elif t == "wedge":
+ bb_min = [
+ pos[0] + p["xmin"],
+ pos[1] + p["ymin"],
+ pos[2] + p["zmin"],
+ ]
+ bb_max = [
+ pos[0] + p["xmax"],
+ pos[1] + p["ymax"],
+ pos[2] + p["zmax"],
+ ]
+ else:
+ # Unknown / boolean — deferred
+ return _store_measurement(project, "bounding_box", {
+ "part_index": index,
+ "min": None,
+ "max": None,
+ "size": None,
+ "deferred": True,
+ })
+
+ size = [bb_max[i] - bb_min[i] for i in range(3)]
+
+ return _store_measurement(project, "bounding_box", {
+ "part_index": index,
+ "min": [round(v, 6) for v in bb_min],
+ "max": [round(v, 6) for v in bb_max],
+ "size": [round(v, 6) for v in size],
+ "deferred": False,
+ })
+
+
+def measure_inertia(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Estimate the principal moments of inertia (unit density).
+
+ Returns
+ -------
+ dict
+ Measurement record with ``Ixx``, ``Iyy``, ``Izz`` values.
+ """
+ part = get_part(project, index)
+ inertia = _compute_inertia(part)
+
+ if inertia is not None:
+ inertia = {k: round(v, 6) for k, v in inertia.items()}
+
+ return _store_measurement(project, "inertia", {
+ "part_index": index,
+ "inertia": inertia,
+ "deferred": inertia is None,
+ })
+
+
+def check_geometry(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Perform basic geometry validation on a part.
+
+ Checks that all numeric parameters are positive and that the part
+ type is a known primitive.
+
+ Returns
+ -------
+ dict
+ Record with ``valid`` boolean and list of ``issues``.
+ """
+ part = get_part(project, index)
+ issues: List[str] = []
+
+ t = part["type"]
+ if t not in PRIMITIVES:
+ issues.append(f"Unknown primitive type '{t}'")
+ else:
+ p = part["params"]
+ defaults = PRIMITIVES[t]
+ for key in defaults:
+ if key in p:
+ val = p[key]
+ # Angle parameters may be negative (e.g. angle1 on sphere/torus)
+ if "angle" not in key and val <= 0:
+ issues.append(f"Parameter '{key}' must be positive, got {val}")
+ else:
+ issues.append(f"Missing expected parameter '{key}'")
+
+ # Validate placement exists
+ placement = part.get("placement")
+ if placement is None:
+ issues.append("Missing 'placement' on part")
+ else:
+ if "position" not in placement:
+ issues.append("Missing 'position' in placement")
+ if "rotation" not in placement:
+ issues.append("Missing 'rotation' in placement")
+
+ return _store_measurement(project, "geometry_check", {
+ "part_index": index,
+ "valid": len(issues) == 0,
+ "issues": issues,
+ })
diff --git a/freecad/agent-harness/cli_anything/freecad/core/mesh.py b/freecad/agent-harness/cli_anything/freecad/core/mesh.py
new file mode 100644
index 000000000..a884b896c
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/mesh.py
@@ -0,0 +1,747 @@
+"""FreeCAD CLI - Mesh operations module.
+
+Manages mesh import, export, tessellation from shapes, analysis, boolean
+operations, decimation, remeshing, smoothing, repair, and conversion back
+to solid shapes. Meshes are stored in ``project["meshes"]`` via
+:func:`~cli_anything.freecad.core.document.ensure_collection`.
+"""
+
+import os
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Set
+
+from cli_anything.freecad.core.document import ensure_collection
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+MESH_FORMATS: Set[str] = {"stl", "obj", "ply", "off", "3mf", "amf", "bms"}
+MESH_BOOLEAN_OPS: Set[str] = {"union", "difference", "intersection"}
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _next_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for meshes."""
+ items = project.get("meshes", [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str) -> str:
+ """Return a unique name derived from *base* inside ``project["meshes"]``."""
+ existing = {item["name"] for item in project.get("meshes", [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _get_mesh(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the mesh at *index*, raising ``IndexError`` if out of range."""
+ meshes = project.get("meshes", [])
+ if not isinstance(index, int) or index < 0 or index >= len(meshes):
+ raise IndexError(
+ f"Mesh index {index} out of range (0..{len(meshes) - 1})"
+ )
+ return meshes[index]
+
+
+def _validate_path(path: str, label: str = "path") -> str:
+ """Validate that *path* is a non-empty string and return it normalised."""
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError(f"{label} must be a non-empty string")
+ return path.strip()
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def import_mesh(
+ project: Dict[str, Any],
+ path: str,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Import a mesh file and register it in ``project["meshes"]``.
+
+ The actual file loading happens during macro generation; this function
+ records the import intent and metadata.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ path : str
+ Filesystem path to the mesh file.
+ name : str or None
+ Human-readable label. Derived from filename when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created mesh entry.
+
+ Raises
+ ------
+ ValueError
+ If *path* is empty.
+ """
+ path = _validate_path(path)
+ meshes = ensure_collection(project, "meshes")
+
+ ext = os.path.splitext(path)[1].lstrip(".").lower()
+ if name is None:
+ base = os.path.splitext(os.path.basename(path))[0]
+ name = _unique_name(project, base)
+
+ mesh: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "source": path,
+ "format": ext if ext else "unknown",
+ "vertices_count": 0,
+ "faces_count": 0,
+ "operations_applied": [],
+ }
+
+ meshes.append(mesh)
+ return mesh
+
+
+def mesh_from_shape(
+ project: Dict[str, Any],
+ part_index: int,
+ name: Optional[str] = None,
+ max_length: Optional[float] = None,
+ deviation: float = 0.1,
+) -> Dict[str, Any]:
+ """Tessellate a solid part into a triangular mesh.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ part_index : int
+ Index of the source part in ``project["parts"]``.
+ name : str or None
+ Label for the new mesh. Auto-generated when *None*.
+ max_length : float or None
+ Maximum edge length constraint. *None* means no constraint.
+ deviation : float
+ Surface deviation tolerance (default ``0.1``).
+
+ Returns
+ -------
+ dict
+ The newly created mesh entry.
+
+ Raises
+ ------
+ IndexError
+ If *part_index* is out of range.
+ ValueError
+ If *deviation* is not positive.
+ """
+ parts = project.get("parts", [])
+ if not isinstance(part_index, int) or part_index < 0 or part_index >= len(parts):
+ raise IndexError(
+ f"Part index {part_index} out of range (0..{len(parts) - 1})"
+ )
+
+ if deviation <= 0:
+ raise ValueError("deviation must be a positive number")
+
+ meshes = ensure_collection(project, "meshes")
+ part = parts[part_index]
+
+ if name is None:
+ name = _unique_name(project, f"{part['name']}_Mesh")
+
+ params: Dict[str, Any] = {"deviation": float(deviation)}
+ if max_length is not None:
+ if max_length <= 0:
+ raise ValueError("max_length must be a positive number")
+ params["max_length"] = float(max_length)
+
+ mesh: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "source": part_index,
+ "format": "tessellated",
+ "vertices_count": 0,
+ "faces_count": 0,
+ "operations_applied": [
+ {"op": "tessellate", "params": params},
+ ],
+ }
+
+ meshes.append(mesh)
+ return mesh
+
+
+def export_mesh(
+ project: Dict[str, Any],
+ mesh_index: int,
+ path: str,
+ format: str = "stl",
+) -> Dict[str, Any]:
+ """Record an export request for the mesh at *mesh_index*.
+
+ The actual file writing is performed during macro generation; this
+ function validates the arguments and returns export metadata.
+
+ Parameters
+ ----------
+ project : dict
+ The project state dictionary.
+ mesh_index : int
+ Index of the mesh to export.
+ path : str
+ Destination file path.
+ format : str
+ Output format (default ``"stl"``).
+
+ Returns
+ -------
+ dict
+ Export metadata including mesh id, path, and format.
+
+ Raises
+ ------
+ IndexError
+ If *mesh_index* is out of range.
+ ValueError
+ If *format* is unsupported or *path* is empty.
+ """
+ mesh = _get_mesh(project, mesh_index)
+ path = _validate_path(path, "export path")
+
+ fmt = format.lower()
+ if fmt not in MESH_FORMATS:
+ valid = ", ".join(sorted(MESH_FORMATS))
+ raise ValueError(f"Unsupported mesh format '{fmt}'. Valid: {valid}")
+
+ return {
+ "mesh_id": mesh["id"],
+ "mesh_name": mesh["name"],
+ "path": path,
+ "format": fmt,
+ }
+
+
+def mesh_info(project: Dict[str, Any], mesh_index: int) -> Dict[str, Any]:
+ """Return a summary of the mesh at *mesh_index*.
+
+ Parameters
+ ----------
+ project : dict
+ The project state dictionary.
+ mesh_index : int
+ Index of the mesh.
+
+ Returns
+ -------
+ dict
+ Copy of the mesh entry.
+ """
+ mesh = _get_mesh(project, mesh_index)
+ return deepcopy(mesh)
+
+
+def analyze_mesh(project: Dict[str, Any], mesh_index: int) -> Dict[str, Any]:
+ """Return stored analysis results for the mesh at *mesh_index*.
+
+ Analysis covers vertex/face counts, bounding-box estimation, and
+ volume/area placeholders. Actual numerical analysis happens in the
+ FreeCAD macro; this records the intent and returns current metadata.
+
+ Parameters
+ ----------
+ project : dict
+ The project state dictionary.
+ mesh_index : int
+ Index of the mesh.
+
+ Returns
+ -------
+ dict
+ Analysis result dictionary.
+ """
+ mesh = _get_mesh(project, mesh_index)
+ return {
+ "mesh_id": mesh["id"],
+ "name": mesh["name"],
+ "vertices_count": mesh["vertices_count"],
+ "faces_count": mesh["faces_count"],
+ "format": mesh["format"],
+ "operations_applied": list(mesh["operations_applied"]),
+ "analysis": "pending_macro_execution",
+ }
+
+
+def check_mesh(project: Dict[str, Any], mesh_index: int) -> Dict[str, Any]:
+ """Check the mesh at *mesh_index* for common problems.
+
+ Returns a diagnostic dictionary. The actual checks (non-manifold
+ edges, self-intersections, degenerate faces) are performed by the
+ FreeCAD macro; this function records the request.
+
+ Parameters
+ ----------
+ project : dict
+ The project state dictionary.
+ mesh_index : int
+ Index of the mesh.
+
+ Returns
+ -------
+ dict
+ Diagnostic placeholder with mesh metadata.
+ """
+ mesh = _get_mesh(project, mesh_index)
+ return {
+ "mesh_id": mesh["id"],
+ "name": mesh["name"],
+ "checks": [
+ "non_manifold_edges",
+ "self_intersections",
+ "degenerate_faces",
+ "duplicate_faces",
+ "duplicate_points",
+ "orientation",
+ ],
+ "status": "pending_macro_execution",
+ }
+
+
+def mesh_boolean(
+ project: Dict[str, Any],
+ op: str,
+ base_index: int,
+ tool_index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Perform a boolean operation between two meshes.
+
+ Creates a new mesh entry representing the result.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ op : str
+ One of ``"union"``, ``"difference"``, or ``"intersection"``.
+ base_index : int
+ Index of the base mesh.
+ tool_index : int
+ Index of the tool mesh.
+ name : str or None
+ Label for the result mesh.
+
+ Returns
+ -------
+ dict
+ The newly created result mesh entry.
+
+ Raises
+ ------
+ ValueError
+ If *op* is unknown or indices are equal.
+ IndexError
+ If either index is out of range.
+ """
+ if op not in MESH_BOOLEAN_OPS:
+ valid = ", ".join(sorted(MESH_BOOLEAN_OPS))
+ raise ValueError(f"Unknown mesh boolean op '{op}'. Valid: {valid}")
+
+ if base_index == tool_index:
+ raise ValueError("base_index and tool_index must differ")
+
+ base_mesh = _get_mesh(project, base_index)
+ tool_mesh = _get_mesh(project, tool_index)
+
+ meshes = ensure_collection(project, "meshes")
+
+ if name is None:
+ name = _unique_name(project, f"MeshBool_{op.capitalize()}")
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "source": f"boolean:{op}",
+ "format": "computed",
+ "vertices_count": 0,
+ "faces_count": 0,
+ "operations_applied": [
+ {
+ "op": f"boolean_{op}",
+ "params": {
+ "base_id": base_mesh["id"],
+ "tool_id": tool_mesh["id"],
+ },
+ },
+ ],
+ }
+
+ meshes.append(result)
+ return result
+
+
+def decimate_mesh(
+ project: Dict[str, Any],
+ mesh_index: int,
+ target_faces: int = 1000,
+) -> Dict[str, Any]:
+ """Decimate (simplify) the mesh at *mesh_index*.
+
+ Records a decimation operation targeting *target_faces* triangles.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ mesh_index : int
+ Index of the mesh to decimate.
+ target_faces : int
+ Target number of faces after decimation.
+
+ Returns
+ -------
+ dict
+ The updated mesh entry.
+
+ Raises
+ ------
+ IndexError
+ If *mesh_index* is out of range.
+ ValueError
+ If *target_faces* is not a positive integer.
+ """
+ if not isinstance(target_faces, int) or target_faces <= 0:
+ raise ValueError("target_faces must be a positive integer")
+
+ mesh = _get_mesh(project, mesh_index)
+ mesh["operations_applied"].append({
+ "op": "decimate",
+ "params": {"target_faces": target_faces},
+ })
+ return mesh
+
+
+def remesh_mesh(
+ project: Dict[str, Any],
+ mesh_index: int,
+ target_length: float = 1.0,
+) -> Dict[str, Any]:
+ """Remesh the mesh at *mesh_index* with uniform edge lengths.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ mesh_index : int
+ Index of the mesh to remesh.
+ target_length : float
+ Target edge length for the remeshed output.
+
+ Returns
+ -------
+ dict
+ The updated mesh entry.
+
+ Raises
+ ------
+ IndexError
+ If *mesh_index* is out of range.
+ ValueError
+ If *target_length* is not positive.
+ """
+ if target_length <= 0:
+ raise ValueError("target_length must be a positive number")
+
+ mesh = _get_mesh(project, mesh_index)
+ mesh["operations_applied"].append({
+ "op": "remesh",
+ "params": {"target_length": float(target_length)},
+ })
+ return mesh
+
+
+def smooth_mesh(
+ project: Dict[str, Any],
+ mesh_index: int,
+ iterations: int = 3,
+ factor: float = 0.5,
+) -> Dict[str, Any]:
+ """Apply Laplacian smoothing to the mesh at *mesh_index*.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ mesh_index : int
+ Index of the mesh to smooth.
+ iterations : int
+ Number of smoothing passes (default ``3``).
+ factor : float
+ Smoothing intensity factor between 0 and 1 (default ``0.5``).
+
+ Returns
+ -------
+ dict
+ The updated mesh entry.
+
+ Raises
+ ------
+ IndexError
+ If *mesh_index* is out of range.
+ ValueError
+ If *iterations* or *factor* is invalid.
+ """
+ if not isinstance(iterations, int) or iterations <= 0:
+ raise ValueError("iterations must be a positive integer")
+ if not (0.0 < factor <= 1.0):
+ raise ValueError("factor must be between 0 (exclusive) and 1 (inclusive)")
+
+ mesh = _get_mesh(project, mesh_index)
+ mesh["operations_applied"].append({
+ "op": "smooth",
+ "params": {"iterations": iterations, "factor": float(factor)},
+ })
+ return mesh
+
+
+def repair_mesh(project: Dict[str, Any], mesh_index: int) -> Dict[str, Any]:
+ """Record a repair operation for the mesh at *mesh_index*.
+
+ Repair includes fixing degenerate faces, removing duplicates,
+ harmonising normals, and filling small holes.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ mesh_index : int
+ Index of the mesh to repair.
+
+ Returns
+ -------
+ dict
+ The updated mesh entry.
+ """
+ mesh = _get_mesh(project, mesh_index)
+ mesh["operations_applied"].append({
+ "op": "repair",
+ "params": {},
+ })
+ return mesh
+
+
+def fill_holes(
+ project: Dict[str, Any],
+ mesh_index: int,
+ max_hole_size: int = 10,
+) -> Dict[str, Any]:
+ """Fill holes in the mesh at *mesh_index*.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ mesh_index : int
+ Index of the mesh.
+ max_hole_size : int
+ Maximum number of edges bounding a hole to fill (default ``10``).
+
+ Returns
+ -------
+ dict
+ The updated mesh entry.
+
+ Raises
+ ------
+ ValueError
+ If *max_hole_size* is not a positive integer.
+ """
+ if not isinstance(max_hole_size, int) or max_hole_size <= 0:
+ raise ValueError("max_hole_size must be a positive integer")
+
+ mesh = _get_mesh(project, mesh_index)
+ mesh["operations_applied"].append({
+ "op": "fill_holes",
+ "params": {"max_hole_size": max_hole_size},
+ })
+ return mesh
+
+
+def flip_normals(project: Dict[str, Any], mesh_index: int) -> Dict[str, Any]:
+ """Flip all face normals on the mesh at *mesh_index*.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ mesh_index : int
+ Index of the mesh.
+
+ Returns
+ -------
+ dict
+ The updated mesh entry.
+ """
+ mesh = _get_mesh(project, mesh_index)
+ mesh["operations_applied"].append({
+ "op": "flip_normals",
+ "params": {},
+ })
+ return mesh
+
+
+def merge_meshes(
+ project: Dict[str, Any],
+ indices: List[int],
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Merge multiple meshes into a single mesh.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ indices : list[int]
+ Indices of the meshes to merge.
+ name : str or None
+ Label for the merged mesh.
+
+ Returns
+ -------
+ dict
+ The newly created merged mesh entry.
+
+ Raises
+ ------
+ ValueError
+ If fewer than two indices are supplied or any index is invalid.
+ """
+ if not isinstance(indices, (list, tuple)) or len(indices) < 2:
+ raise ValueError("At least two mesh indices are required for merging")
+
+ source_ids = []
+ for idx in indices:
+ mesh = _get_mesh(project, idx)
+ source_ids.append(mesh["id"])
+
+ meshes = ensure_collection(project, "meshes")
+
+ if name is None:
+ name = _unique_name(project, "MergedMesh")
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "source": "merged",
+ "format": "computed",
+ "vertices_count": 0,
+ "faces_count": 0,
+ "operations_applied": [
+ {"op": "merge", "params": {"source_ids": source_ids}},
+ ],
+ }
+
+ meshes.append(result)
+ return result
+
+
+def split_mesh(project: Dict[str, Any], mesh_index: int) -> Dict[str, Any]:
+ """Split a mesh into its disconnected components.
+
+ Records the split operation. The actual component separation is
+ performed by the FreeCAD macro; this function returns metadata
+ about the request.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ mesh_index : int
+ Index of the mesh to split.
+
+ Returns
+ -------
+ dict
+ Metadata describing the split request.
+ """
+ mesh = _get_mesh(project, mesh_index)
+ mesh["operations_applied"].append({
+ "op": "split",
+ "params": {},
+ })
+ return {
+ "mesh_id": mesh["id"],
+ "name": mesh["name"],
+ "status": "split_pending_macro_execution",
+ }
+
+
+def mesh_to_shape(
+ project: Dict[str, Any],
+ mesh_index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Convert a mesh to a solid shape and add it to ``project["parts"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ mesh_index : int
+ Index of the source mesh.
+ name : str or None
+ Label for the resulting part.
+
+ Returns
+ -------
+ dict
+ The newly created part entry in ``project["parts"]``.
+ """
+ mesh = _get_mesh(project, mesh_index)
+ parts = ensure_collection(project, "parts")
+
+ if name is None:
+ base = f"{mesh['name']}_Solid"
+ existing = {p["name"] for p in parts}
+ if base in existing:
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ base = f"{base}_{counter}"
+ name = base
+
+ # Compute next part id
+ part_id = max((p["id"] for p in parts), default=0) + 1
+
+ part: Dict[str, Any] = {
+ "id": part_id,
+ "name": name,
+ "type": "mesh_to_shape",
+ "params": {
+ "source_mesh_id": mesh["id"],
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ parts.append(part)
+ return part
diff --git a/freecad/agent-harness/cli_anything/freecad/core/parts.py b/freecad/agent-harness/cli_anything/freecad/core/parts.py
new file mode 100644
index 000000000..51aeef8ef
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/parts.py
@@ -0,0 +1,1346 @@
+"""FreeCAD CLI - 3D parts and primitives module.
+
+Manages part creation, removal, transformation, and boolean operations
+on a JSON-based project state. Each part carries its own placement
+(position + rotation) and parameter set derived from FreeCAD primitives.
+"""
+
+import math
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Set, Union
+
+
+# ---------------------------------------------------------------------------
+# Primitive definitions (type -> default parameters)
+# ---------------------------------------------------------------------------
+
+PRIMITIVES: Dict[str, Dict[str, float]] = {
+ "box": {
+ "length": 10.0,
+ "width": 10.0,
+ "height": 10.0,
+ },
+ "cylinder": {
+ "radius": 5.0,
+ "height": 10.0,
+ "angle": 360.0,
+ },
+ "sphere": {
+ "radius": 5.0,
+ "angle1": -90.0,
+ "angle2": 90.0,
+ "angle3": 360.0,
+ },
+ "cone": {
+ "radius1": 5.0,
+ "radius2": 2.5,
+ "height": 10.0,
+ "angle": 360.0,
+ },
+ "torus": {
+ "radius1": 10.0,
+ "radius2": 2.0,
+ "angle1": -180.0,
+ "angle2": 180.0,
+ "angle3": 360.0,
+ },
+ "wedge": {
+ "xmin": 0.0,
+ "ymin": 0.0,
+ "zmin": 0.0,
+ "x2min": 2.0,
+ "z2min": 2.0,
+ "xmax": 10.0,
+ "ymax": 10.0,
+ "zmax": 10.0,
+ "x2max": 8.0,
+ "z2max": 8.0,
+ },
+ "helix": {
+ "pitch": 5.0,
+ "height": 20.0,
+ "radius": 5.0,
+ "angle": 0.0,
+ },
+ "spiral": {
+ "growth": 1.0,
+ "turns": 5.0,
+ "radius": 5.0,
+ },
+ "thread": {
+ "pitch": 1.5,
+ "diameter": 10.0,
+ "length": 20.0,
+ "thread_type": 0.0, # 0 = metric (encoded as float for consistency)
+ },
+ "plane": {
+ "length": 10.0,
+ "width": 10.0,
+ },
+ "polygon_3d": {
+ "sides": 6.0,
+ "radius": 5.0,
+ },
+}
+
+BOOLEAN_OPS: Set[str] = {"cut", "fuse", "common"}
+
+
+# ---------------------------------------------------------------------------
+# Helper functions
+# ---------------------------------------------------------------------------
+
+def _next_id(project: Dict[str, Any], key: str = "parts") -> int:
+ """Return the next available integer ID for *key* in *project*.
+
+ Scans existing items under ``project[key]`` and returns one more than
+ the current maximum ``id`` value, or ``1`` if the list is empty.
+ """
+ items = project.get(key, [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(
+ project: Dict[str, Any], base: str, key: str = "parts"
+) -> str:
+ """Return a unique name derived from *base* inside ``project[key]``.
+
+ If *base* is not yet taken the string is returned as-is; otherwise a
+ numeric suffix is appended (e.g. ``Box_2``, ``Box_3``).
+ """
+ existing = {item["name"] for item in project.get(key, [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _validate_vec3(value: Any, label: str) -> List[float]:
+ """Validate that *value* is a list of exactly three numbers.
+
+ Returns the value normalised to a list of Python floats.
+
+ Raises ``ValueError`` with a descriptive message on failure.
+ """
+ if not isinstance(value, (list, tuple)):
+ raise ValueError(f"{label} must be a list of 3 numbers, got {type(value).__name__}")
+ if len(value) != 3:
+ raise ValueError(f"{label} must have exactly 3 elements, got {len(value)}")
+ try:
+ return [float(v) for v in value]
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} elements must be numeric: {exc}") from exc
+
+
+# ---------------------------------------------------------------------------
+# Core functions
+# ---------------------------------------------------------------------------
+
+def add_part(
+ project: Dict[str, Any],
+ part_type: str = "box",
+ name: Optional[str] = None,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+ params: Optional[Dict[str, float]] = None,
+) -> Dict[str, Any]:
+ """Create a new primitive part and append it to ``project["parts"]``.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary. Must contain a ``"parts"``
+ list (created automatically if missing).
+ part_type : str
+ One of the keys in :data:`PRIMITIVES`.
+ name : str or None
+ Human-readable label. When *None* a unique name is derived from
+ *part_type* (e.g. ``"Box"``, ``"Cylinder_2"``).
+ position : list[float] or None
+ ``[x, y, z]`` translation. Defaults to ``[0, 0, 0]``.
+ rotation : list[float] or None
+ ``[x, y, z]`` Euler rotation in degrees. Defaults to ``[0, 0, 0]``.
+ params : dict or None
+ Parameter overrides merged on top of the primitive defaults.
+
+ Returns
+ -------
+ dict
+ The newly created part dictionary.
+
+ Raises
+ ------
+ ValueError
+ If *part_type* is unknown or vector arguments are invalid.
+ """
+ # Validate part type
+ if part_type not in PRIMITIVES:
+ valid = ", ".join(sorted(PRIMITIVES))
+ raise ValueError(f"Unknown part_type '{part_type}'. Valid types: {valid}")
+
+ # Ensure the parts list exists
+ if "parts" not in project:
+ project["parts"] = []
+
+ # Validate / default placement vectors
+ pos = _validate_vec3(position, "position") if position is not None else [0.0, 0.0, 0.0]
+ rot = _validate_vec3(rotation, "rotation") if rotation is not None else [0.0, 0.0, 0.0]
+
+ # Merge parameters
+ merged_params = deepcopy(PRIMITIVES[part_type])
+ if params:
+ unknown = set(params) - set(merged_params)
+ if unknown:
+ raise ValueError(
+ f"Unknown parameter(s) for '{part_type}': {', '.join(sorted(unknown))}. "
+ f"Valid: {', '.join(sorted(merged_params))}"
+ )
+ for k, v in params.items():
+ try:
+ merged_params[k] = float(v)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"Parameter '{k}' must be numeric: {exc}") from exc
+
+ # Build the name
+ if name is None:
+ base = part_type.capitalize()
+ name = _unique_name(project, base)
+
+ part: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": part_type,
+ "params": merged_params,
+ "placement": {
+ "position": pos,
+ "rotation": rot,
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ project["parts"].append(part)
+ return part
+
+
+def remove_part(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Remove and return the part at *index* in ``project["parts"]``.
+
+ Raises ``IndexError`` when the index is out of range.
+ """
+ parts = project.get("parts", [])
+ if not isinstance(index, int) or index < 0 or index >= len(parts):
+ raise IndexError(
+ f"Part index {index} out of range (0..{len(parts) - 1})"
+ )
+ return parts.pop(index)
+
+
+def list_parts(project: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return all parts in the project."""
+ return project.get("parts", [])
+
+
+def get_part(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the part at *index* without removing it.
+
+ Raises ``IndexError`` when the index is out of range.
+ """
+ parts = project.get("parts", [])
+ if not isinstance(index, int) or index < 0 or index >= len(parts):
+ raise IndexError(
+ f"Part index {index} out of range (0..{len(parts) - 1})"
+ )
+ return parts[index]
+
+
+def transform_part(
+ project: Dict[str, Any],
+ index: int,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Update the placement of the part at *index*.
+
+ Only the supplied vectors are changed; the other is left untouched.
+
+ Returns the updated part dictionary.
+ """
+ part = get_part(project, index)
+
+ if position is not None:
+ part["placement"]["position"] = _validate_vec3(position, "position")
+ if rotation is not None:
+ part["placement"]["rotation"] = _validate_vec3(rotation, "rotation")
+
+ return part
+
+
+def boolean_op(
+ project: Dict[str, Any],
+ op: str,
+ base_index: int,
+ tool_index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Perform a boolean operation between two parts.
+
+ Creates a new part of ``type=op`` that references the *base* and *tool*
+ parts by their IDs. Both source parts are marked ``visible=False``.
+
+ Parameters
+ ----------
+ op : str
+ One of ``"cut"``, ``"fuse"``, or ``"common"``.
+ base_index : int
+ Index of the base (kept) shape in ``project["parts"]``.
+ tool_index : int
+ Index of the tool shape in ``project["parts"]``.
+ name : str or None
+ Label for the result. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created boolean-result part.
+
+ Raises
+ ------
+ ValueError
+ If *op* is unknown or indices are equal.
+ IndexError
+ If either index is out of range.
+ """
+ if op not in BOOLEAN_OPS:
+ valid = ", ".join(sorted(BOOLEAN_OPS))
+ raise ValueError(f"Unknown boolean op '{op}'. Valid: {valid}")
+
+ if base_index == tool_index:
+ raise ValueError("base_index and tool_index must differ")
+
+ base_part = get_part(project, base_index)
+ tool_part = get_part(project, tool_index)
+
+ # Mark operands as hidden
+ base_part["visible"] = False
+ tool_part["visible"] = False
+
+ # Ensure the parts list exists
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base_name = op.capitalize()
+ name = _unique_name(project, base_name)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": op,
+ "params": {
+ "base_id": base_part["id"],
+ "tool_id": tool_part["id"],
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Extended operations
+# ---------------------------------------------------------------------------
+
+def copy_part(
+ project: Dict[str, Any],
+ index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Deep-copy the part at *index* and append the copy to the project.
+
+ The copy receives a new unique ``id`` and (optionally) a new *name*.
+ All other attributes — parameters, placement, material — are duplicated.
+
+ Returns the newly created part dictionary.
+ """
+ source = get_part(project, index)
+ new_part: Dict[str, Any] = deepcopy(source)
+ new_part["id"] = _next_id(project)
+
+ if name is None:
+ base = f"{source['name']}_copy"
+ name = _unique_name(project, base)
+ new_part["name"] = name
+
+ project["parts"].append(new_part)
+ return new_part
+
+
+def mirror_part(
+ project: Dict[str, Any],
+ index: int,
+ plane: str = "XY",
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a mirrored copy of the part at *index*.
+
+ Parameters
+ ----------
+ plane : str
+ Mirror plane — one of ``"XY"``, ``"XZ"``, or ``"YZ"``.
+ name : str or None
+ Label for the result. Auto-generated when *None*.
+
+ Returns the newly created mirror part.
+ """
+ valid_planes = {"XY", "XZ", "YZ"}
+ if plane not in valid_planes:
+ raise ValueError(
+ f"Unknown mirror plane '{plane}'. Valid: {', '.join(sorted(valid_planes))}"
+ )
+
+ source = get_part(project, index)
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = f"{source['name']}_mirror"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "mirror",
+ "params": {
+ "original_id": source["id"],
+ "mirror_plane": plane,
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def scale_part(
+ project: Dict[str, Any],
+ index: int,
+ factor: Union[float, List[float]],
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a uniformly (or non-uniformly) scaled copy of a part.
+
+ Parameters
+ ----------
+ factor : float or list[float]
+ A single number for uniform scaling, or ``[sx, sy, sz]`` for
+ per-axis scaling.
+ """
+ source = get_part(project, index)
+
+ if isinstance(factor, (list, tuple)):
+ scale_vec = _validate_vec3(factor, "factor")
+ else:
+ try:
+ sf = float(factor)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"factor must be numeric: {exc}") from exc
+ scale_vec = [sf, sf, sf]
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = f"{source['name']}_scaled"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "scale",
+ "params": {
+ "original_id": source["id"],
+ "scale": scale_vec,
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def offset_shape(
+ project: Dict[str, Any],
+ index: int,
+ distance: float,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create an offset shell of the part at *index*.
+
+ Parameters
+ ----------
+ distance : float
+ Offset distance. Positive grows outward, negative shrinks inward.
+ """
+ source = get_part(project, index)
+
+ try:
+ dist = float(distance)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"distance must be numeric: {exc}") from exc
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = f"{source['name']}_offset"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "offset",
+ "params": {
+ "original_id": source["id"],
+ "distance": dist,
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def thickness_part(
+ project: Dict[str, Any],
+ index: int,
+ thickness: float,
+ faces: str = "all",
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Hollow a solid by applying a wall *thickness*.
+
+ Parameters
+ ----------
+ thickness : float
+ Wall thickness value.
+ faces : str
+ Which faces to open — ``"all"`` or a comma-separated list of
+ face indices (e.g. ``"0,2,5"``).
+ """
+ source = get_part(project, index)
+
+ try:
+ thick = float(thickness)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"thickness must be numeric: {exc}") from exc
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = f"{source['name']}_thickness"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "thickness",
+ "params": {
+ "original_id": source["id"],
+ "thickness": thick,
+ "faces": faces,
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def compound_parts(
+ project: Dict[str, Any],
+ indices: List[int],
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Group several parts into a compound.
+
+ The source parts are marked ``visible=False``; the compound is
+ visible and stores references to its children by ID.
+
+ Parameters
+ ----------
+ indices : list[int]
+ Indices of the parts to group.
+ """
+ if not indices:
+ raise ValueError("indices must be a non-empty list")
+
+ child_ids: List[int] = []
+ for idx in indices:
+ part = get_part(project, idx)
+ part["visible"] = False
+ child_ids.append(part["id"])
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = "Compound"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "compound",
+ "params": {
+ "compound_children": child_ids,
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def explode_compound(
+ project: Dict[str, Any],
+ index: int,
+) -> List[Dict[str, Any]]:
+ """Break a compound back into its individual child parts.
+
+ The compound part is marked ``visible=False`` and each child part
+ is restored to ``visible=True``.
+
+ Returns the list of (now visible) child part dictionaries.
+ """
+ compound = get_part(project, index)
+ if compound.get("type") != "compound":
+ raise ValueError(
+ f"Part at index {index} is not a compound (type='{compound.get('type')}')"
+ )
+
+ compound["visible"] = False
+
+ child_ids = set(compound["params"].get("compound_children", []))
+ restored: List[Dict[str, Any]] = []
+ for part in project.get("parts", []):
+ if part["id"] in child_ids:
+ part["visible"] = True
+ restored.append(part)
+
+ return restored
+
+
+def fillet_3d(
+ project: Dict[str, Any],
+ index: int,
+ radius: float,
+ edges: str = "all",
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Apply a Part-level 3-D fillet to the part at *index*.
+
+ Parameters
+ ----------
+ radius : float
+ Fillet radius.
+ edges : str
+ Which edges to fillet — ``"all"`` or a comma-separated list of
+ edge indices.
+ """
+ source = get_part(project, index)
+
+ try:
+ rad = float(radius)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"radius must be numeric: {exc}") from exc
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = f"{source['name']}_fillet3d"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "fillet_3d",
+ "params": {
+ "original_id": source["id"],
+ "radius": rad,
+ "edges": edges,
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def chamfer_3d(
+ project: Dict[str, Any],
+ index: int,
+ size: float,
+ edges: str = "all",
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Apply a Part-level 3-D chamfer to the part at *index*.
+
+ Parameters
+ ----------
+ size : float
+ Chamfer size (distance).
+ edges : str
+ Which edges to chamfer — ``"all"`` or a comma-separated list of
+ edge indices.
+ """
+ source = get_part(project, index)
+
+ try:
+ sz = float(size)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"size must be numeric: {exc}") from exc
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = f"{source['name']}_chamfer3d"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "chamfer_3d",
+ "params": {
+ "original_id": source["id"],
+ "size": sz,
+ "edges": edges,
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def loft_parts(
+ project: Dict[str, Any],
+ section_indices: List[int],
+ solid: bool = True,
+ ruled: bool = False,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Loft through a series of cross-section parts.
+
+ Parameters
+ ----------
+ section_indices : list[int]
+ Ordered indices of the profile/section parts.
+ solid : bool
+ Whether to create a solid (True) or a shell (False).
+ ruled : bool
+ Whether to use ruled surfaces between sections.
+ """
+ if len(section_indices) < 2:
+ raise ValueError("loft requires at least 2 section indices")
+
+ section_ids: List[int] = []
+ for idx in section_indices:
+ part = get_part(project, idx)
+ section_ids.append(part["id"])
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = "Loft"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "loft",
+ "params": {
+ "section_ids": section_ids,
+ "solid": solid,
+ "ruled": ruled,
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def sweep_part(
+ project: Dict[str, Any],
+ profile_index: int,
+ path_index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Sweep a profile shape along a path shape.
+
+ Parameters
+ ----------
+ profile_index : int
+ Index of the profile (cross-section) part.
+ path_index : int
+ Index of the path (spine) part.
+ """
+ profile = get_part(project, profile_index)
+ path = get_part(project, path_index)
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = "Sweep"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "sweep",
+ "params": {
+ "profile_id": profile["id"],
+ "path_id": path["id"],
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def revolve_part(
+ project: Dict[str, Any],
+ index: int,
+ axis: str = "Z",
+ angle: float = 360.0,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Revolve the part at *index* around an axis.
+
+ Parameters
+ ----------
+ axis : str
+ Axis of revolution — ``"X"``, ``"Y"``, or ``"Z"``.
+ angle : float
+ Revolution angle in degrees (default 360 for a full revolution).
+ """
+ valid_axes = {"X", "Y", "Z"}
+ if axis not in valid_axes:
+ raise ValueError(
+ f"Unknown axis '{axis}'. Valid: {', '.join(sorted(valid_axes))}"
+ )
+
+ source = get_part(project, index)
+
+ try:
+ ang = float(angle)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"angle must be numeric: {exc}") from exc
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = f"{source['name']}_revolve"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "revolve",
+ "params": {
+ "original_id": source["id"],
+ "axis": axis,
+ "angle": ang,
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def extrude_part(
+ project: Dict[str, Any],
+ index: int,
+ direction: Optional[List[float]] = None,
+ length: float = 10.0,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Extrude the part at *index* along a direction vector.
+
+ Parameters
+ ----------
+ direction : list[float] or None
+ ``[dx, dy, dz]`` unit direction. Defaults to ``[0, 0, 1]``.
+ length : float
+ Extrusion length.
+ """
+ source = get_part(project, index)
+
+ dir_vec = _validate_vec3(direction, "direction") if direction is not None else [0.0, 0.0, 1.0]
+
+ try:
+ lng = float(length)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"length must be numeric: {exc}") from exc
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = f"{source['name']}_extrude"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "extrude",
+ "params": {
+ "original_id": source["id"],
+ "direction": dir_vec,
+ "length": lng,
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def section_part(
+ project: Dict[str, Any],
+ index: int,
+ plane: str = "XY",
+ offset: float = 0.0,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a cross-section of the part at *index*.
+
+ Parameters
+ ----------
+ plane : str
+ Cutting plane — ``"XY"``, ``"XZ"``, or ``"YZ"``.
+ offset : float
+ Distance to shift the cutting plane along its normal.
+ """
+ valid_planes = {"XY", "XZ", "YZ"}
+ if plane not in valid_planes:
+ raise ValueError(
+ f"Unknown section plane '{plane}'. Valid: {', '.join(sorted(valid_planes))}"
+ )
+
+ source = get_part(project, index)
+
+ try:
+ off = float(offset)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"offset must be numeric: {exc}") from exc
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = f"{source['name']}_section"
+ name = _unique_name(project, base)
+
+ result: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "section",
+ "params": {
+ "original_id": source["id"],
+ "plane": plane,
+ "offset": off,
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+
+ project["parts"].append(result)
+ return result
+
+
+def slice_part(
+ project: Dict[str, Any],
+ index: int,
+ plane: str = "XY",
+ offset: float = 0.0,
+) -> Dict[str, Any]:
+ """Slice the part at *index* into two halves along a plane.
+
+ The original part is marked ``visible=False`` and two new parts are
+ created — one for each side of the cutting plane.
+
+ Returns a dict with keys ``"positive"`` and ``"negative"``, each
+ holding the newly created part dictionary, plus ``"positive_index"``
+ and ``"negative_index"`` with their list positions.
+ """
+ valid_planes = {"XY", "XZ", "YZ"}
+ if plane not in valid_planes:
+ raise ValueError(
+ f"Unknown slice plane '{plane}'. Valid: {', '.join(sorted(valid_planes))}"
+ )
+
+ source = get_part(project, index)
+
+ try:
+ off = float(offset)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"offset must be numeric: {exc}") from exc
+
+ source["visible"] = False
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ pos_name = _unique_name(project, f"{source['name']}_slice_pos")
+ pos_part: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": pos_name,
+ "type": "slice",
+ "params": {
+ "original_id": source["id"],
+ "plane": plane,
+ "offset": off,
+ "side": "positive",
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+ project["parts"].append(pos_part)
+ pos_index = len(project["parts"]) - 1
+
+ neg_name = _unique_name(project, f"{source['name']}_slice_neg")
+ neg_part: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": neg_name,
+ "type": "slice",
+ "params": {
+ "original_id": source["id"],
+ "plane": plane,
+ "offset": off,
+ "side": "negative",
+ },
+ "placement": deepcopy(source["placement"]),
+ "material_index": source.get("material_index"),
+ "visible": True,
+ }
+ project["parts"].append(neg_part)
+ neg_index = len(project["parts"]) - 1
+
+ return {
+ "positive": pos_part,
+ "negative": neg_part,
+ "positive_index": pos_index,
+ "negative_index": neg_index,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Additional geometry creators
+# ---------------------------------------------------------------------------
+
+def add_line_3d(
+ project: Dict[str, Any],
+ start: Optional[List[float]] = None,
+ end: Optional[List[float]] = None,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Add a 3-D line (edge) between two points.
+
+ Parameters
+ ----------
+ start : list[float] or None
+ ``[x, y, z]`` start point. Defaults to ``[0, 0, 0]``.
+ end : list[float] or None
+ ``[x, y, z]`` end point. Defaults to ``[10, 0, 0]``.
+
+ Returns the newly created part.
+ """
+ s = _validate_vec3(start, "start") if start is not None else [0.0, 0.0, 0.0]
+ e = _validate_vec3(end, "end") if end is not None else [10.0, 0.0, 0.0]
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = "Line3D"
+ name = _unique_name(project, base)
+
+ part: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "line_3d",
+ "params": {
+ "start": s,
+ "end": e,
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ project["parts"].append(part)
+ return part
+
+
+def add_wire(
+ project: Dict[str, Any],
+ points: List[List[float]],
+ closed: bool = False,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Add a wire (polyline) from a list of ``[x, y, z]`` points.
+
+ Parameters
+ ----------
+ points : list[list[float]]
+ Ordered vertices. Must contain at least 2 points.
+ closed : bool
+ If *True* the wire forms a closed loop.
+
+ Returns the newly created part.
+ """
+ if not isinstance(points, (list, tuple)) or len(points) < 2:
+ raise ValueError("points must be a list of at least 2 [x,y,z] vertices")
+
+ validated: List[List[float]] = []
+ for i, pt in enumerate(points):
+ validated.append(_validate_vec3(pt, f"points[{i}]"))
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = "Wire"
+ name = _unique_name(project, base)
+
+ part: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "wire",
+ "params": {
+ "points": validated,
+ "closed": closed,
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ project["parts"].append(part)
+ return part
+
+
+def add_polygon_3d(
+ project: Dict[str, Any],
+ center: Optional[List[float]] = None,
+ sides: int = 6,
+ radius: float = 5.0,
+ normal: Optional[List[float]] = None,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Add a regular polygon in 3-D space.
+
+ Parameters
+ ----------
+ center : list[float] or None
+ ``[x, y, z]`` center point. Defaults to ``[0, 0, 0]``.
+ sides : int
+ Number of sides (>= 3).
+ radius : float
+ Circumscribed-circle radius.
+ normal : list[float] or None
+ ``[nx, ny, nz]`` plane normal. Defaults to ``[0, 0, 1]``.
+
+ Returns the newly created part.
+ """
+ c = _validate_vec3(center, "center") if center is not None else [0.0, 0.0, 0.0]
+ n = _validate_vec3(normal, "normal") if normal is not None else [0.0, 0.0, 1.0]
+
+ if not isinstance(sides, int) or sides < 3:
+ raise ValueError(f"sides must be an integer >= 3, got {sides}")
+
+ try:
+ rad = float(radius)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"radius must be numeric: {exc}") from exc
+
+ if "parts" not in project:
+ project["parts"] = []
+
+ if name is None:
+ base = "Polygon3D"
+ name = _unique_name(project, base)
+
+ part: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "polygon_3d",
+ "params": {
+ "center": c,
+ "sides": float(sides),
+ "radius": rad,
+ "normal": n,
+ },
+ "placement": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+ project["parts"].append(part)
+ return part
+
+
+# ---------------------------------------------------------------------------
+# Part info query
+# ---------------------------------------------------------------------------
+
+def _estimate_geometry(part_type: str, params: Dict[str, Any]) -> Dict[str, Any]:
+ """Compute estimated volume, surface area, and bounding box from params.
+
+ Returns a dict with keys ``volume``, ``area``, and ``bounding_box``
+ (each may be *None* when computation is not applicable).
+ """
+ volume: Optional[float] = None
+ area: Optional[float] = None
+ bbox: Optional[Dict[str, float]] = None
+
+ if part_type == "box":
+ l, w, h = params["length"], params["width"], params["height"]
+ volume = l * w * h
+ area = 2.0 * (l * w + w * h + l * h)
+ bbox = {"x": l, "y": w, "z": h}
+
+ elif part_type == "cylinder":
+ r, h = params["radius"], params["height"]
+ volume = math.pi * r * r * h
+ area = 2.0 * math.pi * r * (r + h)
+ bbox = {"x": 2 * r, "y": 2 * r, "z": h}
+
+ elif part_type == "sphere":
+ r = params["radius"]
+ volume = (4.0 / 3.0) * math.pi * r ** 3
+ area = 4.0 * math.pi * r ** 2
+ bbox = {"x": 2 * r, "y": 2 * r, "z": 2 * r}
+
+ elif part_type == "cone":
+ r1, r2, h = params["radius1"], params["radius2"], params["height"]
+ volume = math.pi * h / 3.0 * (r1 ** 2 + r1 * r2 + r2 ** 2)
+ # Lateral + two caps
+ slant = math.sqrt(h ** 2 + (r1 - r2) ** 2)
+ area = (
+ math.pi * (r1 + r2) * slant
+ + math.pi * r1 ** 2
+ + math.pi * r2 ** 2
+ )
+ rmax = max(r1, r2)
+ bbox = {"x": 2 * rmax, "y": 2 * rmax, "z": h}
+
+ elif part_type == "torus":
+ R, r = params["radius1"], params["radius2"]
+ volume = 2.0 * math.pi ** 2 * R * r ** 2
+ area = 4.0 * math.pi ** 2 * R * r
+ bbox = {"x": 2 * (R + r), "y": 2 * (R + r), "z": 2 * r}
+
+ return {
+ "volume": volume,
+ "area": area,
+ "bounding_box": bbox,
+ }
+
+
+def part_info(
+ project: Dict[str, Any],
+ index: int,
+) -> Dict[str, Any]:
+ """Return detailed information about the part at *index*.
+
+ The returned dictionary includes:
+
+ - ``type`` — the part type string.
+ - ``params`` — a copy of the part's parameter dict.
+ - ``placement`` — position and rotation.
+ - ``material_index`` — index into the materials list (or *None*).
+ - ``visible`` — visibility flag.
+ - ``volume`` — estimated volume (or *None* if not computable).
+ - ``area`` — estimated surface area (or *None*).
+ - ``bounding_box`` — estimated axis-aligned bounding box ``{x, y, z}``
+ (or *None*).
+ """
+ part = get_part(project, index)
+ geo = _estimate_geometry(part["type"], part.get("params", {}))
+
+ return {
+ "id": part["id"],
+ "name": part["name"],
+ "type": part["type"],
+ "params": deepcopy(part["params"]),
+ "placement": deepcopy(part["placement"]),
+ "material_index": part.get("material_index"),
+ "visible": part.get("visible", True),
+ "volume": geo["volume"],
+ "area": geo["area"],
+ "bounding_box": geo["bounding_box"],
+ }
diff --git a/freecad/agent-harness/cli_anything/freecad/core/session.py b/freecad/agent-harness/cli_anything/freecad/core/session.py
new file mode 100644
index 000000000..9580634e5
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/session.py
@@ -0,0 +1,209 @@
+"""
+Session management for FreeCAD CLI harness.
+
+Handles project state, undo/redo history, and session persistence
+with atomic file locking for safe concurrent access.
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import os
+import time
+from typing import Any, Dict, List, Optional
+
+
+def _locked_save_json(path: str, data: Any, **dump_kwargs: Any) -> None:
+ """Persist JSON data to *path* using atomic file locking.
+
+ Opens with ``"r+"`` to avoid truncation before the lock is acquired.
+ Falls back to ``"w"`` when the file does not yet exist. On platforms
+ that lack :mod:`fcntl` (Windows) the write proceeds without locking.
+ """
+ try:
+ f = open(path, "r+")
+ except FileNotFoundError:
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ f = open(path, "w")
+
+ with f:
+ _locked = False
+ try:
+ import fcntl
+
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)
+ _locked = True
+ except (ImportError, OSError):
+ pass
+ try:
+ f.seek(0)
+ f.truncate()
+ json.dump(data, f, **dump_kwargs)
+ f.flush()
+ finally:
+ if _locked:
+ import fcntl as _fcntl
+
+ _fcntl.flock(f.fileno(), _fcntl.LOCK_UN)
+
+
+class Session:
+ """Manages project state, undo/redo snapshots and persistence for a FreeCAD project."""
+
+ MAX_UNDO: int = 50
+
+ def __init__(self) -> None:
+ self.project: Optional[Dict] = None
+ self.project_path: Optional[str] = None
+ self._undo_stack: List[Dict] = []
+ self._redo_stack: List[Dict] = []
+ self._modified: bool = False
+
+ # -- project access --------------------------------------------------------
+
+ def get_project(self) -> Dict:
+ """Return the current project dict.
+
+ Raises :class:`RuntimeError` if no project is loaded.
+ """
+ if self.project is None:
+ raise RuntimeError("No project is currently loaded.")
+ return self.project
+
+ def set_project(self, project: Dict, path: Optional[str] = None) -> None:
+ """Replace the current project, clearing all undo/redo history."""
+ self.project = project
+ if path is not None:
+ self.project_path = path
+ self._undo_stack.clear()
+ self._redo_stack.clear()
+ self._modified = False
+
+ # -- snapshot / undo / redo ------------------------------------------------
+
+ def snapshot(self, description: str = "") -> None:
+ """Save a deep copy of the current project state before a mutation.
+
+ The redo stack is cleared on every new snapshot. When the undo
+ stack exceeds :attr:`MAX_UNDO`, the oldest entry is discarded
+ (FIFO).
+ """
+ if self.project is None:
+ return
+
+ entry: Dict = {
+ "timestamp": time.time(),
+ "description": description,
+ "state": copy.deepcopy(self.project),
+ }
+ self._undo_stack.append(entry)
+
+ # FIFO limit
+ if len(self._undo_stack) > self.MAX_UNDO:
+ self._undo_stack.pop(0)
+
+ self._redo_stack.clear()
+ self._modified = True
+
+ def undo(self) -> Optional[str]:
+ """Restore the previous project state.
+
+ Returns the snapshot description, or ``None`` if there is nothing
+ to undo.
+ """
+ if not self._undo_stack:
+ return None
+
+ # Save current state onto redo stack before restoring.
+ redo_entry: Dict = {
+ "timestamp": time.time(),
+ "description": self._undo_stack[-1].get("description", ""),
+ "state": copy.deepcopy(self.project),
+ }
+ self._redo_stack.append(redo_entry)
+
+ entry = self._undo_stack.pop()
+ self.project = entry["state"]
+ self._modified = True
+ return entry.get("description", "")
+
+ def redo(self) -> Optional[str]:
+ """Restore the next project state after an undo.
+
+ Returns the snapshot description, or ``None`` if there is nothing
+ to redo.
+ """
+ if not self._redo_stack:
+ return None
+
+ # Save current state onto undo stack before restoring.
+ undo_entry: Dict = {
+ "timestamp": time.time(),
+ "description": self._redo_stack[-1].get("description", ""),
+ "state": copy.deepcopy(self.project),
+ }
+ self._undo_stack.append(undo_entry)
+
+ entry = self._redo_stack.pop()
+ self.project = entry["state"]
+ self._modified = True
+ return entry.get("description", "")
+
+ # -- persistence -----------------------------------------------------------
+
+ def save_session(self, path: Optional[str] = None) -> str:
+ """Persist the current project to disk using atomic file locking.
+
+ Parameters
+ ----------
+ path:
+ Destination file path. Falls back to :attr:`project_path`.
+
+ Returns
+ -------
+ str
+ The absolute path the project was saved to.
+
+ Raises
+ ------
+ ValueError
+ If no path is available.
+ RuntimeError
+ If no project is loaded.
+ """
+ save_path = path or self.project_path
+ if save_path is None:
+ raise ValueError("No save path specified and no project_path set.")
+ if self.project is None:
+ raise RuntimeError("No project is currently loaded.")
+
+ save_path = os.path.abspath(save_path)
+ _locked_save_json(save_path, self.project, indent=2, default=str)
+
+ self.project_path = save_path
+ self._modified = False
+ return save_path
+
+ # -- query helpers ---------------------------------------------------------
+
+ def status(self) -> Dict:
+ """Return a summary of the current session state."""
+ return {
+ "has_project": self.project is not None,
+ "project_path": self.project_path,
+ "modified": self._modified,
+ "undo_depth": len(self._undo_stack),
+ "redo_depth": len(self._redo_stack),
+ }
+
+ def list_history(self) -> List[Dict]:
+ """Return the undo stack in reverse chronological order (newest first)."""
+ return [
+ {
+ "index": i,
+ "timestamp": entry["timestamp"],
+ "description": entry.get("description", ""),
+ }
+ for i, entry in reversed(list(enumerate(self._undo_stack)))
+ ]
diff --git a/freecad/agent-harness/cli_anything/freecad/core/sketch.py b/freecad/agent-harness/cli_anything/freecad/core/sketch.py
new file mode 100644
index 000000000..7a72f1aba
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/sketch.py
@@ -0,0 +1,1612 @@
+"""
+Sketch module for 2D constraint-based sketching in the FreeCAD CLI harness.
+
+Provides creation and manipulation of parametric sketches with lines, circles,
+arcs, rectangles, and geometric/dimensional constraints.
+"""
+
+import math
+from typing import Any, Dict, List, Optional
+
+
+# ---------------------------------------------------------------------------
+# Valid constants
+# ---------------------------------------------------------------------------
+
+VALID_PLANES = {"XY", "XZ", "YZ"}
+
+VALID_CONSTRAINT_TYPES = {
+ "coincident",
+ "horizontal",
+ "vertical",
+ "parallel",
+ "perpendicular",
+ "equal",
+ "fixed",
+ "distance",
+ "angle",
+ "radius",
+ "tangent",
+ "symmetric",
+ "block",
+ "diameter",
+ "point_on_object",
+ "distance_x",
+ "distance_y",
+}
+
+# Constraints that require a numeric value
+VALUED_CONSTRAINTS = {"distance", "angle", "radius", "diameter", "distance_x", "distance_y"}
+
+# Minimum number of element references each constraint type requires
+CONSTRAINT_MIN_ELEMENTS = {
+ "coincident": 2,
+ "horizontal": 1,
+ "vertical": 1,
+ "parallel": 2,
+ "perpendicular": 2,
+ "equal": 2,
+ "fixed": 1,
+ "distance": 1,
+ "angle": 1,
+ "radius": 1,
+ "tangent": 2,
+ "symmetric": 3,
+ "block": 1,
+ "diameter": 1,
+ "point_on_object": 2,
+ "distance_x": 1,
+ "distance_y": 1,
+}
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _next_id(project: Dict[str, Any], collection_key: str = "sketches") -> int:
+ """Generate the next unique ID for a collection."""
+ items = project.get(collection_key, [])
+ existing_ids = [item.get("id", 0) for item in items]
+ return max(existing_ids, default=-1) + 1
+
+
+def _unique_name(project: Dict[str, Any], base_name: str, collection_key: str = "sketches") -> str:
+ """Generate a unique name within a collection."""
+ items = project.get(collection_key, [])
+ existing_names = {item.get("name", "") for item in items}
+ if base_name not in existing_names:
+ return base_name
+ counter = 1
+ while f"{base_name}.{counter:03d}" in existing_names:
+ counter += 1
+ return f"{base_name}.{counter:03d}"
+
+
+def _next_element_id(sketch: Dict[str, Any]) -> int:
+ """Generate the next unique element ID within a sketch."""
+ elements = sketch.get("elements", [])
+ existing_ids = [el.get("id", 0) for el in elements]
+ return max(existing_ids, default=-1) + 1
+
+
+def _next_constraint_id(sketch: Dict[str, Any]) -> int:
+ """Generate the next unique constraint ID within a sketch."""
+ constraints = sketch.get("constraints", [])
+ existing_ids = [c.get("id", 0) for c in constraints]
+ return max(existing_ids, default=-1) + 1
+
+
+def _validate_project(project: Dict[str, Any]) -> None:
+ """Raise ``ValueError`` if *project* is not a valid dict with a sketches list."""
+ if not isinstance(project, dict):
+ raise ValueError("Project must be a dictionary")
+ if "sketches" not in project:
+ raise ValueError("Project is missing 'sketches' collection")
+ if not isinstance(project["sketches"], list):
+ raise ValueError("Project 'sketches' must be a list")
+
+
+def _get_sketch(project: Dict[str, Any], sketch_index: int) -> Dict[str, Any]:
+ """Return sketch at *sketch_index* or raise ``IndexError``."""
+ sketches = project["sketches"]
+ if sketch_index < 0 or sketch_index >= len(sketches):
+ raise IndexError(
+ f"Sketch index {sketch_index} out of range (0-{len(sketches) - 1})"
+ )
+ return sketches[sketch_index]
+
+
+def _validate_point_2d(point: List[float], label: str = "point") -> List[float]:
+ """Validate and return a 2D point as a list of two floats."""
+ if not isinstance(point, (list, tuple)) or len(point) != 2:
+ raise ValueError(f"{label} must be a list of 2 numbers, got {point!r}")
+ try:
+ return [float(point[0]), float(point[1])]
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} components must be numeric: {exc}") from exc
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def create_sketch(
+ project: Dict[str, Any],
+ name: Optional[str] = None,
+ plane: str = "XY",
+ offset: float = 0.0,
+) -> Dict[str, Any]:
+ """Create a new sketch on the specified plane.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ name:
+ Optional sketch name. Auto-generated if ``None``.
+ plane:
+ Reference plane: ``"XY"``, ``"XZ"``, or ``"YZ"``.
+ offset:
+ Offset distance from the reference plane.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created sketch dictionary.
+
+ Raises
+ ------
+ ValueError
+ If the plane is invalid or the project is malformed.
+ """
+ _validate_project(project)
+
+ plane = plane.upper()
+ if plane not in VALID_PLANES:
+ raise ValueError(
+ f"Invalid plane '{plane}'. Must be one of: {', '.join(sorted(VALID_PLANES))}"
+ )
+
+ offset = float(offset)
+
+ base_name = name if name else "Sketch"
+ sketch_name = _unique_name(project, base_name)
+
+ sketch: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": sketch_name,
+ "plane": plane,
+ "offset": offset,
+ "elements": [],
+ "constraints": [],
+ "closed": False,
+ }
+
+ project["sketches"].append(sketch)
+ return sketch
+
+
+def add_line(
+ project: Dict[str, Any],
+ sketch_index: int,
+ start: Optional[List[float]] = None,
+ end: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a line element to a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch in ``project["sketches"]``.
+ start:
+ Start point ``[x, y]``. Defaults to ``[0, 0]``.
+ end:
+ End point ``[x, y]``. Defaults to ``[10, 0]``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created line element.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ start = _validate_point_2d(start if start is not None else [0, 0], "start")
+ end = _validate_point_2d(end if end is not None else [10, 0], "end")
+
+ if start == end:
+ raise ValueError("Line start and end points must be different")
+
+ element: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "line",
+ "start": start,
+ "end": end,
+ }
+
+ sketch["elements"].append(element)
+ return element
+
+
+def add_circle(
+ project: Dict[str, Any],
+ sketch_index: int,
+ center: Optional[List[float]] = None,
+ radius: float = 5.0,
+) -> Dict[str, Any]:
+ """Add a circle element to a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ center:
+ Center point ``[x, y]``. Defaults to ``[0, 0]``.
+ radius:
+ Circle radius. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created circle element.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ center = _validate_point_2d(center if center is not None else [0, 0], "center")
+ radius = float(radius)
+ if radius <= 0:
+ raise ValueError(f"Radius must be positive, got {radius}")
+
+ element: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "circle",
+ "center": center,
+ "radius": radius,
+ }
+
+ sketch["elements"].append(element)
+ return element
+
+
+def add_rectangle(
+ project: Dict[str, Any],
+ sketch_index: int,
+ corner: Optional[List[float]] = None,
+ width: float = 10.0,
+ height: float = 10.0,
+) -> Dict[str, Any]:
+ """Add a rectangle to a sketch (4 lines + 4 perpendicular constraints).
+
+ The rectangle is axis-aligned with its bottom-left at *corner*.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ corner:
+ Bottom-left corner ``[x, y]``. Defaults to ``[0, 0]``.
+ width:
+ Rectangle width (X extent). Must be positive.
+ height:
+ Rectangle height (Y extent). Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Summary containing the four line element IDs and four constraint IDs.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ corner = _validate_point_2d(corner if corner is not None else [0, 0], "corner")
+ width = float(width)
+ height = float(height)
+ if width <= 0:
+ raise ValueError(f"Width must be positive, got {width}")
+ if height <= 0:
+ raise ValueError(f"Height must be positive, got {height}")
+
+ x, y = corner
+ # Four corners: BL, BR, TR, TL
+ bl = [x, y]
+ br = [x + width, y]
+ tr = [x + width, y + height]
+ tl = [x, y + height]
+
+ # Create four line elements
+ lines: List[Dict[str, Any]] = []
+ for start, end in [(bl, br), (br, tr), (tr, tl), (tl, bl)]:
+ elem: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "line",
+ "start": list(start),
+ "end": list(end),
+ }
+ sketch["elements"].append(elem)
+ lines.append(elem)
+
+ # Add 4 coincident constraints at the corners (each pair of adjacent lines)
+ constraint_ids: List[int] = []
+ for i in range(4):
+ j = (i + 1) % 4
+ constraint: Dict[str, Any] = {
+ "id": _next_constraint_id(sketch),
+ "type": "coincident",
+ "elements": [lines[i]["id"], lines[j]["id"]],
+ "value": None,
+ }
+ sketch["constraints"].append(constraint)
+ constraint_ids.append(constraint["id"])
+
+ return {
+ "type": "rectangle",
+ "line_ids": [line["id"] for line in lines],
+ "constraint_ids": constraint_ids,
+ "corner": corner,
+ "width": width,
+ "height": height,
+ }
+
+
+def add_arc(
+ project: Dict[str, Any],
+ sketch_index: int,
+ center: Optional[List[float]] = None,
+ radius: float = 5.0,
+ start_angle: float = 0.0,
+ end_angle: float = 90.0,
+) -> Dict[str, Any]:
+ """Add an arc element to a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ center:
+ Center point ``[x, y]``. Defaults to ``[0, 0]``.
+ radius:
+ Arc radius. Must be positive.
+ start_angle:
+ Start angle in degrees.
+ end_angle:
+ End angle in degrees. Must differ from *start_angle*.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created arc element.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ center = _validate_point_2d(center if center is not None else [0, 0], "center")
+ radius = float(radius)
+ start_angle = float(start_angle)
+ end_angle = float(end_angle)
+
+ if radius <= 0:
+ raise ValueError(f"Radius must be positive, got {radius}")
+ if start_angle == end_angle:
+ raise ValueError("Start angle and end angle must be different")
+
+ # Compute start/end points for reference
+ start_rad = math.radians(start_angle)
+ end_rad = math.radians(end_angle)
+ start_point = [
+ center[0] + radius * math.cos(start_rad),
+ center[1] + radius * math.sin(start_rad),
+ ]
+ end_point = [
+ center[0] + radius * math.cos(end_rad),
+ center[1] + radius * math.sin(end_rad),
+ ]
+
+ element: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "arc",
+ "center": center,
+ "radius": radius,
+ "start_angle": start_angle,
+ "end_angle": end_angle,
+ "start_point": start_point,
+ "end_point": end_point,
+ }
+
+ sketch["elements"].append(element)
+ return element
+
+
+def add_constraint(
+ project: Dict[str, Any],
+ sketch_index: int,
+ constraint_type: str,
+ elements: List[int],
+ value: Optional[float] = None,
+) -> Dict[str, Any]:
+ """Add a geometric or dimensional constraint to a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ constraint_type:
+ One of: ``"coincident"``, ``"horizontal"``, ``"vertical"``,
+ ``"parallel"``, ``"perpendicular"``, ``"equal"``, ``"fixed"``,
+ ``"distance"``, ``"angle"``, ``"radius"``, ``"tangent"``.
+ elements:
+ List of element IDs (indices within the sketch's ``elements``
+ list) that participate in the constraint.
+ value:
+ Numeric value for dimensional constraints (``"distance"``,
+ ``"angle"``, ``"radius"``).
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created constraint dictionary.
+
+ Raises
+ ------
+ ValueError
+ If the constraint type is unknown, required value is missing,
+ or element references are invalid.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add constraints to a closed sketch")
+
+ constraint_type = constraint_type.lower()
+ if constraint_type not in VALID_CONSTRAINT_TYPES:
+ raise ValueError(
+ f"Unknown constraint type '{constraint_type}'. "
+ f"Valid types: {', '.join(sorted(VALID_CONSTRAINT_TYPES))}"
+ )
+
+ if not isinstance(elements, (list, tuple)) or len(elements) == 0:
+ raise ValueError("Elements must be a non-empty list of element IDs")
+
+ # Validate minimum element count
+ min_elements = CONSTRAINT_MIN_ELEMENTS[constraint_type]
+ if len(elements) < min_elements:
+ raise ValueError(
+ f"Constraint '{constraint_type}' requires at least {min_elements} "
+ f"element(s), got {len(elements)}"
+ )
+
+ # Validate element IDs exist in the sketch
+ existing_ids = {el["id"] for el in sketch["elements"]}
+ for eid in elements:
+ if eid not in existing_ids:
+ raise ValueError(
+ f"Element ID {eid} not found in sketch. "
+ f"Existing IDs: {sorted(existing_ids)}"
+ )
+
+ # Validate value for dimensional constraints
+ if constraint_type in VALUED_CONSTRAINTS:
+ if value is None:
+ raise ValueError(
+ f"Constraint '{constraint_type}' requires a numeric value"
+ )
+ value = float(value)
+ if constraint_type == "radius" and value <= 0:
+ raise ValueError(f"Radius constraint value must be positive, got {value}")
+ if constraint_type == "distance" and value < 0:
+ raise ValueError(f"Distance constraint value must be non-negative, got {value}")
+ else:
+ # Geometric constraints ignore value
+ value = None
+
+ constraint: Dict[str, Any] = {
+ "id": _next_constraint_id(sketch),
+ "type": constraint_type,
+ "elements": list(elements),
+ "value": value,
+ }
+
+ sketch["constraints"].append(constraint)
+ return constraint
+
+
+def close_sketch(
+ project: Dict[str, Any],
+ sketch_index: int,
+) -> Dict[str, Any]:
+ """Mark a sketch as closed, preventing further modifications.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The closed sketch dictionary.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError(f"Sketch '{sketch['name']}' is already closed")
+
+ sketch["closed"] = True
+ return sketch
+
+
+def list_sketches(project: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return a summary list of all sketches in the project.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+
+ Returns
+ -------
+ List[Dict[str, Any]]
+ List of sketch summaries with index, id, name, plane, element
+ count, constraint count, and closed status.
+ """
+ _validate_project(project)
+
+ result: List[Dict[str, Any]] = []
+ for i, sk in enumerate(project["sketches"]):
+ result.append({
+ "index": i,
+ "id": sk.get("id", i),
+ "name": sk.get("name", f"Sketch {i}"),
+ "plane": sk.get("plane", "XY"),
+ "offset": sk.get("offset", 0.0),
+ "element_count": len(sk.get("elements", [])),
+ "constraint_count": len(sk.get("constraints", [])),
+ "closed": sk.get("closed", False),
+ })
+ return result
+
+
+def get_sketch(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the full sketch dictionary at the given index.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ index:
+ Sketch index.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The complete sketch dictionary.
+ """
+ _validate_project(project)
+ return _get_sketch(project, index)
+
+
+# ---------------------------------------------------------------------------
+# New Geometry
+# ---------------------------------------------------------------------------
+
+
+def add_point(
+ project: Dict[str, Any],
+ sketch_index: int,
+ position: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a point element to a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ position:
+ Point position ``[x, y]``. Defaults to ``[0, 0]``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created point element.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ position = _validate_point_2d(position if position is not None else [0, 0], "position")
+
+ element: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "point",
+ "position": position,
+ }
+
+ sketch["elements"].append(element)
+ return element
+
+
+def add_ellipse(
+ project: Dict[str, Any],
+ sketch_index: int,
+ center: Optional[List[float]] = None,
+ major_radius: float = 10.0,
+ minor_radius: float = 5.0,
+ angle: float = 0.0,
+) -> Dict[str, Any]:
+ """Add an ellipse element to a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ center:
+ Center point ``[x, y]``. Defaults to ``[0, 0]``.
+ major_radius:
+ Semi-major axis length. Must be positive.
+ minor_radius:
+ Semi-minor axis length. Must be positive.
+ angle:
+ Rotation angle of the major axis in degrees.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created ellipse element.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ center = _validate_point_2d(center if center is not None else [0, 0], "center")
+ major_radius = float(major_radius)
+ minor_radius = float(minor_radius)
+ angle = float(angle)
+
+ if major_radius <= 0:
+ raise ValueError(f"Major radius must be positive, got {major_radius}")
+ if minor_radius <= 0:
+ raise ValueError(f"Minor radius must be positive, got {minor_radius}")
+ if minor_radius > major_radius:
+ raise ValueError(
+ f"Minor radius ({minor_radius}) cannot exceed major radius ({major_radius})"
+ )
+
+ element: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "ellipse",
+ "center": center,
+ "major_radius": major_radius,
+ "minor_radius": minor_radius,
+ "angle": angle,
+ }
+
+ sketch["elements"].append(element)
+ return element
+
+
+def add_polygon_sketch(
+ project: Dict[str, Any],
+ sketch_index: int,
+ center: Optional[List[float]] = None,
+ sides: int = 6,
+ radius: float = 5.0,
+) -> Dict[str, Any]:
+ """Add a regular polygon to a sketch (N lines + N coincident constraints).
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ center:
+ Center point ``[x, y]``. Defaults to ``[0, 0]``.
+ sides:
+ Number of sides. Must be at least 3.
+ radius:
+ Circumscribed circle radius. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Summary containing line element IDs and coincident constraint IDs.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ center = _validate_point_2d(center if center is not None else [0, 0], "center")
+ sides = int(sides)
+ radius = float(radius)
+
+ if sides < 3:
+ raise ValueError(f"Polygon must have at least 3 sides, got {sides}")
+ if radius <= 0:
+ raise ValueError(f"Radius must be positive, got {radius}")
+
+ cx, cy = center
+
+ # Compute vertices
+ vertices: List[List[float]] = []
+ for i in range(sides):
+ angle_rad = 2 * math.pi * i / sides
+ vertices.append([
+ cx + radius * math.cos(angle_rad),
+ cy + radius * math.sin(angle_rad),
+ ])
+
+ # Create line elements for each side
+ lines: List[Dict[str, Any]] = []
+ for i in range(sides):
+ j = (i + 1) % sides
+ elem: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "line",
+ "start": list(vertices[i]),
+ "end": list(vertices[j]),
+ }
+ sketch["elements"].append(elem)
+ lines.append(elem)
+
+ # Add coincident constraints at each vertex (adjacent lines)
+ constraint_ids: List[int] = []
+ for i in range(sides):
+ j = (i + 1) % sides
+ constraint: Dict[str, Any] = {
+ "id": _next_constraint_id(sketch),
+ "type": "coincident",
+ "elements": [lines[i]["id"], lines[j]["id"]],
+ "value": None,
+ }
+ sketch["constraints"].append(constraint)
+ constraint_ids.append(constraint["id"])
+
+ return {
+ "type": "polygon",
+ "line_ids": [line["id"] for line in lines],
+ "constraint_ids": constraint_ids,
+ "center": center,
+ "sides": sides,
+ "radius": radius,
+ }
+
+
+def add_bspline(
+ project: Dict[str, Any],
+ sketch_index: int,
+ points: List[List[float]],
+ closed: bool = False,
+) -> Dict[str, Any]:
+ """Add a B-spline element from control points to a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ points:
+ List of control points, each ``[x, y]``. Minimum 2 points.
+ closed:
+ If ``True``, the B-spline forms a closed loop.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created B-spline element.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ if not isinstance(points, (list, tuple)) or len(points) < 2:
+ raise ValueError("B-spline requires at least 2 control points")
+
+ validated_points: List[List[float]] = []
+ for i, pt in enumerate(points):
+ validated_points.append(_validate_point_2d(pt, f"points[{i}]"))
+
+ element: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "bspline",
+ "poles": validated_points,
+ "closed": bool(closed),
+ }
+
+ sketch["elements"].append(element)
+ return element
+
+
+def add_slot(
+ project: Dict[str, Any],
+ sketch_index: int,
+ center1: Optional[List[float]] = None,
+ center2: Optional[List[float]] = None,
+ radius: float = 2.0,
+) -> Dict[str, Any]:
+ """Add a slot (obround) shape to a sketch.
+
+ The slot consists of two semicircular arcs connected by two lines.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ center1:
+ Center of the first semicircle ``[x, y]``. Defaults to ``[0, 0]``.
+ center2:
+ Center of the second semicircle ``[x, y]``. Defaults to ``[10, 0]``.
+ radius:
+ Radius of the semicircular ends. Must be positive.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Summary containing arc and line element IDs.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ center1 = _validate_point_2d(center1 if center1 is not None else [0, 0], "center1")
+ center2 = _validate_point_2d(center2 if center2 is not None else [10, 0], "center2")
+ radius = float(radius)
+
+ if radius <= 0:
+ raise ValueError(f"Radius must be positive, got {radius}")
+ if center1 == center2:
+ raise ValueError("center1 and center2 must be different")
+
+ # Direction vector from center1 to center2
+ dx = center2[0] - center1[0]
+ dy = center2[1] - center1[1]
+ length = math.sqrt(dx * dx + dy * dy)
+ nx = -dy / length # perpendicular normal
+ ny = dx / length
+
+ # Four connection points
+ p1_top = [center1[0] + nx * radius, center1[1] + ny * radius]
+ p1_bot = [center1[0] - nx * radius, center1[1] - ny * radius]
+ p2_top = [center2[0] + nx * radius, center2[1] + ny * radius]
+ p2_bot = [center2[0] - nx * radius, center2[1] - ny * radius]
+
+ # Angle of the direction vector
+ base_angle = math.degrees(math.atan2(dy, dx))
+
+ # Arc at center1 (from bottom to top, going "left")
+ arc1: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "arc",
+ "center": list(center1),
+ "radius": radius,
+ "start_angle": base_angle + 90,
+ "end_angle": base_angle + 270,
+ "start_point": list(p1_top),
+ "end_point": list(p1_bot),
+ }
+ sketch["elements"].append(arc1)
+
+ # Top line from center1 to center2
+ line_top: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "line",
+ "start": list(p1_top),
+ "end": list(p2_top),
+ }
+ sketch["elements"].append(line_top)
+
+ # Arc at center2 (from top to bottom, going "right")
+ arc2: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "arc",
+ "center": list(center2),
+ "radius": radius,
+ "start_angle": base_angle - 90,
+ "end_angle": base_angle + 90,
+ "start_point": list(p2_bot),
+ "end_point": list(p2_top),
+ }
+ sketch["elements"].append(arc2)
+
+ # Bottom line from center2 to center1
+ line_bot: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "line",
+ "start": list(p2_bot),
+ "end": list(p1_bot),
+ }
+ sketch["elements"].append(line_bot)
+
+ return {
+ "type": "slot",
+ "arc_ids": [arc1["id"], arc2["id"]],
+ "line_ids": [line_top["id"], line_bot["id"]],
+ "center1": center1,
+ "center2": center2,
+ "radius": radius,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Editing
+# ---------------------------------------------------------------------------
+
+
+def edit_element(
+ project: Dict[str, Any],
+ sketch_index: int,
+ elem_id: int,
+ **props: Any,
+) -> Dict[str, Any]:
+ """Modify properties of an existing sketch element.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ elem_id:
+ ID of the element to edit.
+ **props:
+ Key-value pairs of properties to update (e.g. ``start``, ``end``,
+ ``center``, ``radius``).
+
+ Returns
+ -------
+ Dict[str, Any]
+ The updated element dictionary.
+
+ Raises
+ ------
+ ValueError
+ If the sketch is closed or no properties are provided.
+ KeyError
+ If the element ID is not found.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot edit elements in a closed sketch")
+
+ if not props:
+ raise ValueError("At least one property must be provided to edit")
+
+ for elem in sketch["elements"]:
+ if elem["id"] == elem_id:
+ # Validate point-like properties
+ for key in ("start", "end", "center", "position"):
+ if key in props:
+ props[key] = _validate_point_2d(props[key], key)
+ if "radius" in props:
+ props["radius"] = float(props["radius"])
+ if props["radius"] <= 0:
+ raise ValueError(f"Radius must be positive, got {props['radius']}")
+ elem.update(props)
+ return elem
+
+ raise KeyError(f"Element ID {elem_id} not found in sketch")
+
+
+def remove_element(
+ project: Dict[str, Any],
+ sketch_index: int,
+ elem_id: int,
+) -> Dict[str, Any]:
+ """Remove an element and all its associated constraints from a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ elem_id:
+ ID of the element to remove.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Summary with removed element ID and list of removed constraint IDs.
+
+ Raises
+ ------
+ ValueError
+ If the sketch is closed.
+ KeyError
+ If the element ID is not found.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot remove elements from a closed sketch")
+
+ # Find and remove the element
+ found = False
+ for i, elem in enumerate(sketch["elements"]):
+ if elem["id"] == elem_id:
+ sketch["elements"].pop(i)
+ found = True
+ break
+
+ if not found:
+ raise KeyError(f"Element ID {elem_id} not found in sketch")
+
+ # Remove constraints that reference this element
+ removed_constraints: List[int] = []
+ remaining: List[Dict[str, Any]] = []
+ for c in sketch["constraints"]:
+ if elem_id in c.get("elements", []):
+ removed_constraints.append(c["id"])
+ else:
+ remaining.append(c)
+ sketch["constraints"] = remaining
+
+ return {
+ "removed_element_id": elem_id,
+ "removed_constraint_ids": removed_constraints,
+ }
+
+
+def remove_constraint(
+ project: Dict[str, Any],
+ sketch_index: int,
+ constraint_id: int,
+) -> Dict[str, Any]:
+ """Remove a specific constraint from a sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ constraint_id:
+ ID of the constraint to remove.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The removed constraint dictionary.
+
+ Raises
+ ------
+ ValueError
+ If the sketch is closed.
+ KeyError
+ If the constraint ID is not found.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot remove constraints from a closed sketch")
+
+ for i, c in enumerate(sketch["constraints"]):
+ if c["id"] == constraint_id:
+ return sketch["constraints"].pop(i)
+
+ raise KeyError(f"Constraint ID {constraint_id} not found in sketch")
+
+
+def edit_constraint(
+ project: Dict[str, Any],
+ sketch_index: int,
+ constraint_id: int,
+ value: Optional[float] = None,
+) -> Dict[str, Any]:
+ """Change the value of an existing constraint.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ constraint_id:
+ ID of the constraint to edit.
+ value:
+ New numeric value for the constraint.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The updated constraint dictionary.
+
+ Raises
+ ------
+ ValueError
+ If the sketch is closed or the constraint is not a valued type.
+ KeyError
+ If the constraint ID is not found.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot edit constraints in a closed sketch")
+
+ for c in sketch["constraints"]:
+ if c["id"] == constraint_id:
+ if c["type"] not in VALUED_CONSTRAINTS:
+ raise ValueError(
+ f"Constraint type '{c['type']}' does not accept a numeric value"
+ )
+ if value is not None:
+ value = float(value)
+ c["value"] = value
+ return c
+
+ raise KeyError(f"Constraint ID {constraint_id} not found in sketch")
+
+
+# ---------------------------------------------------------------------------
+# Operations
+# ---------------------------------------------------------------------------
+
+
+def mirror_elements(
+ project: Dict[str, Any],
+ sketch_index: int,
+ elem_ids: List[int],
+ axis_elem_id: int,
+) -> Dict[str, Any]:
+ """Mirror sketch elements about an axis element.
+
+ Creates mirrored copies of the specified elements and adds symmetric
+ constraints linking originals to their mirrors.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ elem_ids:
+ List of element IDs to mirror.
+ axis_elem_id:
+ ID of the line element to use as mirror axis.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Summary with original IDs, mirrored element IDs, and constraint IDs.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot mirror elements in a closed sketch")
+
+ existing_ids = {el["id"] for el in sketch["elements"]}
+ if axis_elem_id not in existing_ids:
+ raise ValueError(f"Axis element ID {axis_elem_id} not found in sketch")
+ for eid in elem_ids:
+ if eid not in existing_ids:
+ raise ValueError(f"Element ID {eid} not found in sketch")
+
+ mirrored_ids: List[int] = []
+ constraint_ids: List[int] = []
+
+ for eid in elem_ids:
+ # Find original element and create a shallow copy
+ original = next(el for el in sketch["elements"] if el["id"] == eid)
+ mirrored = dict(original)
+ mirrored["id"] = _next_element_id(sketch)
+ mirrored["mirrored_from"] = eid
+ sketch["elements"].append(mirrored)
+ mirrored_ids.append(mirrored["id"])
+
+ # Add symmetric constraint (original, mirror, axis)
+ constraint: Dict[str, Any] = {
+ "id": _next_constraint_id(sketch),
+ "type": "symmetric",
+ "elements": [eid, mirrored["id"], axis_elem_id],
+ "value": None,
+ }
+ sketch["constraints"].append(constraint)
+ constraint_ids.append(constraint["id"])
+
+ return {
+ "original_ids": list(elem_ids),
+ "mirrored_ids": mirrored_ids,
+ "constraint_ids": constraint_ids,
+ "axis_elem_id": axis_elem_id,
+ }
+
+
+def offset_wire(
+ project: Dict[str, Any],
+ sketch_index: int,
+ elem_ids: List[int],
+ distance: float,
+) -> Dict[str, Any]:
+ """Offset a wire of elements by a given distance.
+
+ Creates offset copies of the specified elements in the sketch.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ elem_ids:
+ List of element IDs forming the wire to offset.
+ distance:
+ Offset distance. Positive offsets outward, negative inward.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Summary with original IDs and new offset element IDs.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot offset elements in a closed sketch")
+
+ distance = float(distance)
+ if distance == 0:
+ raise ValueError("Offset distance must be non-zero")
+
+ existing_ids = {el["id"] for el in sketch["elements"]}
+ for eid in elem_ids:
+ if eid not in existing_ids:
+ raise ValueError(f"Element ID {eid} not found in sketch")
+
+ offset_ids: List[int] = []
+ for eid in elem_ids:
+ original = next(el for el in sketch["elements"] if el["id"] == eid)
+ offset_elem = dict(original)
+ offset_elem["id"] = _next_element_id(sketch)
+ offset_elem["offset_from"] = eid
+ offset_elem["offset_distance"] = distance
+ sketch["elements"].append(offset_elem)
+ offset_ids.append(offset_elem["id"])
+
+ return {
+ "original_ids": list(elem_ids),
+ "offset_ids": offset_ids,
+ "distance": distance,
+ }
+
+
+def trim_element(
+ project: Dict[str, Any],
+ sketch_index: int,
+ elem_id: int,
+ keep_side: str = "start",
+) -> Dict[str, Any]:
+ """Trim an element at its intersection point.
+
+ This is a simplified trim that marks the element with a trim point
+ indicator and the side to keep.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ elem_id:
+ ID of the element to trim.
+ keep_side:
+ Which side to keep: ``"start"`` or ``"end"``.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The updated element dictionary with trim metadata.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot trim elements in a closed sketch")
+
+ keep_side = keep_side.lower()
+ if keep_side not in ("start", "end"):
+ raise ValueError(f"keep_side must be 'start' or 'end', got '{keep_side}'")
+
+ for elem in sketch["elements"]:
+ if elem["id"] == elem_id:
+ elem["trimmed"] = True
+ elem["trim_keep_side"] = keep_side
+ return elem
+
+ raise KeyError(f"Element ID {elem_id} not found in sketch")
+
+
+def extend_element(
+ project: Dict[str, Any],
+ sketch_index: int,
+ elem_id: int,
+ target_elem_id: int,
+) -> Dict[str, Any]:
+ """Extend an element to reach a target element.
+
+ Marks the element with extension metadata referencing the target.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ elem_id:
+ ID of the element to extend.
+ target_elem_id:
+ ID of the target element to extend towards.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The updated element dictionary with extension metadata.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot extend elements in a closed sketch")
+
+ existing_ids = {el["id"] for el in sketch["elements"]}
+ if elem_id not in existing_ids:
+ raise KeyError(f"Element ID {elem_id} not found in sketch")
+ if target_elem_id not in existing_ids:
+ raise KeyError(f"Target element ID {target_elem_id} not found in sketch")
+ if elem_id == target_elem_id:
+ raise ValueError("Element and target must be different")
+
+ for elem in sketch["elements"]:
+ if elem["id"] == elem_id:
+ elem["extended"] = True
+ elem["extend_target_id"] = target_elem_id
+ return elem
+
+ raise KeyError(f"Element ID {elem_id} not found in sketch")
+
+
+# ---------------------------------------------------------------------------
+# State
+# ---------------------------------------------------------------------------
+
+
+def validate_sketch(
+ project: Dict[str, Any],
+ sketch_index: int,
+) -> Dict[str, Any]:
+ """Check sketch validity.
+
+ Performs basic validation: ensures the sketch has elements and that
+ all constraint element references are valid.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Validation result with ``valid`` flag and list of ``issues``.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ issues: List[str] = []
+ elements = sketch.get("elements", [])
+ constraints = sketch.get("constraints", [])
+
+ if not elements:
+ issues.append("Sketch has no elements")
+
+ existing_ids = {el["id"] for el in elements}
+ for c in constraints:
+ for eid in c.get("elements", []):
+ if eid not in existing_ids:
+ issues.append(
+ f"Constraint {c['id']} references non-existent element {eid}"
+ )
+
+ return {
+ "valid": len(issues) == 0,
+ "issues": issues,
+ "element_count": len(elements),
+ "constraint_count": len(constraints),
+ }
+
+
+def solve_status(
+ project: Dict[str, Any],
+ sketch_index: int,
+) -> Dict[str, Any]:
+ """Return the constraint solving status of a sketch.
+
+ Provides an estimate of the degrees of freedom (DOF) and whether the
+ sketch is fully, under, or over constrained.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+
+ Returns
+ -------
+ Dict[str, Any]
+ Status containing ``status``, ``element_count``,
+ ``constraint_count``, and ``dof`` (estimated degrees of freedom).
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ elements = sketch.get("elements", [])
+ constraints = sketch.get("constraints", [])
+
+ # Rough DOF estimation: each element contributes DOF based on type,
+ # each constraint removes 1 DOF.
+ dof_per_type = {
+ "point": 2,
+ "line": 4,
+ "circle": 3,
+ "arc": 5,
+ "ellipse": 5,
+ "bspline": 2, # per pole, but simplified
+ }
+
+ total_dof = 0
+ for el in elements:
+ etype = el.get("type", "line")
+ if etype == "bspline":
+ total_dof += len(el.get("poles", [])) * 2
+ else:
+ total_dof += dof_per_type.get(etype, 4)
+
+ total_dof -= len(constraints)
+
+ if total_dof == 0:
+ status = "fully_constrained"
+ elif total_dof > 0:
+ status = "under_constrained"
+ else:
+ status = "over_constrained"
+
+ return {
+ "status": status,
+ "element_count": len(elements),
+ "constraint_count": len(constraints),
+ "dof": total_dof,
+ }
+
+
+def set_construction(
+ project: Dict[str, Any],
+ sketch_index: int,
+ elem_id: int,
+ flag: bool = True,
+) -> Dict[str, Any]:
+ """Toggle the construction geometry flag on an element.
+
+ Construction geometry is used as reference and does not form part of
+ the sketch profile.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ elem_id:
+ ID of the element.
+ flag:
+ ``True`` to mark as construction, ``False`` to unmark.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The updated element dictionary.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ for elem in sketch["elements"]:
+ if elem["id"] == elem_id:
+ elem["construction"] = bool(flag)
+ return elem
+
+ raise KeyError(f"Element ID {elem_id} not found in sketch")
+
+
+def project_external(
+ project: Dict[str, Any],
+ sketch_index: int,
+ part_index: int,
+ edge_ref: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Project external geometry into the sketch as a reference element.
+
+ Parameters
+ ----------
+ project:
+ The project dictionary.
+ sketch_index:
+ Index of the target sketch.
+ part_index:
+ Index of the body/part containing the external geometry.
+ edge_ref:
+ Optional edge reference identifier (e.g. ``"Edge1"``).
+ If ``None``, the entire shape is projected.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The newly created external reference element.
+ """
+ _validate_project(project)
+ sketch = _get_sketch(project, sketch_index)
+
+ if sketch["closed"]:
+ raise ValueError("Cannot add elements to a closed sketch")
+
+ element: Dict[str, Any] = {
+ "id": _next_element_id(sketch),
+ "type": "external_reference",
+ "part_index": int(part_index),
+ "edge_ref": edge_ref,
+ "construction": True,
+ }
+
+ sketch["elements"].append(element)
+ return element
diff --git a/freecad/agent-harness/cli_anything/freecad/core/spreadsheet.py b/freecad/agent-harness/cli_anything/freecad/core/spreadsheet.py
new file mode 100644
index 000000000..780334c0f
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/spreadsheet.py
@@ -0,0 +1,504 @@
+"""FreeCAD CLI - Spreadsheet module for parametric data tables.
+
+Manages spreadsheet creation and cell manipulation within the JSON-based
+project state. Spreadsheets can store raw values, formulas (prefixed
+with ``=``), and named aliases for parametric linking.
+"""
+
+import csv
+import io
+import os
+import re
+from typing import Any, Dict, List, Optional, Union
+
+from cli_anything.freecad.core.document import ensure_collection
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_CELL_REF_RE = re.compile(r"^[A-Z]{1,3}[1-9][0-9]*$")
+_ALIAS_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _next_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for spreadsheets."""
+ items = project.get("spreadsheets", [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str) -> str:
+ """Return a unique spreadsheet name derived from *base*."""
+ existing = {item["name"] for item in project.get("spreadsheets", [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _validate_cell_ref(cell_ref: str) -> str:
+ """Validate and return a normalised cell reference (upper-case).
+
+ Raises ``ValueError`` if the reference is malformed.
+ """
+ if not isinstance(cell_ref, str):
+ raise ValueError(
+ f"Cell reference must be a string, got {type(cell_ref).__name__}"
+ )
+ ref = cell_ref.strip().upper()
+ if not _CELL_REF_RE.match(ref):
+ raise ValueError(
+ f"Invalid cell reference '{cell_ref}'. "
+ f"Expected format like A1, B2, AA23 (1-3 uppercase letters + row number >= 1)"
+ )
+ return ref
+
+
+def _get_sheet(project: Dict[str, Any], sheet_index: int) -> Dict[str, Any]:
+ """Return the spreadsheet at *sheet_index*.
+
+ Raises ``IndexError`` when the index is out of range.
+ """
+ sheets = project.get("spreadsheets", [])
+ if not isinstance(sheet_index, int) or sheet_index < 0 or sheet_index >= len(sheets):
+ raise IndexError(
+ f"Spreadsheet index {sheet_index} out of range "
+ f"(0..{len(sheets) - 1})"
+ )
+ return sheets[sheet_index]
+
+
+def _parse_cell_ref(cell_ref: str):
+ """Split a cell reference into (column_letters, row_number)."""
+ match = re.match(r"^([A-Z]{1,3})([1-9][0-9]*)$", cell_ref)
+ if not match:
+ raise ValueError(f"Cannot parse cell reference '{cell_ref}'")
+ return match.group(1), int(match.group(2))
+
+
+def _col_to_index(col: str) -> int:
+ """Convert column letters to a zero-based index (A=0, B=1, ..., Z=25, AA=26)."""
+ result = 0
+ for ch in col:
+ result = result * 26 + (ord(ch) - ord("A") + 1)
+ return result - 1
+
+
+def _index_to_col(index: int) -> str:
+ """Convert a zero-based column index back to letters."""
+ result = []
+ index += 1 # 1-based
+ while index > 0:
+ index, remainder = divmod(index - 1, 26)
+ result.append(chr(ord("A") + remainder))
+ return "".join(reversed(result))
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+def create_spreadsheet(
+ project: Dict[str, Any], name: Optional[str] = None
+) -> Dict[str, Any]:
+ """Create a new spreadsheet and append it to the project.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ name : str or None
+ Label for the spreadsheet. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created spreadsheet dictionary.
+ """
+ sheets = ensure_collection(project, "spreadsheets")
+
+ if name is None:
+ name = _unique_name(project, "Spreadsheet")
+ elif not isinstance(name, str) or not name.strip():
+ raise ValueError("Spreadsheet name must be a non-empty string")
+ else:
+ name = name.strip()
+
+ sheet: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "cells": {},
+ "aliases": {},
+ }
+
+ sheets.append(sheet)
+ return sheet
+
+
+def set_cell(
+ project: Dict[str, Any],
+ sheet_index: int,
+ cell_ref: str,
+ value: Union[str, int, float],
+) -> Dict[str, Any]:
+ """Set a cell value in a spreadsheet.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ sheet_index : int
+ Index of the spreadsheet in ``project["spreadsheets"]``.
+ cell_ref : str
+ Cell reference such as ``"A1"``, ``"B2"``, ``"AA23"``.
+ value : str, int, or float
+ The value to store. Strings starting with ``"="`` are treated as
+ formulas.
+
+ Returns
+ -------
+ dict
+ A summary containing the cell reference and stored value.
+
+ Raises
+ ------
+ IndexError
+ If *sheet_index* is out of range.
+ ValueError
+ If *cell_ref* is invalid.
+ """
+ ref = _validate_cell_ref(cell_ref)
+ sheet = _get_sheet(project, sheet_index)
+
+ # Determine cell content type
+ if isinstance(value, str) and value.startswith("="):
+ cell_data = {"value": value, "type": "formula"}
+ elif isinstance(value, (int, float)):
+ cell_data = {"value": value, "type": "number"}
+ else:
+ cell_data = {"value": str(value), "type": "string"}
+
+ sheet["cells"][ref] = cell_data
+
+ return {
+ "sheet_index": sheet_index,
+ "cell_ref": ref,
+ "value": cell_data["value"],
+ "type": cell_data["type"],
+ }
+
+
+def get_cell(
+ project: Dict[str, Any], sheet_index: int, cell_ref: str
+) -> Dict[str, Any]:
+ """Retrieve a cell value from a spreadsheet.
+
+ Parameters
+ ----------
+ project : dict
+ The project state dictionary.
+ sheet_index : int
+ Index of the spreadsheet.
+ cell_ref : str
+ Cell reference such as ``"A1"``.
+
+ Returns
+ -------
+ dict
+ Cell data including ``value`` and ``type``, or ``None`` values if
+ the cell is empty.
+
+ Raises
+ ------
+ IndexError
+ If *sheet_index* is out of range.
+ ValueError
+ If *cell_ref* is invalid.
+ """
+ ref = _validate_cell_ref(cell_ref)
+ sheet = _get_sheet(project, sheet_index)
+
+ cell_data = sheet["cells"].get(ref)
+ if cell_data is None:
+ return {
+ "sheet_index": sheet_index,
+ "cell_ref": ref,
+ "value": None,
+ "type": None,
+ }
+
+ return {
+ "sheet_index": sheet_index,
+ "cell_ref": ref,
+ "value": cell_data["value"],
+ "type": cell_data["type"],
+ }
+
+
+def set_alias(
+ project: Dict[str, Any],
+ sheet_index: int,
+ cell_ref: str,
+ alias: str,
+) -> Dict[str, Any]:
+ """Assign an alias name to a cell.
+
+ Aliases allow cells to be referenced by name in formulas and
+ parametric expressions.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ sheet_index : int
+ Index of the spreadsheet.
+ cell_ref : str
+ Cell reference to alias.
+ alias : str
+ Alias name. Must start with a letter or underscore and contain
+ only alphanumeric characters and underscores.
+
+ Returns
+ -------
+ dict
+ Summary with ``cell_ref`` and ``alias``.
+
+ Raises
+ ------
+ IndexError
+ If *sheet_index* is out of range.
+ ValueError
+ If *cell_ref* or *alias* is invalid, or the alias is already in use.
+ """
+ ref = _validate_cell_ref(cell_ref)
+ sheet = _get_sheet(project, sheet_index)
+
+ if not isinstance(alias, str) or not alias.strip():
+ raise ValueError("Alias must be a non-empty string")
+ alias = alias.strip()
+
+ if not _ALIAS_RE.match(alias):
+ raise ValueError(
+ f"Invalid alias '{alias}'. Must start with a letter or underscore "
+ f"and contain only alphanumeric characters and underscores."
+ )
+
+ # Check alias uniqueness (allow re-aliasing the same cell)
+ for existing_ref, existing_alias in sheet["aliases"].items():
+ if existing_alias == alias and existing_ref != ref:
+ raise ValueError(
+ f"Alias '{alias}' is already assigned to cell {existing_ref}"
+ )
+
+ sheet["aliases"][ref] = alias
+
+ return {
+ "sheet_index": sheet_index,
+ "cell_ref": ref,
+ "alias": alias,
+ }
+
+
+def import_csv(
+ project: Dict[str, Any],
+ sheet_index: int,
+ path: str,
+ start_cell: str = "A1",
+) -> Dict[str, Any]:
+ """Import CSV data into a spreadsheet.
+
+ Each CSV value is stored as a cell starting from *start_cell*.
+ Numeric strings are converted to floats automatically.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ sheet_index : int
+ Index of the target spreadsheet.
+ path : str
+ Path to the CSV file.
+ start_cell : str
+ Top-left cell for the imported data. Defaults to ``"A1"``.
+
+ Returns
+ -------
+ dict
+ Summary with number of rows and columns imported.
+
+ Raises
+ ------
+ IndexError
+ If *sheet_index* is out of range.
+ FileNotFoundError
+ If *path* does not exist.
+ ValueError
+ If *start_cell* is invalid.
+ """
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError("Path must be a non-empty string")
+ if not os.path.isfile(path):
+ raise FileNotFoundError(f"CSV file not found: {path}")
+
+ start_ref = _validate_cell_ref(start_cell)
+ start_col_letters, start_row = _parse_cell_ref(start_ref)
+ start_col = _col_to_index(start_col_letters)
+
+ sheet = _get_sheet(project, sheet_index)
+
+ with open(path, "r", encoding="utf-8", newline="") as fh:
+ reader = csv.reader(fh)
+ rows_imported = 0
+ max_cols = 0
+
+ for row_offset, row in enumerate(reader):
+ for col_offset, raw_value in enumerate(row):
+ col_letters = _index_to_col(start_col + col_offset)
+ row_num = start_row + row_offset
+ ref = f"{col_letters}{row_num}"
+
+ # Try to parse as number
+ value: Union[str, float]
+ try:
+ value = float(raw_value)
+ # Keep as int if no decimal part
+ if value == int(value):
+ value = int(value)
+ cell_type = "number"
+ except (ValueError, OverflowError):
+ value = raw_value
+ cell_type = "string"
+
+ sheet["cells"][ref] = {"value": value, "type": cell_type}
+
+ rows_imported += 1
+ if len(row) > max_cols:
+ max_cols = len(row)
+
+ return {
+ "sheet_index": sheet_index,
+ "rows_imported": rows_imported,
+ "columns_imported": max_cols,
+ "start_cell": start_ref,
+ }
+
+
+def export_csv(
+ project: Dict[str, Any], sheet_index: int, path: str
+) -> Dict[str, Any]:
+ """Export a spreadsheet to a CSV file.
+
+ Cells are written in row-major order. Empty cells produce empty
+ strings in the output.
+
+ Parameters
+ ----------
+ project : dict
+ The project state dictionary.
+ sheet_index : int
+ Index of the spreadsheet.
+ path : str
+ Destination file path.
+
+ Returns
+ -------
+ dict
+ Summary with the absolute path and dimensions.
+
+ Raises
+ ------
+ IndexError
+ If *sheet_index* is out of range.
+ ValueError
+ If *path* is invalid.
+ """
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError("Path must be a non-empty string")
+
+ sheet = _get_sheet(project, sheet_index)
+ cells = sheet["cells"]
+
+ if not cells:
+ # Write an empty file
+ dir_name = os.path.dirname(path)
+ if dir_name:
+ os.makedirs(dir_name, exist_ok=True)
+ with open(path, "w", encoding="utf-8", newline="") as fh:
+ pass
+ return {
+ "sheet_index": sheet_index,
+ "path": os.path.abspath(path),
+ "rows": 0,
+ "columns": 0,
+ }
+
+ # Determine grid bounds
+ min_col, max_col = float("inf"), 0
+ min_row, max_row = float("inf"), 0
+
+ for ref in cells:
+ col_letters, row_num = _parse_cell_ref(ref)
+ col_idx = _col_to_index(col_letters)
+ min_col = min(min_col, col_idx)
+ max_col = max(max_col, col_idx)
+ min_row = min(min_row, row_num)
+ max_row = max(max_row, row_num)
+
+ min_col = int(min_col)
+ min_row = int(min_row)
+
+ dir_name = os.path.dirname(path)
+ if dir_name:
+ os.makedirs(dir_name, exist_ok=True)
+
+ num_rows = max_row - min_row + 1
+ num_cols = max_col - min_col + 1
+
+ with open(path, "w", encoding="utf-8", newline="") as fh:
+ writer = csv.writer(fh)
+ for row_num in range(min_row, max_row + 1):
+ row_data: List[str] = []
+ for col_idx in range(min_col, max_col + 1):
+ ref = f"{_index_to_col(col_idx)}{row_num}"
+ cell = cells.get(ref)
+ if cell is not None:
+ row_data.append(str(cell["value"]))
+ else:
+ row_data.append("")
+ writer.writerow(row_data)
+
+ return {
+ "sheet_index": sheet_index,
+ "path": os.path.abspath(path),
+ "rows": num_rows,
+ "columns": num_cols,
+ }
+
+
+def list_spreadsheets(project: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return a summary of all spreadsheets in the project.
+
+ Returns
+ -------
+ list[dict]
+ Each entry has ``id``, ``name``, ``cell_count``, and ``alias_count``.
+ """
+ sheets = project.get("spreadsheets", [])
+ return [
+ {
+ "id": s["id"],
+ "name": s["name"],
+ "cell_count": len(s.get("cells", {})),
+ "alias_count": len(s.get("aliases", {})),
+ }
+ for s in sheets
+ ]
diff --git a/freecad/agent-harness/cli_anything/freecad/core/surface.py b/freecad/agent-harness/cli_anything/freecad/core/surface.py
new file mode 100644
index 000000000..6efee927a
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/surface.py
@@ -0,0 +1,391 @@
+"""FreeCAD CLI - Surface workbench module.
+
+Provides surface creation and manipulation functions including filling,
+lofting through sections, extending, blending, sewing, and cutting.
+All surfaces are stored in ``project["surfaces"]`` via
+:func:`~cli_anything.freecad.core.document.ensure_collection`.
+"""
+
+from typing import Any, Dict, List, Optional
+
+from cli_anything.freecad.core.document import ensure_collection
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _next_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for surfaces."""
+ items = project.get("surfaces", [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str) -> str:
+ """Return a unique name derived from *base* inside ``project["surfaces"]``."""
+ existing = {item["name"] for item in project.get("surfaces", [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _get_surface(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return the surface at *index*, raising ``IndexError`` if out of range."""
+ surfaces = project.get("surfaces", [])
+ if not isinstance(index, int) or index < 0 or index >= len(surfaces):
+ raise IndexError(
+ f"Surface index {index} out of range (0..{len(surfaces) - 1})"
+ )
+ return surfaces[index]
+
+
+def _validate_index_list(indices: Any, label: str, min_count: int = 1) -> List[int]:
+ """Validate that *indices* is a list of non-negative integers."""
+ if not isinstance(indices, (list, tuple)):
+ raise ValueError(f"{label} must be a list of indices")
+ if len(indices) < min_count:
+ raise ValueError(f"{label} requires at least {min_count} index(es), got {len(indices)}")
+ for i, v in enumerate(indices):
+ if not isinstance(v, int) or v < 0:
+ raise ValueError(f"{label}[{i}] must be a non-negative integer, got {v!r}")
+ return list(indices)
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def surface_filling(
+ project: Dict[str, Any],
+ edge_indices: List[int],
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a surface that fills a boundary defined by edges.
+
+ The filling surface interpolates through the specified boundary
+ edges, producing a smooth G1/G2 surface patch.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ edge_indices : list[int]
+ Indices referencing boundary edges (from parts or sketches).
+ name : str or None
+ Label for the surface. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created surface entry.
+
+ Raises
+ ------
+ ValueError
+ If *edge_indices* has fewer than 1 entry or contains invalid values.
+ """
+ refs = _validate_index_list(edge_indices, "edge_indices", min_count=1)
+ surfaces = ensure_collection(project, "surfaces")
+
+ if name is None:
+ name = _unique_name(project, "Filling")
+
+ surface: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "filling",
+ "params": {},
+ "source_refs": refs,
+ }
+
+ surfaces.append(surface)
+ return surface
+
+
+def surface_sections(
+ project: Dict[str, Any],
+ section_indices: List[int],
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a loft-like surface through cross-section profiles.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ section_indices : list[int]
+ Indices referencing cross-section profiles (edges, wires, or
+ sketches). At least two sections are required.
+ name : str or None
+ Label for the surface. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created surface entry.
+
+ Raises
+ ------
+ ValueError
+ If fewer than two sections are provided.
+ """
+ refs = _validate_index_list(section_indices, "section_indices", min_count=2)
+ surfaces = ensure_collection(project, "surfaces")
+
+ if name is None:
+ name = _unique_name(project, "Sections")
+
+ surface: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "sections",
+ "params": {},
+ "source_refs": refs,
+ }
+
+ surfaces.append(surface)
+ return surface
+
+
+def surface_extend(
+ project: Dict[str, Any],
+ surface_index: int,
+ length: float = 10.0,
+ direction: str = "normal",
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Extend an existing surface by *length* along *direction*.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ surface_index : int
+ Index of the surface to extend.
+ length : float
+ Extension distance (default ``10``).
+ direction : str
+ Extension direction — ``"normal"`` (default), ``"u"``, or ``"v"``.
+ name : str or None
+ Label for the new surface. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created extended surface entry.
+
+ Raises
+ ------
+ IndexError
+ If *surface_index* is out of range.
+ ValueError
+ If *length* is not positive or *direction* is invalid.
+ """
+ source = _get_surface(project, surface_index)
+
+ if length <= 0:
+ raise ValueError("length must be a positive number")
+
+ valid_dirs = {"normal", "u", "v"}
+ if direction not in valid_dirs:
+ raise ValueError(f"direction must be one of {', '.join(sorted(valid_dirs))}, got '{direction}'")
+
+ surfaces = ensure_collection(project, "surfaces")
+
+ if name is None:
+ name = _unique_name(project, f"{source['name']}_Extended")
+
+ surface: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "extend",
+ "params": {
+ "length": float(length),
+ "direction": direction,
+ "source_surface_id": source["id"],
+ },
+ "source_refs": [surface_index],
+ }
+
+ surfaces.append(surface)
+ return surface
+
+
+def surface_blend_curve(
+ project: Dict[str, Any],
+ edge_index1: int,
+ edge_index2: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a blend surface between two edges.
+
+ The blend surface smoothly connects two boundary edges with
+ tangency continuity.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ edge_index1 : int
+ Index referencing the first boundary edge.
+ edge_index2 : int
+ Index referencing the second boundary edge.
+ name : str or None
+ Label for the surface. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created surface entry.
+
+ Raises
+ ------
+ ValueError
+ If edge indices are equal or negative.
+ """
+ if not isinstance(edge_index1, int) or edge_index1 < 0:
+ raise ValueError("edge_index1 must be a non-negative integer")
+ if not isinstance(edge_index2, int) or edge_index2 < 0:
+ raise ValueError("edge_index2 must be a non-negative integer")
+ if edge_index1 == edge_index2:
+ raise ValueError("edge_index1 and edge_index2 must differ")
+
+ surfaces = ensure_collection(project, "surfaces")
+
+ if name is None:
+ name = _unique_name(project, "BlendCurve")
+
+ surface: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "blend_curve",
+ "params": {},
+ "source_refs": [edge_index1, edge_index2],
+ }
+
+ surfaces.append(surface)
+ return surface
+
+
+def surface_sew(
+ project: Dict[str, Any],
+ surface_indices: List[int],
+ tolerance: float = 0.01,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Sew multiple surfaces into a single shell.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ surface_indices : list[int]
+ Indices of the surfaces to sew together. At least two required.
+ tolerance : float
+ Sewing tolerance (default ``0.01``).
+ name : str or None
+ Label for the resulting surface. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created sewn surface entry.
+
+ Raises
+ ------
+ ValueError
+ If fewer than two surfaces or tolerance is invalid.
+ IndexError
+ If any surface index is out of range.
+ """
+ if tolerance <= 0:
+ raise ValueError("tolerance must be a positive number")
+
+ refs = _validate_index_list(surface_indices, "surface_indices", min_count=2)
+
+ # Validate that each referenced surface exists
+ source_ids = []
+ for idx in refs:
+ s = _get_surface(project, idx)
+ source_ids.append(s["id"])
+
+ surfaces = ensure_collection(project, "surfaces")
+
+ if name is None:
+ name = _unique_name(project, "SewnSurface")
+
+ surface: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "sew",
+ "params": {
+ "tolerance": float(tolerance),
+ "source_surface_ids": source_ids,
+ },
+ "source_refs": refs,
+ }
+
+ surfaces.append(surface)
+ return surface
+
+
+def surface_cut(
+ project: Dict[str, Any],
+ surface_index: int,
+ cutting_index: int,
+ name: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Cut a surface with another surface or shape.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ surface_index : int
+ Index of the surface to cut.
+ cutting_index : int
+ Index of the cutting surface or shape reference.
+ name : str or None
+ Label for the resulting surface. Auto-generated when *None*.
+
+ Returns
+ -------
+ dict
+ The newly created cut surface entry.
+
+ Raises
+ ------
+ IndexError
+ If *surface_index* is out of range.
+ ValueError
+ If indices are equal.
+ """
+ source = _get_surface(project, surface_index)
+
+ if surface_index == cutting_index:
+ raise ValueError("surface_index and cutting_index must differ")
+
+ surfaces = ensure_collection(project, "surfaces")
+
+ if name is None:
+ name = _unique_name(project, f"{source['name']}_Cut")
+
+ surface: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "type": "cut",
+ "params": {
+ "source_surface_id": source["id"],
+ "cutting_index": cutting_index,
+ },
+ "source_refs": [surface_index, cutting_index],
+ }
+
+ surfaces.append(surface)
+ return surface
diff --git a/freecad/agent-harness/cli_anything/freecad/core/techdraw.py b/freecad/agent-harness/cli_anything/freecad/core/techdraw.py
new file mode 100644
index 000000000..0b7ef4096
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/techdraw.py
@@ -0,0 +1,624 @@
+"""FreeCAD CLI - TechDraw module.
+
+Manages technical drawing pages, views (standard, projection, section,
+detail), dimensions, annotations, leaders, centerlines, hatches, and
+PDF/SVG export on a JSON-based project state.
+"""
+
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Set
+
+from .document import ensure_collection
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+VALID_DIM_TYPES: Set[str] = {"length", "distance", "radius", "diameter", "angle"}
+
+_COLLECTION_KEY = "techdraw_pages"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _next_id(project: Dict[str, Any]) -> int:
+ """Return the next available integer ID for TechDraw pages."""
+ items = project.get(_COLLECTION_KEY, [])
+ if not items:
+ return 1
+ return max(item["id"] for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str) -> str:
+ """Return a unique name derived from *base* inside the pages list."""
+ existing = {item["name"] for item in project.get(_COLLECTION_KEY, [])}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _validate_vec2(value: Any, label: str) -> List[float]:
+ """Validate that *value* is a list of exactly two numbers."""
+ if not isinstance(value, (list, tuple)):
+ raise ValueError(f"{label} must be a list of 2 numbers, got {type(value).__name__}")
+ if len(value) != 2:
+ raise ValueError(f"{label} must have exactly 2 elements, got {len(value)}")
+ try:
+ return [float(v) for v in value]
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} elements must be numeric: {exc}") from exc
+
+
+def _validate_vec3(value: Any, label: str) -> List[float]:
+ """Validate that *value* is a list of exactly three numbers."""
+ if not isinstance(value, (list, tuple)):
+ raise ValueError(f"{label} must be a list of 3 numbers, got {type(value).__name__}")
+ if len(value) != 3:
+ raise ValueError(f"{label} must have exactly 3 elements, got {len(value)}")
+ try:
+ return [float(v) for v in value]
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} elements must be numeric: {exc}") from exc
+
+
+def _get_page(project: Dict[str, Any], page_index: int) -> Dict[str, Any]:
+ """Internal accessor with bounds checking."""
+ items = ensure_collection(project, _COLLECTION_KEY)
+ if not isinstance(page_index, int) or page_index < 0 or page_index >= len(items):
+ raise IndexError(
+ f"Page index {page_index} out of range (0..{len(items) - 1})"
+ )
+ return items[page_index]
+
+
+def _get_view(
+ project: Dict[str, Any], page_index: int, view_index: int
+) -> Dict[str, Any]:
+ """Internal accessor for a view within a page."""
+ page = _get_page(project, page_index)
+ views = page["views"]
+ if not isinstance(view_index, int) or view_index < 0 or view_index >= len(views):
+ raise IndexError(
+ f"View index {view_index} out of range (0..{len(views) - 1})"
+ )
+ return views[view_index]
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+def new_page(
+ project: Dict[str, Any],
+ name: Optional[str] = None,
+ template: str = "A4_LandscapeTD",
+) -> Dict[str, Any]:
+ """Create a new TechDraw page and append it to the project.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ name : str or None
+ Human-readable label. Auto-generated when *None*.
+ template : str
+ Drawing template name (e.g. ``"A4_LandscapeTD"``, ``"A3_LandscapeTD"``).
+
+ Returns
+ -------
+ dict
+ The newly created page dictionary.
+ """
+ items = ensure_collection(project, _COLLECTION_KEY)
+
+ if name is None:
+ name = _unique_name(project, "Page")
+
+ page: Dict[str, Any] = {
+ "id": _next_id(project),
+ "name": name,
+ "template": template,
+ "views": [],
+ "dimensions": [],
+ "annotations": [],
+ }
+
+ items.append(page)
+ return page
+
+
+def set_template(
+ project: Dict[str, Any],
+ page_index: int,
+ template: str,
+) -> Dict[str, Any]:
+ """Change the template of an existing page.
+
+ Returns the updated page dictionary.
+ """
+ if not isinstance(template, str) or not template.strip():
+ raise ValueError("Template must be a non-empty string")
+
+ page = _get_page(project, page_index)
+ page["template"] = template.strip()
+ return page
+
+
+def add_view(
+ project: Dict[str, Any],
+ page_index: int,
+ source_index: int,
+ direction: Optional[List[float]] = None,
+ scale: float = 1.0,
+ position: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a standard view of a part/body to a TechDraw page.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ page_index : int
+ Index of the target page.
+ source_index : int
+ Index of the source object in ``project["parts"]``.
+ direction : list[float] or None
+ View projection direction ``[x, y, z]``. Defaults to ``[0, 0, 1]``.
+ scale : float
+ View scale factor.
+ position : list[float] or None
+ Position on the page ``[x, y]``. Defaults to ``[0, 0]``.
+
+ Returns
+ -------
+ dict
+ The newly created view entry.
+ """
+ page = _get_page(project, page_index)
+
+ if direction is not None:
+ direction = _validate_vec3(direction, "direction")
+ else:
+ direction = [0.0, 0.0, 1.0]
+
+ if position is not None:
+ position = _validate_vec2(position, "position")
+ else:
+ position = [0.0, 0.0]
+
+ view: Dict[str, Any] = {
+ "type": "standard",
+ "source_index": source_index,
+ "direction": direction,
+ "scale": float(scale),
+ "position": position,
+ }
+
+ page["views"].append(view)
+ return view
+
+
+def add_projection_group(
+ project: Dict[str, Any],
+ page_index: int,
+ source_index: int,
+ directions: Optional[List[str]] = None,
+) -> Dict[str, Any]:
+ """Add a projection group (front, right, top, etc.) to a page.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ page_index : int
+ Index of the target page.
+ source_index : int
+ Index of the source object in ``project["parts"]``.
+ directions : list[str] or None
+ Projection names. Defaults to ``["front", "right", "top"]``.
+
+ Returns
+ -------
+ dict
+ The projection group view entry.
+ """
+ page = _get_page(project, page_index)
+
+ if directions is None:
+ directions = ["front", "right", "top"]
+
+ group: Dict[str, Any] = {
+ "type": "projection_group",
+ "source_index": source_index,
+ "directions": list(directions),
+ "scale": 1.0,
+ "position": [0.0, 0.0],
+ }
+
+ page["views"].append(group)
+ return group
+
+
+def add_section_view(
+ project: Dict[str, Any],
+ page_index: int,
+ view_index: int,
+ section_normal: Optional[List[float]] = None,
+ section_origin: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a section view derived from an existing view.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ page_index : int
+ Index of the target page.
+ view_index : int
+ Index of the parent view within the page.
+ section_normal : list[float] or None
+ Normal vector of the section plane. Defaults to ``[1, 0, 0]``.
+ section_origin : list[float] or None
+ Origin point of the section plane. Defaults to ``[0, 0, 0]``.
+
+ Returns
+ -------
+ dict
+ The section view entry.
+ """
+ page = _get_page(project, page_index)
+ # Validate parent view exists
+ _get_view(project, page_index, view_index)
+
+ if section_normal is not None:
+ section_normal = _validate_vec3(section_normal, "section_normal")
+ else:
+ section_normal = [1.0, 0.0, 0.0]
+
+ if section_origin is not None:
+ section_origin = _validate_vec3(section_origin, "section_origin")
+ else:
+ section_origin = [0.0, 0.0, 0.0]
+
+ section: Dict[str, Any] = {
+ "type": "section",
+ "parent_view_index": view_index,
+ "section_normal": section_normal,
+ "section_origin": section_origin,
+ "scale": 1.0,
+ "position": [0.0, 0.0],
+ }
+
+ page["views"].append(section)
+ return section
+
+
+def add_detail_view(
+ project: Dict[str, Any],
+ page_index: int,
+ view_index: int,
+ center: Optional[List[float]] = None,
+ radius: float = 20.0,
+) -> Dict[str, Any]:
+ """Add a detail (magnified) view of part of an existing view.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ page_index : int
+ Index of the target page.
+ view_index : int
+ Index of the parent view within the page.
+ center : list[float] or None
+ Center of the detail circle ``[x, y]``. Defaults to ``[0, 0]``.
+ radius : float
+ Radius of the detail circle.
+
+ Returns
+ -------
+ dict
+ The detail view entry.
+ """
+ page = _get_page(project, page_index)
+ _get_view(project, page_index, view_index)
+
+ if center is not None:
+ center = _validate_vec2(center, "center")
+ else:
+ center = [0.0, 0.0]
+
+ detail: Dict[str, Any] = {
+ "type": "detail",
+ "parent_view_index": view_index,
+ "center": center,
+ "radius": float(radius),
+ "scale": 2.0,
+ "position": [0.0, 0.0],
+ }
+
+ page["views"].append(detail)
+ return detail
+
+
+def add_dimension(
+ project: Dict[str, Any],
+ page_index: int,
+ view_index: int,
+ dim_type: str,
+ references: List[Any],
+ value: Optional[float] = None,
+) -> Dict[str, Any]:
+ """Add a dimension annotation to a page.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ page_index : int
+ Index of the target page.
+ view_index : int
+ Index of the view the dimension references.
+ dim_type : str
+ One of ``"length"``, ``"distance"``, ``"radius"``,
+ ``"diameter"``, ``"angle"``.
+ references : list
+ Geometry references (edges, vertices) for the dimension.
+ value : float or None
+ Explicit override value. When *None* the value is derived from
+ the referenced geometry during macro execution.
+
+ Returns
+ -------
+ dict
+ The dimension entry.
+
+ Raises
+ ------
+ ValueError
+ If *dim_type* is unknown.
+ """
+ if dim_type not in VALID_DIM_TYPES:
+ valid = ", ".join(sorted(VALID_DIM_TYPES))
+ raise ValueError(f"Unknown dim_type '{dim_type}'. Valid: {valid}")
+
+ page = _get_page(project, page_index)
+ _get_view(project, page_index, view_index)
+
+ dimension: Dict[str, Any] = {
+ "type": dim_type,
+ "view_index": view_index,
+ "references": list(references),
+ "value": float(value) if value is not None else None,
+ }
+
+ page["dimensions"].append(dimension)
+ return dimension
+
+
+def add_annotation(
+ project: Dict[str, Any],
+ page_index: int,
+ text: str,
+ position: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Add a text annotation to a page.
+
+ Returns the annotation entry.
+ """
+ page = _get_page(project, page_index)
+
+ if position is not None:
+ position = _validate_vec2(position, "position")
+ else:
+ position = [0.0, 0.0]
+
+ annotation: Dict[str, Any] = {
+ "type": "annotation",
+ "text": str(text),
+ "position": position,
+ }
+
+ page["annotations"].append(annotation)
+ return annotation
+
+
+def add_leader(
+ project: Dict[str, Any],
+ page_index: int,
+ points: List[List[float]],
+ text: str = "",
+) -> Dict[str, Any]:
+ """Add a leader line with optional text to a page.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ page_index : int
+ Index of the target page.
+ points : list[list[float]]
+ List of ``[x, y]`` waypoints for the leader line.
+ text : str
+ Optional text label at the end of the leader.
+
+ Returns
+ -------
+ dict
+ The leader entry.
+ """
+ page = _get_page(project, page_index)
+
+ validated_points: List[List[float]] = []
+ for i, pt in enumerate(points):
+ validated_points.append(_validate_vec2(pt, f"points[{i}]"))
+
+ leader: Dict[str, Any] = {
+ "type": "leader",
+ "points": validated_points,
+ "text": str(text),
+ }
+
+ page["annotations"].append(leader)
+ return leader
+
+
+def add_centerline(
+ project: Dict[str, Any],
+ page_index: int,
+ view_index: int,
+ references: List[Any],
+) -> Dict[str, Any]:
+ """Add a centerline to a view on a page.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ page_index : int
+ Index of the target page.
+ view_index : int
+ Index of the view within the page.
+ references : list
+ Geometry references (edges, faces) that define the centerline.
+
+ Returns
+ -------
+ dict
+ The centerline entry.
+ """
+ page = _get_page(project, page_index)
+ _get_view(project, page_index, view_index)
+
+ centerline: Dict[str, Any] = {
+ "type": "centerline",
+ "view_index": view_index,
+ "references": list(references),
+ }
+
+ page["annotations"].append(centerline)
+ return centerline
+
+
+def add_hatch(
+ project: Dict[str, Any],
+ page_index: int,
+ view_index: int,
+ pattern: str = "steel",
+ scale: float = 1.0,
+) -> Dict[str, Any]:
+ """Add a hatch pattern to a view on a page.
+
+ Parameters
+ ----------
+ project : dict
+ The mutable project state dictionary.
+ page_index : int
+ Index of the target page.
+ view_index : int
+ Index of the view within the page.
+ pattern : str
+ Hatch pattern name (e.g. ``"steel"``, ``"aluminum"``).
+ scale : float
+ Pattern scale factor.
+
+ Returns
+ -------
+ dict
+ The hatch entry.
+ """
+ page = _get_page(project, page_index)
+ _get_view(project, page_index, view_index)
+
+ hatch: Dict[str, Any] = {
+ "type": "hatch",
+ "view_index": view_index,
+ "pattern": str(pattern),
+ "scale": float(scale),
+ }
+
+ page["annotations"].append(hatch)
+ return hatch
+
+
+def export_page_pdf(
+ project: Dict[str, Any],
+ page_index: int,
+ path: str,
+) -> Dict[str, Any]:
+ """Record metadata for exporting a page to PDF.
+
+ The actual export is performed by the generated FreeCAD macro.
+
+ Returns
+ -------
+ dict
+ Export metadata including page name and output path.
+ """
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError("Path must be a non-empty string")
+
+ page = _get_page(project, page_index)
+
+ return {
+ "action": "export_pdf",
+ "page_name": page["name"],
+ "page_index": page_index,
+ "path": path.strip(),
+ "format": "pdf",
+ }
+
+
+def export_page_svg(
+ project: Dict[str, Any],
+ page_index: int,
+ path: str,
+) -> Dict[str, Any]:
+ """Record metadata for exporting a page to SVG.
+
+ The actual export is performed by the generated FreeCAD macro.
+
+ Returns
+ -------
+ dict
+ Export metadata including page name and output path.
+ """
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError("Path must be a non-empty string")
+
+ page = _get_page(project, page_index)
+
+ return {
+ "action": "export_svg",
+ "page_name": page["name"],
+ "page_index": page_index,
+ "path": path.strip(),
+ "format": "svg",
+ }
+
+
+def list_views(
+ project: Dict[str, Any],
+ page_index: int,
+) -> List[Dict[str, Any]]:
+ """Return all views on a page."""
+ page = _get_page(project, page_index)
+ return page["views"]
+
+
+def get_view(
+ project: Dict[str, Any],
+ page_index: int,
+ view_index: int,
+) -> Dict[str, Any]:
+ """Return a specific view from a page.
+
+ Raises ``IndexError`` when either index is out of range.
+ """
+ return _get_view(project, page_index, view_index)
diff --git a/freecad/agent-harness/cli_anything/freecad/freecad_cli.py b/freecad/agent-harness/cli_anything/freecad/freecad_cli.py
new file mode 100644
index 000000000..1bac9bbea
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/freecad_cli.py
@@ -0,0 +1,3999 @@
+#!/usr/bin/env python3
+"""cli-anything-freecad — CLI harness for FreeCAD parametric 3D CAD modeler.
+
+Provides stateful CLI and REPL interface for creating, modifying, and exporting
+FreeCAD 3D models without a GUI. Designed for AI agent consumption.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from functools import wraps
+from typing import Any, Optional
+
+import click
+
+from cli_anything.freecad.core import (
+ document as doc_mod,
+ parts as parts_mod,
+ sketch as sketch_mod,
+ body as body_mod,
+ materials as mat_mod,
+ export as export_mod,
+ measure as measure_mod,
+ spreadsheet as spread_mod,
+ mesh as mesh_mod,
+ draft as draft_mod,
+ surface as surface_mod,
+ import_mod as import_mod,
+ assembly as asm_mod,
+ techdraw as td_mod,
+ fem as fem_mod,
+ cam as cam_mod,
+)
+from cli_anything.freecad.core.session import Session
+
+# ── Global state ─────────────────────────────────────────────────────
+
+_session: Optional[Session] = None
+_json_output: bool = False
+_repl_mode: bool = False
+
+
+def get_session() -> Session:
+ """Get or create the global session."""
+ global _session
+ if _session is None:
+ _session = Session()
+ return _session
+
+
+# ── Output helpers ───────────────────────────────────────────────────
+
+def output(data: Any, message: str = "") -> None:
+ """Print data as JSON or human-readable."""
+ if _json_output:
+ click.echo(json.dumps(data, indent=2, default=str))
+ else:
+ if message:
+ click.echo(message)
+ if isinstance(data, dict):
+ for k, v in data.items():
+ if isinstance(v, (dict, list)):
+ click.echo(f" {k}: {json.dumps(v, default=str)}")
+ else:
+ click.echo(f" {k}: {v}")
+ elif isinstance(data, list):
+ for i, item in enumerate(data):
+ if isinstance(item, dict):
+ label = item.get("name", item.get("type", f"#{i}"))
+ click.echo(f" [{i}] {label}")
+ for k, v in item.items():
+ if k != "name":
+ click.echo(f" {k}: {v}")
+ else:
+ click.echo(f" [{i}] {item}")
+
+
+def handle_error(f):
+ """Decorator to handle errors gracefully in CLI and REPL modes."""
+ @wraps(f)
+ def wrapper(*args, **kwargs):
+ try:
+ return f(*args, **kwargs)
+ except (FileNotFoundError, ValueError, IndexError,
+ RuntimeError, FileExistsError, KeyError, TypeError) as e:
+ if _json_output:
+ click.echo(json.dumps({"error": str(e)}, indent=2), err=True)
+ else:
+ click.echo(f"Error: {e}", err=True)
+ if not _repl_mode:
+ sys.exit(1)
+ return wrapper
+
+
+# ── Argument parsing helpers ─────────────────────────────────────────
+
+def _parse_vec3(s: str) -> list[float]:
+ """Parse 'x,y,z' string to [float, float, float]."""
+ parts = s.split(",")
+ if len(parts) != 3:
+ raise ValueError(f"Expected x,y,z format, got: {s}")
+ return [float(x.strip()) for x in parts]
+
+
+def _parse_vec2(s: str) -> list[float]:
+ """Parse 'x,y' string to [float, float]."""
+ parts = s.split(",")
+ if len(parts) != 2:
+ raise ValueError(f"Expected x,y format, got: {s}")
+ return [float(x.strip()) for x in parts]
+
+
+def _parse_params(params: tuple) -> dict[str, float] | None:
+ """Parse ('key=value', ...) to dict."""
+ if not params:
+ return None
+ result = {}
+ for p in params:
+ if "=" not in p:
+ raise ValueError(f"Param must be key=value, got: {p}")
+ k, v = p.split("=", 1)
+ result[k.strip()] = float(v.strip())
+ return result
+
+
+def _parse_indices(s: str) -> list[int]:
+ """Parse comma-separated int list string '1,2,3' to [1, 2, 3]."""
+ return [int(x.strip()) for x in s.split(",")]
+
+
+def _parse_points(s: str) -> list[list[float]]:
+ """Parse semicolon-separated points 'x,y,z;x,y,z;...' to list of vec3."""
+ points = []
+ for pt_str in s.split(";"):
+ pt_str = pt_str.strip()
+ if pt_str:
+ points.append(_parse_vec3(pt_str))
+ return points
+
+
+def _parse_points_2d(s: str) -> list[list[float]]:
+ """Parse semicolon-separated 2D points 'x,y;x,y;...' to list of vec2."""
+ points = []
+ for pt_str in s.split(";"):
+ pt_str = pt_str.strip()
+ if pt_str:
+ points.append(_parse_vec2(pt_str))
+ return points
+
+
+def _parse_references(s: str) -> list:
+ """Parse comma-separated references (ints or strings)."""
+ refs = []
+ for item in s.split(","):
+ item = item.strip()
+ try:
+ refs.append(int(item))
+ except ValueError:
+ refs.append(item)
+ return refs
+
+
+# Use output_fn as alias for output to avoid collision with click.argument("output")
+output_fn = output
+
+
+# ── Main CLI group ───────────────────────────────────────────────────
+
[email protected](invoke_without_command=True)
[email protected]("--json", "use_json", is_flag=True, help="Output in JSON format.")
[email protected]("--project", "-p", type=click.Path(), help="Load project file.")
+def cli(ctx: click.Context, use_json: bool, project: Optional[str]) -> None:
+ """cli-anything-freecad — CLI harness for FreeCAD 3D CAD modeler."""
+ global _json_output
+ _json_output = use_json
+
+ if project:
+ sess = get_session()
+ proj = doc_mod.open_document(project)
+ sess.set_project(proj, path=project)
+
+ # Auto-save after one-shot commands when --project is used
+ def _auto_save():
+ if sess._modified and sess.project_path and not _repl_mode:
+ sess.save_session()
+
+ ctx.call_on_close(_auto_save)
+
+ if ctx.invoked_subcommand is None:
+ ctx.invoke(repl, project_path=project)
+
+
+# ── Document commands ────────────────────────────────────────────────
+
[email protected]("document")
+def document_group():
+ """Document management commands."""
+ pass
+
+
+@document_group.command("new")
[email protected]("--name", "-n", default="Untitled", help="Document name.")
[email protected]("--units", "-u", default="mm", help="Units (mm, m, in).")
[email protected]("--profile", help="Use a preset profile.")
[email protected]("--output", "-o", type=click.Path(), help="Save to file.")
+@handle_error
+def document_new(name: str, units: str, profile: Optional[str],
+ output: Optional[str]) -> None:
+ """Create a new FreeCAD document."""
+ sess = get_session()
+ proj = doc_mod.create_document(name=name, units=units, profile=profile)
+ path = None
+ if output:
+ path = doc_mod.save_document(proj, output)
+ sess.set_project(proj, path=path)
+ result = doc_mod.get_document_info(proj)
+ if path:
+ result["saved_to"] = path
+ output_fn(result, f"Created document: {name}")
+
+
+@document_group.command("open")
[email protected]("path", type=click.Path(exists=True))
+@handle_error
+def document_open(path: str) -> None:
+ """Open an existing document."""
+ sess = get_session()
+ proj = doc_mod.open_document(path)
+ sess.set_project(proj, path=path)
+ result = doc_mod.get_document_info(proj)
+ output_fn(result, f"Opened: {path}")
+
+
+@document_group.command("save")
[email protected]("--output", "-o", type=click.Path(), help="Save to new path.")
+@handle_error
+def document_save(output: Optional[str]) -> None:
+ """Save the current document."""
+ sess = get_session()
+ proj = sess.get_project()
+ path = sess.save_session(path=output)
+ result = {"saved_to": path}
+ output_fn(result, f"Saved: {path}")
+
+
+@document_group.command("info")
+@handle_error
+def document_info() -> None:
+ """Show document information."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = doc_mod.get_document_info(proj)
+ output_fn(result, "Document info:")
+
+
+@document_group.command("profiles")
+@handle_error
+def document_profiles() -> None:
+ """List available document profiles."""
+ result = doc_mod.list_profiles()
+ output_fn(result, "Available profiles:")
+
+
+# ── Part commands ────────────────────────────────────────────────────
+
+def part_group():
+ """3D part/primitive management commands."""
+ pass
+
+
+@part_group.command("add")
[email protected]("part_type", default="box")
[email protected]("--name", "-n", help="Part name.")
[email protected]("--position", "-pos", help="Position as x,y,z (e.g. 0,0,0).")
[email protected]("--rotation", "-rot", help="Rotation as x,y,z degrees.")
[email protected]("--param", "-P", multiple=True, help="Param as key=value.")
+@handle_error
+def part_add(part_type: str, name: Optional[str], position: Optional[str],
+ rotation: Optional[str], param: tuple) -> None:
+ """Add a 3D primitive part (box, cylinder, sphere, cone, torus, wedge, helix, spiral, thread)."""
+ sess = get_session()
+ sess.snapshot(f"Add part: {part_type}")
+ proj = sess.get_project()
+
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ params = _parse_params(param)
+
+ result = parts_mod.add_part(proj, part_type=part_type, name=name,
+ position=pos, rotation=rot, params=params)
+ output_fn(result, f"Added {part_type}: {result.get('name', '')}")
+
+
+@part_group.command("remove")
[email protected]("index", type=int)
+@handle_error
+def part_remove(index: int) -> None:
+ """Remove a part by index."""
+ sess = get_session()
+ sess.snapshot(f"Remove part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.remove_part(proj, index)
+ output_fn(result, f"Removed: {result.get('name', f'#{index}')}")
+
+
+@part_group.command("list")
+@handle_error
+def part_list() -> None:
+ """List all parts."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = parts_mod.list_parts(proj)
+ output_fn(result, f"{len(result)} part(s):")
+
+
+@part_group.command("get")
[email protected]("index", type=int)
+@handle_error
+def part_get(index: int) -> None:
+ """Get details of a part by index."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = parts_mod.get_part(proj, index)
+ output_fn(result, f"Part #{index}:")
+
+
+@part_group.command("transform")
[email protected]("index", type=int)
[email protected]("--position", "-pos", help="New position as x,y,z.")
[email protected]("--rotation", "-rot", help="New rotation as x,y,z degrees.")
+@handle_error
+def part_transform(index: int, position: Optional[str],
+ rotation: Optional[str]) -> None:
+ """Transform a part (position and/or rotation)."""
+ sess = get_session()
+ sess.snapshot(f"Transform part #{index}")
+ proj = sess.get_project()
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = parts_mod.transform_part(proj, index, position=pos, rotation=rot)
+ output_fn(result, f"Transformed: {result.get('name', f'#{index}')}")
+
+
+@part_group.command("boolean")
[email protected]("operation", type=click.Choice(["cut", "fuse", "common"]))
[email protected]("base_index", type=int)
[email protected]("tool_index", type=int)
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_boolean(operation: str, base_index: int, tool_index: int,
+ name: Optional[str]) -> None:
+ """Perform boolean operation (cut, fuse, common) on two parts."""
+ sess = get_session()
+ sess.snapshot(f"Boolean {operation}: #{base_index} vs #{tool_index}")
+ proj = sess.get_project()
+ result = parts_mod.boolean_op(proj, operation, base_index, tool_index,
+ name=name)
+ output_fn(result, f"Boolean {operation}: {result.get('name', '')}")
+
+
+@part_group.command("copy")
[email protected]("index", type=int)
[email protected]("--name", "-n", help="Name for copy.")
+@handle_error
+def part_copy(index: int, name: Optional[str]) -> None:
+ """Copy a part by index."""
+ sess = get_session()
+ sess.snapshot(f"Copy part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.copy_part(proj, index, name=name)
+ output_fn(result, f"Copied: {result.get('name', '')}")
+
+
+@part_group.command("mirror")
[email protected]("index", type=int)
[email protected]("--plane", default="XY", type=click.Choice(["XY", "XZ", "YZ"]),
+ help="Mirror plane.")
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_mirror(index: int, plane: str, name: Optional[str]) -> None:
+ """Create a mirrored copy of a part."""
+ sess = get_session()
+ sess.snapshot(f"Mirror part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.mirror_part(proj, index, plane=plane, name=name)
+ output_fn(result, f"Mirrored: {result.get('name', '')}")
+
+
+@part_group.command("scale")
[email protected]("index", type=int)
[email protected]("factor", type=str)
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_scale(index: int, factor: str, name: Optional[str]) -> None:
+ """Scale a part by a uniform factor or x,y,z factors."""
+ sess = get_session()
+ sess.snapshot(f"Scale part #{index}")
+ proj = sess.get_project()
+ if "," in factor:
+ fac = _parse_vec3(factor)
+ else:
+ fac = float(factor)
+ result = parts_mod.scale_part(proj, index, factor=fac, name=name)
+ output_fn(result, f"Scaled: {result.get('name', '')}")
+
+
+@part_group.command("offset")
[email protected]("index", type=int)
[email protected]("distance", type=float)
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_offset(index: int, distance: float, name: Optional[str]) -> None:
+ """Create an offset shell of a part."""
+ sess = get_session()
+ sess.snapshot(f"Offset part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.offset_shape(proj, index, distance=distance, name=name)
+ output_fn(result, f"Offset: {result.get('name', '')}")
+
+
+@part_group.command("thickness")
[email protected]("index", type=int)
[email protected]("thickness_val", type=float)
[email protected]("--faces", default="all", help="Faces: 'all' or comma-sep indices.")
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_thickness(index: int, thickness_val: float, faces: str,
+ name: Optional[str]) -> None:
+ """Hollow a solid by applying wall thickness."""
+ sess = get_session()
+ sess.snapshot(f"Thickness part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.thickness_part(proj, index, thickness=thickness_val,
+ faces=faces, name=name)
+ output_fn(result, f"Thickness: {result.get('name', '')}")
+
+
+@part_group.command("compound")
[email protected]("indices", type=str)
[email protected]("--name", "-n", help="Name for compound.")
+@handle_error
+def part_compound(indices: str, name: Optional[str]) -> None:
+ """Group parts into a compound (comma-separated indices)."""
+ sess = get_session()
+ sess.snapshot("Create compound")
+ proj = sess.get_project()
+ idx_list = _parse_indices(indices)
+ result = parts_mod.compound_parts(proj, idx_list, name=name)
+ output_fn(result, f"Compound: {result.get('name', '')}")
+
+
+@part_group.command("explode")
[email protected]("index", type=int)
+@handle_error
+def part_explode(index: int) -> None:
+ """Explode a compound into individual parts."""
+ sess = get_session()
+ sess.snapshot(f"Explode compound #{index}")
+ proj = sess.get_project()
+ result = parts_mod.explode_compound(proj, index)
+ output_fn(result, f"Exploded {len(result)} part(s)")
+
+
+@part_group.command("fillet-3d")
[email protected]("index", type=int)
[email protected]("--radius", "-r", default=1.0, type=float, help="Fillet radius.")
[email protected]("--edges", default="all", help="Edges: 'all' or comma-sep indices.")
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_fillet_3d(index: int, radius: float, edges: str,
+ name: Optional[str]) -> None:
+ """Apply a 3D fillet to a part."""
+ sess = get_session()
+ sess.snapshot(f"Fillet-3d part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.fillet_3d(proj, index, radius=radius, edges=edges, name=name)
+ output_fn(result, f"Fillet-3D: {result.get('name', '')}")
+
+
+@part_group.command("chamfer-3d")
[email protected]("index", type=int)
[email protected]("--size", "-s", default=1.0, type=float, help="Chamfer size.")
[email protected]("--edges", default="all", help="Edges: 'all' or comma-sep indices.")
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_chamfer_3d(index: int, size: float, edges: str,
+ name: Optional[str]) -> None:
+ """Apply a 3D chamfer to a part."""
+ sess = get_session()
+ sess.snapshot(f"Chamfer-3d part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.chamfer_3d(proj, index, size=size, edges=edges, name=name)
+ output_fn(result, f"Chamfer-3D: {result.get('name', '')}")
+
+
+@part_group.command("loft")
[email protected]("section_indices", type=str)
[email protected]("--solid/--no-solid", default=True, help="Create solid.")
[email protected]("--ruled", is_flag=True, help="Use ruled surfaces.")
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_loft(section_indices: str, solid: bool, ruled: bool,
+ name: Optional[str]) -> None:
+ """Loft through cross-section parts (comma-separated indices)."""
+ sess = get_session()
+ sess.snapshot("Loft parts")
+ proj = sess.get_project()
+ idx_list = _parse_indices(section_indices)
+ result = parts_mod.loft_parts(proj, idx_list, solid=solid, ruled=ruled, name=name)
+ output_fn(result, f"Loft: {result.get('name', '')}")
+
+
+@part_group.command("sweep")
[email protected]("profile_index", type=int)
[email protected]("path_index", type=int)
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_sweep(profile_index: int, path_index: int, name: Optional[str]) -> None:
+ """Sweep a profile shape along a path."""
+ sess = get_session()
+ sess.snapshot("Sweep part")
+ proj = sess.get_project()
+ result = parts_mod.sweep_part(proj, profile_index, path_index, name=name)
+ output_fn(result, f"Sweep: {result.get('name', '')}")
+
+
+@part_group.command("revolve")
[email protected]("index", type=int)
[email protected]("--axis", default="Z", type=click.Choice(["X", "Y", "Z"]),
+ help="Revolution axis.")
[email protected]("--angle", "-a", default=360.0, type=float, help="Angle in degrees.")
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_revolve(index: int, axis: str, angle: float, name: Optional[str]) -> None:
+ """Revolve a part around an axis."""
+ sess = get_session()
+ sess.snapshot(f"Revolve part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.revolve_part(proj, index, axis=axis, angle=angle, name=name)
+ output_fn(result, f"Revolve: {result.get('name', '')}")
+
+
+@part_group.command("extrude")
[email protected]("index", type=int)
[email protected]("--direction", "-d", help="Direction as x,y,z.")
[email protected]("--length", "-l", default=10.0, type=float, help="Extrusion length.")
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_extrude(index: int, direction: Optional[str], length: float,
+ name: Optional[str]) -> None:
+ """Extrude a part along a direction."""
+ sess = get_session()
+ sess.snapshot(f"Extrude part #{index}")
+ proj = sess.get_project()
+ dir_vec = _parse_vec3(direction) if direction else None
+ result = parts_mod.extrude_part(proj, index, direction=dir_vec, length=length,
+ name=name)
+ output_fn(result, f"Extrude: {result.get('name', '')}")
+
+
+@part_group.command("section")
[email protected]("index", type=int)
[email protected]("--plane", default="XY", type=click.Choice(["XY", "XZ", "YZ"]),
+ help="Section plane.")
[email protected]("--offset", default=0.0, type=float, help="Plane offset.")
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def part_section(index: int, plane: str, offset: float,
+ name: Optional[str]) -> None:
+ """Create a cross-section of a part."""
+ sess = get_session()
+ sess.snapshot(f"Section part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.section_part(proj, index, plane=plane, offset=offset, name=name)
+ output_fn(result, f"Section: {result.get('name', '')}")
+
+
+@part_group.command("slice")
[email protected]("index", type=int)
[email protected]("--plane", default="XY", type=click.Choice(["XY", "XZ", "YZ"]),
+ help="Slice plane.")
[email protected]("--offset", default=0.0, type=float, help="Plane offset.")
+@handle_error
+def part_slice(index: int, plane: str, offset: float) -> None:
+ """Slice a part into two halves."""
+ sess = get_session()
+ sess.snapshot(f"Slice part #{index}")
+ proj = sess.get_project()
+ result = parts_mod.slice_part(proj, index, plane=plane, offset=offset)
+ output_fn(result, "Sliced part into two halves")
+
+
+@part_group.command("line-3d")
[email protected]("--start", "-s", default="0,0,0", help="Start point x,y,z.")
[email protected]("--end", "-e", default="10,0,0", help="End point x,y,z.")
[email protected]("--name", "-n", help="Part name.")
+@handle_error
+def part_line_3d(start: str, end: str, name: Optional[str]) -> None:
+ """Add a 3D line (edge) between two points."""
+ sess = get_session()
+ sess.snapshot("Add line-3d")
+ proj = sess.get_project()
+ s = _parse_vec3(start)
+ e = _parse_vec3(end)
+ result = parts_mod.add_line_3d(proj, start=s, end=e, name=name)
+ output_fn(result, f"Added line-3d: {result.get('name', '')}")
+
+
+@part_group.command("wire")
[email protected]("points_str", type=str)
[email protected]("--closed", is_flag=True, help="Close the wire.")
[email protected]("--name", "-n", help="Part name.")
+@handle_error
+def part_wire(points_str: str, closed: bool, name: Optional[str]) -> None:
+ """Add a wire from semicolon-separated x,y,z points."""
+ sess = get_session()
+ sess.snapshot("Add wire")
+ proj = sess.get_project()
+ pts = _parse_points(points_str)
+ result = parts_mod.add_wire(proj, points=pts, closed=closed, name=name)
+ output_fn(result, f"Added wire: {result.get('name', '')}")
+
+
+@part_group.command("polygon-3d")
[email protected]("--center", "-c", default="0,0,0", help="Center x,y,z.")
[email protected]("--sides", default=6, type=int, help="Number of sides.")
[email protected]("--radius", "-r", default=5.0, type=float, help="Radius.")
[email protected]("--normal", default="0,0,1", help="Normal vector x,y,z.")
[email protected]("--name", "-n", help="Part name.")
+@handle_error
+def part_polygon_3d(center: str, sides: int, radius: float, normal: str,
+ name: Optional[str]) -> None:
+ """Add a regular polygon in 3D space."""
+ sess = get_session()
+ sess.snapshot("Add polygon-3d")
+ proj = sess.get_project()
+ c = _parse_vec3(center)
+ n = _parse_vec3(normal)
+ result = parts_mod.add_polygon_3d(proj, center=c, sides=sides, radius=radius,
+ normal=n, name=name)
+ output_fn(result, f"Added polygon-3d: {result.get('name', '')}")
+
+
+@part_group.command("info")
[email protected]("index", type=int)
+@handle_error
+def part_info(index: int) -> None:
+ """Get detailed information about a part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = parts_mod.part_info(proj, index)
+ output_fn(result, f"Part #{index} info:")
+
+
+# ── Sketch commands ──────────────────────────────────────────────────
+
+def sketch_group():
+ """2D sketch commands."""
+ pass
+
+
+@sketch_group.command("new")
[email protected]("--name", "-n", help="Sketch name.")
[email protected]("--plane", default="XY", type=click.Choice(["XY", "XZ", "YZ"]),
+ help="Sketch plane.")
[email protected]("--offset", default=0.0, type=float, help="Plane offset.")
+@handle_error
+def sketch_new(name: Optional[str], plane: str, offset: float) -> None:
+ """Create a new sketch."""
+ sess = get_session()
+ sess.snapshot("New sketch")
+ proj = sess.get_project()
+ result = sketch_mod.create_sketch(proj, name=name, plane=plane, offset=offset)
+ output_fn(result, f"Created sketch: {result.get('name', '')}")
+
+
+@sketch_group.command("add-line")
[email protected]("sketch_index", type=int)
[email protected]("--start", "-s", default="0,0", help="Start point x,y.")
[email protected]("--end", "-e", default="10,0", help="End point x,y.")
+@handle_error
+def sketch_add_line(sketch_index: int, start: str, end: str) -> None:
+ """Add a line to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Add line to sketch #{sketch_index}")
+ proj = sess.get_project()
+ s = _parse_vec2(start)
+ e = _parse_vec2(end)
+ result = sketch_mod.add_line(proj, sketch_index, start=s, end=e)
+ output_fn(result, "Added line")
+
+
+@sketch_group.command("add-circle")
[email protected]("sketch_index", type=int)
[email protected]("--center", "-c", default="0,0", help="Center x,y.")
[email protected]("--radius", "-r", default=5.0, type=float, help="Radius.")
+@handle_error
+def sketch_add_circle(sketch_index: int, center: str, radius: float) -> None:
+ """Add a circle to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Add circle to sketch #{sketch_index}")
+ proj = sess.get_project()
+ c = _parse_vec2(center)
+ result = sketch_mod.add_circle(proj, sketch_index, center=c, radius=radius)
+ output_fn(result, "Added circle")
+
+
+@sketch_group.command("add-rect")
[email protected]("sketch_index", type=int)
[email protected]("--corner", "-c", default="0,0", help="Corner x,y.")
[email protected]("--width", "-w", default=10.0, type=float, help="Width.")
[email protected]("--height", "-h", default=10.0, type=float, help="Height.")
+@handle_error
+def sketch_add_rect(sketch_index: int, corner: str, width: float,
+ height: float) -> None:
+ """Add a rectangle to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Add rectangle to sketch #{sketch_index}")
+ proj = sess.get_project()
+ c = _parse_vec2(corner)
+ result = sketch_mod.add_rectangle(proj, sketch_index, corner=c,
+ width=width, height=height)
+ output_fn(result, "Added rectangle")
+
+
+@sketch_group.command("add-arc")
[email protected]("sketch_index", type=int)
[email protected]("--center", "-c", default="0,0", help="Center x,y.")
[email protected]("--radius", "-r", default=5.0, type=float, help="Radius.")
[email protected]("--start-angle", default=0.0, type=float, help="Start angle (deg).")
[email protected]("--end-angle", default=90.0, type=float, help="End angle (deg).")
+@handle_error
+def sketch_add_arc(sketch_index: int, center: str, radius: float,
+ start_angle: float, end_angle: float) -> None:
+ """Add an arc to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Add arc to sketch #{sketch_index}")
+ proj = sess.get_project()
+ c = _parse_vec2(center)
+ result = sketch_mod.add_arc(proj, sketch_index, center=c, radius=radius,
+ start_angle=start_angle, end_angle=end_angle)
+ output_fn(result, "Added arc")
+
+
+@sketch_group.command("constrain")
[email protected]("sketch_index", type=int)
[email protected]("constraint_type")
[email protected]("--elements", "-e", required=True, help="Element indices (comma-sep).")
[email protected]("--value", "-v", type=float, help="Constraint value.")
+@handle_error
+def sketch_constrain(sketch_index: int, constraint_type: str,
+ elements: str, value: Optional[float]) -> None:
+ """Add a constraint to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Add constraint to sketch #{sketch_index}")
+ proj = sess.get_project()
+ elems = [int(x.strip()) for x in elements.split(",")]
+ result = sketch_mod.add_constraint(proj, sketch_index, constraint_type,
+ elems, value=value)
+ output_fn(result, f"Added constraint: {constraint_type}")
+
+
+@sketch_group.command("close")
[email protected]("sketch_index", type=int)
+@handle_error
+def sketch_close(sketch_index: int) -> None:
+ """Close/finalize a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Close sketch #{sketch_index}")
+ proj = sess.get_project()
+ result = sketch_mod.close_sketch(proj, sketch_index)
+ output_fn(result, "Sketch closed")
+
+
+@sketch_group.command("list")
+@handle_error
+def sketch_list() -> None:
+ """List all sketches."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = sketch_mod.list_sketches(proj)
+ output_fn(result, f"{len(result)} sketch(es):")
+
+
+@sketch_group.command("get")
[email protected]("index", type=int)
+@handle_error
+def sketch_get(index: int) -> None:
+ """Get sketch details."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = sketch_mod.get_sketch(proj, index)
+ output_fn(result, f"Sketch #{index}:")
+
+
+@sketch_group.command("add-point")
[email protected]("sketch_index", type=int)
[email protected]("--position", "-p", default="0,0", help="Position x,y.")
+@handle_error
+def sketch_add_point(sketch_index: int, position: str) -> None:
+ """Add a point to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Add point to sketch #{sketch_index}")
+ proj = sess.get_project()
+ pos = _parse_vec2(position)
+ result = sketch_mod.add_point(proj, sketch_index, position=pos)
+ output_fn(result, "Added point")
+
+
+@sketch_group.command("add-ellipse")
[email protected]("sketch_index", type=int)
[email protected]("--center", "-c", default="0,0", help="Center x,y.")
[email protected]("--major-radius", default=10.0, type=float, help="Semi-major axis.")
[email protected]("--minor-radius", default=5.0, type=float, help="Semi-minor axis.")
[email protected]("--angle", default=0.0, type=float, help="Rotation angle (deg).")
+@handle_error
+def sketch_add_ellipse(sketch_index: int, center: str, major_radius: float,
+ minor_radius: float, angle: float) -> None:
+ """Add an ellipse to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Add ellipse to sketch #{sketch_index}")
+ proj = sess.get_project()
+ c = _parse_vec2(center)
+ result = sketch_mod.add_ellipse(proj, sketch_index, center=c,
+ major_radius=major_radius,
+ minor_radius=minor_radius, angle=angle)
+ output_fn(result, "Added ellipse")
+
+
+@sketch_group.command("add-polygon")
[email protected]("sketch_index", type=int)
[email protected]("--center", "-c", default="0,0", help="Center x,y.")
[email protected]("--sides", default=6, type=int, help="Number of sides.")
[email protected]("--radius", "-r", default=5.0, type=float, help="Radius.")
+@handle_error
+def sketch_add_polygon(sketch_index: int, center: str, sides: int,
+ radius: float) -> None:
+ """Add a regular polygon to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Add polygon to sketch #{sketch_index}")
+ proj = sess.get_project()
+ c = _parse_vec2(center)
+ result = sketch_mod.add_polygon_sketch(proj, sketch_index, center=c,
+ sides=sides, radius=radius)
+ output_fn(result, "Added polygon")
+
+
+@sketch_group.command("add-bspline")
[email protected]("sketch_index", type=int)
[email protected]("points_str", type=str)
[email protected]("--closed", is_flag=True, help="Close the B-spline.")
+@handle_error
+def sketch_add_bspline(sketch_index: int, points_str: str, closed: bool) -> None:
+ """Add a B-spline to a sketch (semicolon-separated x,y points)."""
+ sess = get_session()
+ sess.snapshot(f"Add bspline to sketch #{sketch_index}")
+ proj = sess.get_project()
+ pts = _parse_points_2d(points_str)
+ result = sketch_mod.add_bspline(proj, sketch_index, points=pts, closed=closed)
+ output_fn(result, "Added B-spline")
+
+
+@sketch_group.command("add-slot")
[email protected]("sketch_index", type=int)
[email protected]("--center1", default="0,0", help="First center x,y.")
[email protected]("--center2", default="10,0", help="Second center x,y.")
[email protected]("--radius", "-r", default=2.0, type=float, help="Radius.")
+@handle_error
+def sketch_add_slot(sketch_index: int, center1: str, center2: str,
+ radius: float) -> None:
+ """Add a slot (obround) shape to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Add slot to sketch #{sketch_index}")
+ proj = sess.get_project()
+ c1 = _parse_vec2(center1)
+ c2 = _parse_vec2(center2)
+ result = sketch_mod.add_slot(proj, sketch_index, center1=c1, center2=c2,
+ radius=radius)
+ output_fn(result, "Added slot")
+
+
+@sketch_group.command("edit-element")
[email protected]("sketch_index", type=int)
[email protected]("elem_id", type=int)
[email protected]("--param", "-P", multiple=True, help="Property as key=value.")
+@handle_error
+def sketch_edit_element(sketch_index: int, elem_id: int, param: tuple) -> None:
+ """Edit a sketch element's properties."""
+ sess = get_session()
+ sess.snapshot(f"Edit element {elem_id} in sketch #{sketch_index}")
+ proj = sess.get_project()
+ props = {}
+ for p in param:
+ if "=" not in p:
+ raise ValueError(f"Param must be key=value, got: {p}")
+ k, v = p.split("=", 1)
+ k = k.strip()
+ v = v.strip()
+ if k in ("start", "end", "center", "position"):
+ props[k] = _parse_vec2(v)
+ elif k == "radius":
+ props[k] = float(v)
+ else:
+ try:
+ props[k] = float(v)
+ except ValueError:
+ props[k] = v
+ result = sketch_mod.edit_element(proj, sketch_index, elem_id, **props)
+ output_fn(result, f"Edited element {elem_id}")
+
+
+@sketch_group.command("remove-element")
[email protected]("sketch_index", type=int)
[email protected]("elem_id", type=int)
+@handle_error
+def sketch_remove_element(sketch_index: int, elem_id: int) -> None:
+ """Remove an element from a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Remove element {elem_id} from sketch #{sketch_index}")
+ proj = sess.get_project()
+ result = sketch_mod.remove_element(proj, sketch_index, elem_id)
+ output_fn(result, f"Removed element {elem_id}")
+
+
+@sketch_group.command("remove-constraint")
[email protected]("sketch_index", type=int)
[email protected]("constraint_id", type=int)
+@handle_error
+def sketch_remove_constraint(sketch_index: int, constraint_id: int) -> None:
+ """Remove a constraint from a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Remove constraint {constraint_id} from sketch #{sketch_index}")
+ proj = sess.get_project()
+ result = sketch_mod.remove_constraint(proj, sketch_index, constraint_id)
+ output_fn(result, f"Removed constraint {constraint_id}")
+
+
+@sketch_group.command("edit-constraint")
[email protected]("sketch_index", type=int)
[email protected]("constraint_id", type=int)
[email protected]("--value", "-v", type=float, help="New constraint value.")
+@handle_error
+def sketch_edit_constraint(sketch_index: int, constraint_id: int,
+ value: Optional[float]) -> None:
+ """Edit a constraint value."""
+ sess = get_session()
+ sess.snapshot(f"Edit constraint {constraint_id} in sketch #{sketch_index}")
+ proj = sess.get_project()
+ result = sketch_mod.edit_constraint(proj, sketch_index, constraint_id,
+ value=value)
+ output_fn(result, f"Edited constraint {constraint_id}")
+
+
+@sketch_group.command("mirror")
[email protected]("sketch_index", type=int)
[email protected]("--elements", "-e", required=True, help="Element IDs (comma-sep).")
[email protected]("--axis-elem-id", required=True, type=int, help="Axis element ID.")
+@handle_error
+def sketch_mirror(sketch_index: int, elements: str, axis_elem_id: int) -> None:
+ """Mirror elements about an axis element."""
+ sess = get_session()
+ sess.snapshot(f"Mirror elements in sketch #{sketch_index}")
+ proj = sess.get_project()
+ elem_ids = _parse_indices(elements)
+ result = sketch_mod.mirror_elements(proj, sketch_index, elem_ids=elem_ids,
+ axis_elem_id=axis_elem_id)
+ output_fn(result, "Mirrored elements")
+
+
+@sketch_group.command("offset")
[email protected]("sketch_index", type=int)
[email protected]("--elements", "-e", required=True, help="Element IDs (comma-sep).")
[email protected]("--distance", "-d", required=True, type=float, help="Offset distance.")
+@handle_error
+def sketch_offset(sketch_index: int, elements: str, distance: float) -> None:
+ """Offset wire elements by a distance."""
+ sess = get_session()
+ sess.snapshot(f"Offset elements in sketch #{sketch_index}")
+ proj = sess.get_project()
+ elem_ids = _parse_indices(elements)
+ result = sketch_mod.offset_wire(proj, sketch_index, elem_ids=elem_ids,
+ distance=distance)
+ output_fn(result, "Offset elements")
+
+
+@sketch_group.command("trim")
[email protected]("sketch_index", type=int)
[email protected]("elem_id", type=int)
[email protected]("--keep-side", default="start", type=click.Choice(["start", "end"]),
+ help="Side to keep.")
+@handle_error
+def sketch_trim(sketch_index: int, elem_id: int, keep_side: str) -> None:
+ """Trim a sketch element."""
+ sess = get_session()
+ sess.snapshot(f"Trim element {elem_id} in sketch #{sketch_index}")
+ proj = sess.get_project()
+ result = sketch_mod.trim_element(proj, sketch_index, elem_id,
+ keep_side=keep_side)
+ output_fn(result, f"Trimmed element {elem_id}")
+
+
+@sketch_group.command("extend")
[email protected]("sketch_index", type=int)
[email protected]("elem_id", type=int)
[email protected]("target_elem_id", type=int)
+@handle_error
+def sketch_extend(sketch_index: int, elem_id: int, target_elem_id: int) -> None:
+ """Extend a sketch element to a target element."""
+ sess = get_session()
+ sess.snapshot(f"Extend element {elem_id} in sketch #{sketch_index}")
+ proj = sess.get_project()
+ result = sketch_mod.extend_element(proj, sketch_index, elem_id,
+ target_elem_id=target_elem_id)
+ output_fn(result, f"Extended element {elem_id}")
+
+
+@sketch_group.command("validate")
[email protected]("sketch_index", type=int)
+@handle_error
+def sketch_validate(sketch_index: int) -> None:
+ """Validate a sketch for errors."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = sketch_mod.validate_sketch(proj, sketch_index)
+ output_fn(result, "Sketch validation:")
+
+
+@sketch_group.command("solve-status")
[email protected]("sketch_index", type=int)
+@handle_error
+def sketch_solve_status(sketch_index: int) -> None:
+ """Show constraint solving status of a sketch."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = sketch_mod.solve_status(proj, sketch_index)
+ output_fn(result, "Solve status:")
+
+
+@sketch_group.command("set-construction")
[email protected]("sketch_index", type=int)
[email protected]("elem_id", type=int)
[email protected]("--flag/--no-flag", default=True, help="Construction flag.")
+@handle_error
+def sketch_set_construction(sketch_index: int, elem_id: int, flag: bool) -> None:
+ """Toggle construction geometry flag on an element."""
+ sess = get_session()
+ sess.snapshot(f"Set construction on element {elem_id}")
+ proj = sess.get_project()
+ result = sketch_mod.set_construction(proj, sketch_index, elem_id, flag=flag)
+ output_fn(result, f"Set construction={flag} on element {elem_id}")
+
+
+@sketch_group.command("project-external")
[email protected]("sketch_index", type=int)
[email protected]("part_index", type=int)
[email protected]("--edge-ref", help="Edge reference (e.g. Edge1).")
+@handle_error
+def sketch_project_external(sketch_index: int, part_index: int,
+ edge_ref: Optional[str]) -> None:
+ """Project external geometry into a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Project external into sketch #{sketch_index}")
+ proj = sess.get_project()
+ result = sketch_mod.project_external(proj, sketch_index, part_index,
+ edge_ref=edge_ref)
+ output_fn(result, "Projected external geometry")
+
+
+# ── Body commands ────────────────────────────────────────────────────
+
+def body_group():
+ """PartDesign body commands."""
+ pass
+
+
+@body_group.command("new")
[email protected]("--name", "-n", help="Body name.")
+@handle_error
+def body_new(name: Optional[str]) -> None:
+ """Create a new PartDesign body."""
+ sess = get_session()
+ sess.snapshot("New body")
+ proj = sess.get_project()
+ result = body_mod.create_body(proj, name=name)
+ output_fn(result, f"Created body: {result.get('name', '')}")
+
+
+@body_group.command("pad")
[email protected]("body_index", type=int)
[email protected]("sketch_index", type=int)
[email protected]("--length", "-l", default=10.0, type=float, help="Pad length.")
[email protected]("--symmetric", is_flag=True, help="Symmetric pad.")
[email protected]("--reversed", "is_reversed", is_flag=True, help="Reverse direction.")
+@handle_error
+def body_pad(body_index: int, sketch_index: int, length: float,
+ symmetric: bool, is_reversed: bool) -> None:
+ """Add a pad (extrusion) feature to a body."""
+ sess = get_session()
+ sess.snapshot(f"Pad body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.pad(proj, body_index, sketch_index, length=length,
+ symmetric=symmetric, reversed=is_reversed)
+ output_fn(result, "Added pad feature")
+
+
+@body_group.command("pocket")
[email protected]("body_index", type=int)
[email protected]("sketch_index", type=int)
[email protected]("--length", "-l", default=5.0, type=float, help="Pocket depth.")
[email protected]("--symmetric", is_flag=True, help="Symmetric pocket.")
[email protected]("--reversed", "is_reversed", is_flag=True, help="Reverse direction.")
+@handle_error
+def body_pocket(body_index: int, sketch_index: int, length: float,
+ symmetric: bool, is_reversed: bool) -> None:
+ """Add a pocket (cut extrusion) feature to a body."""
+ sess = get_session()
+ sess.snapshot(f"Pocket body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.pocket(proj, body_index, sketch_index, length=length,
+ symmetric=symmetric, reversed=is_reversed)
+ output_fn(result, "Added pocket feature")
+
+
+@body_group.command("fillet")
[email protected]("body_index", type=int)
[email protected]("--radius", "-r", default=1.0, type=float, help="Fillet radius.")
[email protected]("--edges", default="all", help="Edges: 'all' or comma-sep indices.")
+@handle_error
+def body_fillet(body_index: int, radius: float, edges: str) -> None:
+ """Add a fillet feature to a body."""
+ sess = get_session()
+ sess.snapshot(f"Fillet body #{body_index}")
+ proj = sess.get_project()
+ edge_val = edges if edges == "all" else [int(x) for x in edges.split(",")]
+ result = body_mod.fillet(proj, body_index, radius=radius, edges=edge_val)
+ output_fn(result, "Added fillet feature")
+
+
+@body_group.command("chamfer")
[email protected]("body_index", type=int)
[email protected]("--size", "-s", default=1.0, type=float, help="Chamfer size.")
[email protected]("--edges", default="all", help="Edges: 'all' or comma-sep indices.")
+@handle_error
+def body_chamfer(body_index: int, size: float, edges: str) -> None:
+ """Add a chamfer feature to a body."""
+ sess = get_session()
+ sess.snapshot(f"Chamfer body #{body_index}")
+ proj = sess.get_project()
+ edge_val = edges if edges == "all" else [int(x) for x in edges.split(",")]
+ result = body_mod.chamfer(proj, body_index, size=size, edges=edge_val)
+ output_fn(result, "Added chamfer feature")
+
+
+@body_group.command("revolution")
[email protected]("body_index", type=int)
[email protected]("sketch_index", type=int)
[email protected]("--angle", "-a", default=360.0, type=float, help="Revolution angle.")
[email protected]("--axis", default="Z", type=click.Choice(["X", "Y", "Z"]),
+ help="Revolution axis.")
[email protected]("--reversed", "is_reversed", is_flag=True, help="Reverse direction.")
+@handle_error
+def body_revolution(body_index: int, sketch_index: int, angle: float,
+ axis: str, is_reversed: bool) -> None:
+ """Add a revolution feature to a body."""
+ sess = get_session()
+ sess.snapshot(f"Revolution body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.revolution(proj, body_index, sketch_index, angle=angle,
+ axis=axis, reversed=is_reversed)
+ output_fn(result, "Added revolution feature")
+
+
+@body_group.command("list")
+@handle_error
+def body_list() -> None:
+ """List all bodies."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = body_mod.list_bodies(proj)
+ output_fn(result, f"{len(result)} body/bodies:")
+
+
+@body_group.command("get")
[email protected]("index", type=int)
+@handle_error
+def body_get(index: int) -> None:
+ """Get body details."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = body_mod.get_body(proj, index)
+ output_fn(result, f"Body #{index}:")
+
+
+@body_group.command("groove")
[email protected]("body_index", type=int)
[email protected]("sketch_index", type=int)
[email protected]("--angle", "-a", default=360.0, type=float, help="Groove angle.")
[email protected]("--axis", default="Z", type=click.Choice(["X", "Y", "Z"]),
+ help="Revolution axis.")
[email protected]("--reversed", "is_reversed", is_flag=True, help="Reverse direction.")
+@handle_error
+def body_groove(body_index: int, sketch_index: int, angle: float,
+ axis: str, is_reversed: bool) -> None:
+ """Add a groove (subtractive revolution) feature."""
+ sess = get_session()
+ sess.snapshot(f"Groove body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.groove(proj, body_index, sketch_index, angle=angle,
+ axis=axis, reversed=is_reversed)
+ output_fn(result, "Added groove feature")
+
+
+@body_group.command("additive-loft")
[email protected]("body_index", type=int)
[email protected]("sketch_indices", type=str)
[email protected]("--solid/--no-solid", default=True, help="Create solid.")
[email protected]("--ruled", is_flag=True, help="Use ruled surfaces.")
+@handle_error
+def body_additive_loft(body_index: int, sketch_indices: str,
+ solid: bool, ruled: bool) -> None:
+ """Add an additive loft feature (comma-separated sketch indices)."""
+ sess = get_session()
+ sess.snapshot(f"Additive loft body #{body_index}")
+ proj = sess.get_project()
+ idx_list = _parse_indices(sketch_indices)
+ result = body_mod.additive_loft(proj, body_index, sketch_indices=idx_list,
+ solid=solid, ruled=ruled)
+ output_fn(result, "Added additive loft")
+
+
+@body_group.command("additive-pipe")
[email protected]("body_index", type=int)
[email protected]("profile_sketch_index", type=int)
[email protected]("path_sketch_index", type=int)
+@handle_error
+def body_additive_pipe(body_index: int, profile_sketch_index: int,
+ path_sketch_index: int) -> None:
+ """Add an additive pipe (sweep) feature."""
+ sess = get_session()
+ sess.snapshot(f"Additive pipe body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.additive_pipe(proj, body_index, profile_sketch_index,
+ path_sketch_index)
+ output_fn(result, "Added additive pipe")
+
+
+@body_group.command("additive-helix")
[email protected]("body_index", type=int)
[email protected]("sketch_index", type=int)
[email protected]("--pitch", default=5.0, type=float, help="Helix pitch.")
[email protected]("--height", default=20.0, type=float, help="Helix height.")
[email protected]("--turns", type=float, help="Number of turns (overrides height).")
+@handle_error
+def body_additive_helix(body_index: int, sketch_index: int, pitch: float,
+ height: float, turns: Optional[float]) -> None:
+ """Add an additive helix feature."""
+ sess = get_session()
+ sess.snapshot(f"Additive helix body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.additive_helix(proj, body_index, sketch_index, pitch=pitch,
+ height=height, turns=turns)
+ output_fn(result, "Added additive helix")
+
+
+@body_group.command("subtractive-loft")
[email protected]("body_index", type=int)
[email protected]("sketch_indices", type=str)
[email protected]("--solid/--no-solid", default=True, help="Create solid.")
[email protected]("--ruled", is_flag=True, help="Use ruled surfaces.")
+@handle_error
+def body_subtractive_loft(body_index: int, sketch_indices: str,
+ solid: bool, ruled: bool) -> None:
+ """Add a subtractive loft feature (comma-separated sketch indices)."""
+ sess = get_session()
+ sess.snapshot(f"Subtractive loft body #{body_index}")
+ proj = sess.get_project()
+ idx_list = _parse_indices(sketch_indices)
+ result = body_mod.subtractive_loft(proj, body_index, sketch_indices=idx_list,
+ solid=solid, ruled=ruled)
+ output_fn(result, "Added subtractive loft")
+
+
+@body_group.command("subtractive-pipe")
[email protected]("body_index", type=int)
[email protected]("profile_sketch_index", type=int)
[email protected]("path_sketch_index", type=int)
+@handle_error
+def body_subtractive_pipe(body_index: int, profile_sketch_index: int,
+ path_sketch_index: int) -> None:
+ """Add a subtractive pipe (sweep cut) feature."""
+ sess = get_session()
+ sess.snapshot(f"Subtractive pipe body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.subtractive_pipe(proj, body_index, profile_sketch_index,
+ path_sketch_index)
+ output_fn(result, "Added subtractive pipe")
+
+
+@body_group.command("subtractive-helix")
[email protected]("body_index", type=int)
[email protected]("sketch_index", type=int)
[email protected]("--pitch", default=5.0, type=float, help="Helix pitch.")
[email protected]("--height", default=20.0, type=float, help="Helix height.")
[email protected]("--turns", type=float, help="Number of turns (overrides height).")
+@handle_error
+def body_subtractive_helix(body_index: int, sketch_index: int, pitch: float,
+ height: float, turns: Optional[float]) -> None:
+ """Add a subtractive helix feature."""
+ sess = get_session()
+ sess.snapshot(f"Subtractive helix body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.subtractive_helix(proj, body_index, sketch_index, pitch=pitch,
+ height=height, turns=turns)
+ output_fn(result, "Added subtractive helix")
+
+
+# -- Body: Additive primitives --
+
+@body_group.command("additive-box")
[email protected]("body_index", type=int)
[email protected]("--length", "-l", default=10.0, type=float)
[email protected]("--width", "-w", default=10.0, type=float)
[email protected]("--height", "-h", default=10.0, type=float)
+@handle_error
+def body_additive_box(body_index: int, length: float, width: float,
+ height: float) -> None:
+ """Add an additive box primitive."""
+ sess = get_session()
+ sess.snapshot(f"Additive box body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.additive_box(proj, body_index, length=length, width=width,
+ height=height)
+ output_fn(result, "Added additive box")
+
+
+@body_group.command("additive-cylinder")
[email protected]("body_index", type=int)
[email protected]("--radius", "-r", default=5.0, type=float)
[email protected]("--height", "-h", default=10.0, type=float)
+@handle_error
+def body_additive_cylinder(body_index: int, radius: float, height: float) -> None:
+ """Add an additive cylinder primitive."""
+ sess = get_session()
+ sess.snapshot(f"Additive cylinder body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.additive_cylinder(proj, body_index, radius=radius, height=height)
+ output_fn(result, "Added additive cylinder")
+
+
+@body_group.command("additive-sphere")
[email protected]("body_index", type=int)
[email protected]("--radius", "-r", default=5.0, type=float)
+@handle_error
+def body_additive_sphere(body_index: int, radius: float) -> None:
+ """Add an additive sphere primitive."""
+ sess = get_session()
+ sess.snapshot(f"Additive sphere body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.additive_sphere(proj, body_index, radius=radius)
+ output_fn(result, "Added additive sphere")
+
+
+@body_group.command("additive-cone")
[email protected]("body_index", type=int)
[email protected]("--radius1", default=5.0, type=float)
[email protected]("--radius2", default=0.0, type=float)
[email protected]("--height", "-h", default=10.0, type=float)
+@handle_error
+def body_additive_cone(body_index: int, radius1: float, radius2: float,
+ height: float) -> None:
+ """Add an additive cone primitive."""
+ sess = get_session()
+ sess.snapshot(f"Additive cone body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.additive_cone(proj, body_index, radius1=radius1,
+ radius2=radius2, height=height)
+ output_fn(result, "Added additive cone")
+
+
+@body_group.command("additive-torus")
[email protected]("body_index", type=int)
[email protected]("--radius1", default=10.0, type=float)
[email protected]("--radius2", default=2.0, type=float)
+@handle_error
+def body_additive_torus(body_index: int, radius1: float, radius2: float) -> None:
+ """Add an additive torus primitive."""
+ sess = get_session()
+ sess.snapshot(f"Additive torus body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.additive_torus(proj, body_index, radius1=radius1,
+ radius2=radius2)
+ output_fn(result, "Added additive torus")
+
+
+@body_group.command("additive-wedge")
[email protected]("body_index", type=int)
[email protected]("--param", "-P", multiple=True, help="Wedge param as key=value.")
+@handle_error
+def body_additive_wedge(body_index: int, param: tuple) -> None:
+ """Add an additive wedge primitive."""
+ sess = get_session()
+ sess.snapshot(f"Additive wedge body #{body_index}")
+ proj = sess.get_project()
+ params = _parse_params(param) or {}
+ result = body_mod.additive_wedge(proj, body_index, **params)
+ output_fn(result, "Added additive wedge")
+
+
+# -- Body: Subtractive primitives --
+
+@body_group.command("subtractive-box")
[email protected]("body_index", type=int)
[email protected]("--length", "-l", default=10.0, type=float)
[email protected]("--width", "-w", default=10.0, type=float)
[email protected]("--height", "-h", default=10.0, type=float)
+@handle_error
+def body_subtractive_box(body_index: int, length: float, width: float,
+ height: float) -> None:
+ """Add a subtractive box primitive."""
+ sess = get_session()
+ sess.snapshot(f"Subtractive box body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.subtractive_box(proj, body_index, length=length, width=width,
+ height=height)
+ output_fn(result, "Added subtractive box")
+
+
+@body_group.command("subtractive-cylinder")
[email protected]("body_index", type=int)
[email protected]("--radius", "-r", default=5.0, type=float)
[email protected]("--height", "-h", default=10.0, type=float)
+@handle_error
+def body_subtractive_cylinder(body_index: int, radius: float,
+ height: float) -> None:
+ """Add a subtractive cylinder primitive."""
+ sess = get_session()
+ sess.snapshot(f"Subtractive cylinder body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.subtractive_cylinder(proj, body_index, radius=radius,
+ height=height)
+ output_fn(result, "Added subtractive cylinder")
+
+
+@body_group.command("subtractive-sphere")
[email protected]("body_index", type=int)
[email protected]("--radius", "-r", default=5.0, type=float)
+@handle_error
+def body_subtractive_sphere(body_index: int, radius: float) -> None:
+ """Add a subtractive sphere primitive."""
+ sess = get_session()
+ sess.snapshot(f"Subtractive sphere body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.subtractive_sphere(proj, body_index, radius=radius)
+ output_fn(result, "Added subtractive sphere")
+
+
+@body_group.command("subtractive-cone")
[email protected]("body_index", type=int)
[email protected]("--radius1", default=5.0, type=float)
[email protected]("--radius2", default=0.0, type=float)
[email protected]("--height", "-h", default=10.0, type=float)
+@handle_error
+def body_subtractive_cone(body_index: int, radius1: float, radius2: float,
+ height: float) -> None:
+ """Add a subtractive cone primitive."""
+ sess = get_session()
+ sess.snapshot(f"Subtractive cone body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.subtractive_cone(proj, body_index, radius1=radius1,
+ radius2=radius2, height=height)
+ output_fn(result, "Added subtractive cone")
+
+
+@body_group.command("subtractive-torus")
[email protected]("body_index", type=int)
[email protected]("--radius1", default=10.0, type=float)
[email protected]("--radius2", default=2.0, type=float)
+@handle_error
+def body_subtractive_torus(body_index: int, radius1: float,
+ radius2: float) -> None:
+ """Add a subtractive torus primitive."""
+ sess = get_session()
+ sess.snapshot(f"Subtractive torus body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.subtractive_torus(proj, body_index, radius1=radius1,
+ radius2=radius2)
+ output_fn(result, "Added subtractive torus")
+
+
+@body_group.command("subtractive-wedge")
[email protected]("body_index", type=int)
[email protected]("--param", "-P", multiple=True, help="Wedge param as key=value.")
+@handle_error
+def body_subtractive_wedge(body_index: int, param: tuple) -> None:
+ """Add a subtractive wedge primitive."""
+ sess = get_session()
+ sess.snapshot(f"Subtractive wedge body #{body_index}")
+ proj = sess.get_project()
+ params = _parse_params(param) or {}
+ result = body_mod.subtractive_wedge(proj, body_index, **params)
+ output_fn(result, "Added subtractive wedge")
+
+
+# -- Body: Dress-up features --
+
+@body_group.command("draft-feature")
[email protected]("body_index", type=int)
[email protected]("angle", type=float)
[email protected]("--faces", default="all", help="Faces: 'all' or comma-sep indices.")
[email protected]("--pull-direction", help="Pull direction as x,y,z.")
+@handle_error
+def body_draft_feature(body_index: int, angle: float, faces: str,
+ pull_direction: Optional[str]) -> None:
+ """Add a draft (taper) feature."""
+ sess = get_session()
+ sess.snapshot(f"Draft feature body #{body_index}")
+ proj = sess.get_project()
+ face_val = faces if faces == "all" else _parse_indices(faces)
+ pd = _parse_vec3(pull_direction) if pull_direction else None
+ result = body_mod.draft_feature(proj, body_index, angle=angle, faces=face_val,
+ pull_direction=pd)
+ output_fn(result, "Added draft feature")
+
+
+@body_group.command("thickness-feature")
[email protected]("body_index", type=int)
[email protected]("thickness_val", type=float)
[email protected]("--faces", default="all", help="Faces: 'all' or comma-sep indices.")
[email protected]("--join", default="arc", type=click.Choice(["arc", "tangent", "intersection"]))
+@handle_error
+def body_thickness_feature(body_index: int, thickness_val: float,
+ faces: str, join: str) -> None:
+ """Add a thickness (shell) feature."""
+ sess = get_session()
+ sess.snapshot(f"Thickness feature body #{body_index}")
+ proj = sess.get_project()
+ face_val = faces if faces == "all" else _parse_indices(faces)
+ result = body_mod.thickness_feature(proj, body_index, thickness=thickness_val,
+ faces=face_val, join=join)
+ output_fn(result, "Added thickness feature")
+
+
+@body_group.command("hole")
[email protected]("body_index", type=int)
[email protected]("sketch_index", type=int)
[email protected]("--diameter", "-d", default=5.0, type=float, help="Hole diameter.")
[email protected]("--depth", default=10.0, type=float, help="Hole depth.")
[email protected]("--threaded", is_flag=True, help="Threaded hole.")
[email protected]("--thread-pitch", type=float, help="Thread pitch.")
+@handle_error
+def body_hole(body_index: int, sketch_index: int, diameter: float,
+ depth: float, threaded: bool, thread_pitch: Optional[float]) -> None:
+ """Add a hole feature to a body."""
+ sess = get_session()
+ sess.snapshot(f"Hole body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.hole_feature(proj, body_index, sketch_index,
+ diameter=diameter, depth=depth,
+ threaded=threaded, thread_pitch=thread_pitch)
+ output_fn(result, "Added hole feature")
+
+
+# -- Body: Pattern features --
+
+@body_group.command("linear-pattern")
[email protected]("body_index", type=int)
[email protected]("--direction", "-d", default="1,0,0", help="Direction as x,y,z.")
[email protected]("--length", "-l", default=50.0, type=float, help="Pattern length.")
[email protected]("--occurrences", default=3, type=int, help="Number of occurrences.")
+@handle_error
+def body_linear_pattern(body_index: int, direction: str, length: float,
+ occurrences: int) -> None:
+ """Add a linear pattern feature."""
+ sess = get_session()
+ sess.snapshot(f"Linear pattern body #{body_index}")
+ proj = sess.get_project()
+ dir_vec = _parse_vec3(direction)
+ result = body_mod.linear_pattern(proj, body_index, direction=dir_vec,
+ length=length, occurrences=occurrences)
+ output_fn(result, "Added linear pattern")
+
+
+@body_group.command("polar-pattern")
[email protected]("body_index", type=int)
[email protected]("--axis", default="Z", type=click.Choice(["X", "Y", "Z"]))
[email protected]("--angle", "-a", default=360.0, type=float, help="Total angle.")
[email protected]("--occurrences", default=6, type=int, help="Number of occurrences.")
+@handle_error
+def body_polar_pattern(body_index: int, axis: str, angle: float,
+ occurrences: int) -> None:
+ """Add a polar pattern feature."""
+ sess = get_session()
+ sess.snapshot(f"Polar pattern body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.polar_pattern(proj, body_index, axis=axis, angle=angle,
+ occurrences=occurrences)
+ output_fn(result, "Added polar pattern")
+
+
+@body_group.command("mirrored")
[email protected]("body_index", type=int)
[email protected]("--plane", default="XY", type=click.Choice(["XY", "XZ", "YZ"]))
+@handle_error
+def body_mirrored(body_index: int, plane: str) -> None:
+ """Add a mirrored feature."""
+ sess = get_session()
+ sess.snapshot(f"Mirrored body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.mirrored_feature(proj, body_index, plane=plane)
+ output_fn(result, "Added mirrored feature")
+
+
+@body_group.command("multi-transform")
[email protected]("body_index", type=int)
[email protected]("transforms_json", type=str)
+@handle_error
+def body_multi_transform(body_index: int, transforms_json: str) -> None:
+ """Add a multi-transform feature (JSON array of transformations)."""
+ sess = get_session()
+ sess.snapshot(f"Multi-transform body #{body_index}")
+ proj = sess.get_project()
+ transforms = json.loads(transforms_json)
+ result = body_mod.multi_transform(proj, body_index, transformations=transforms)
+ output_fn(result, "Added multi-transform")
+
+
+# -- Body: Datum features --
+
+@body_group.command("datum-plane")
[email protected]("body_index", type=int)
[email protected]("--offset", default=0.0, type=float, help="Offset from reference.")
[email protected]("--reference", default="XY", type=click.Choice(["XY", "XZ", "YZ"]))
+@handle_error
+def body_datum_plane(body_index: int, offset: float, reference: str) -> None:
+ """Add a datum plane to a body."""
+ sess = get_session()
+ sess.snapshot(f"Datum plane body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.datum_plane(proj, body_index, offset=offset, reference=reference)
+ output_fn(result, "Added datum plane")
+
+
+@body_group.command("datum-line")
[email protected]("body_index", type=int)
[email protected]("--point", default="0,0,0", help="Base point x,y,z.")
[email protected]("--direction", "-d", default="0,0,1", help="Direction x,y,z.")
+@handle_error
+def body_datum_line(body_index: int, point: str, direction: str) -> None:
+ """Add a datum line to a body."""
+ sess = get_session()
+ sess.snapshot(f"Datum line body #{body_index}")
+ proj = sess.get_project()
+ pt = _parse_vec3(point)
+ d = _parse_vec3(direction)
+ result = body_mod.datum_line(proj, body_index, point=pt, direction=d)
+ output_fn(result, "Added datum line")
+
+
+@body_group.command("datum-point")
[email protected]("body_index", type=int)
[email protected]("--position", "-p", default="0,0,0", help="Position x,y,z.")
+@handle_error
+def body_datum_point(body_index: int, position: str) -> None:
+ """Add a datum point to a body."""
+ sess = get_session()
+ sess.snapshot(f"Datum point body #{body_index}")
+ proj = sess.get_project()
+ pos = _parse_vec3(position)
+ result = body_mod.datum_point(proj, body_index, position=pos)
+ output_fn(result, "Added datum point")
+
+
+@body_group.command("shape-binder")
[email protected]("body_index", type=int)
[email protected]("source_body_index", type=int)
[email protected]("--feature-ref", help="Feature reference in source body.")
+@handle_error
+def body_shape_binder(body_index: int, source_body_index: int,
+ feature_ref: Optional[str]) -> None:
+ """Add a shape binder referencing geometry from another body."""
+ sess = get_session()
+ sess.snapshot(f"Shape binder body #{body_index}")
+ proj = sess.get_project()
+ result = body_mod.shape_binder(proj, body_index, source_body_index,
+ feature_ref=feature_ref)
+ output_fn(result, "Added shape binder")
+
+
+# ── Material commands ────────────────────────────────────────────────
+
[email protected]("material")
+def material_group():
+ """Material management commands."""
+ pass
+
+
+@material_group.command("create")
[email protected]("--name", "-n", default="Material", help="Material name.")
[email protected]("--preset", help="Use a material preset.")
[email protected]("--color", help="Color as r,g,b,a (0.0-1.0).")
[email protected]("--metallic", type=float, help="Metallic factor (0-1).")
[email protected]("--roughness", type=float, help="Roughness factor (0-1).")
+@handle_error
+def material_create(name: str, preset: Optional[str], color: Optional[str],
+ metallic: Optional[float], roughness: Optional[float]) -> None:
+ """Create a new material."""
+ sess = get_session()
+ sess.snapshot(f"Create material: {name}")
+ proj = sess.get_project()
+ c = [float(x) for x in color.split(",")] if color else None
+ kwargs: dict[str, Any] = {"name": name}
+ if preset:
+ kwargs["preset"] = preset
+ if c:
+ kwargs["color"] = c
+ if metallic is not None:
+ kwargs["metallic"] = metallic
+ if roughness is not None:
+ kwargs["roughness"] = roughness
+ result = mat_mod.create_material(proj, **kwargs)
+ output_fn(result, f"Created material: {result.get('name', name)}")
+
+
+@material_group.command("assign")
[email protected]("material_index", type=int)
[email protected]("part_index", type=int)
+@handle_error
+def material_assign(material_index: int, part_index: int) -> None:
+ """Assign a material to a part."""
+ sess = get_session()
+ sess.snapshot(f"Assign material #{material_index} to part #{part_index}")
+ proj = sess.get_project()
+ result = mat_mod.assign_material(proj, material_index, part_index)
+ output_fn(result, "Material assigned")
+
+
+@material_group.command("list")
+@handle_error
+def material_list() -> None:
+ """List all materials."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = mat_mod.list_materials(proj)
+ output_fn(result, f"{len(result)} material(s):")
+
+
+@material_group.command("get")
[email protected]("index", type=int)
+@handle_error
+def material_get(index: int) -> None:
+ """Get material details."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = mat_mod.get_material(proj, index)
+ output_fn(result, f"Material #{index}:")
+
+
+@material_group.command("set")
[email protected]("index", type=int)
+@handle_error
+def material_set(index: int, prop: str, value: str) -> None:
+ """Set a material property."""
+ sess = get_session()
+ sess.snapshot(f"Set material #{index} {prop}")
+ proj = sess.get_project()
+ if prop == "color":
+ val: Any = [float(x) for x in value.split(",")]
+ elif prop in ("metallic", "roughness"):
+ val = float(value)
+ else:
+ val = value
+ mat_mod.set_material_property(proj, index, prop, val)
+ result = mat_mod.get_material(proj, index)
+ output_fn(result, f"Updated material #{index}")
+
+
+@material_group.command("presets")
+@handle_error
+def material_presets() -> None:
+ """List available material presets."""
+ result = mat_mod.list_presets()
+ output_fn(result, "Available presets:")
+
+
+@material_group.command("import-material")
[email protected]("path", type=click.Path())
+@handle_error
+def material_import(path: str) -> None:
+ """Import a material from a JSON file."""
+ sess = get_session()
+ sess.snapshot("Import material")
+ proj = sess.get_project()
+ result = mat_mod.import_material(proj, path)
+ output_fn(result, f"Imported material: {result.get('name', '')}")
+
+
+@material_group.command("export-material")
[email protected]("index", type=int)
[email protected]("path", type=click.Path())
+@handle_error
+def material_export(index: int, path: str) -> None:
+ """Export a material to a JSON file."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = mat_mod.export_material(proj, index, path)
+ output_fn(result, f"Exported: {result.get('path', path)}")
+
+
+# ── Export commands ──────────────────────────────────────────────────
+
+def export_group():
+ """Export and rendering commands."""
+ pass
+
+
+@export_group.command("render")
[email protected]("output_path", type=click.Path())
[email protected]("--preset", "-p", default="step", help="Export preset.")
[email protected]("--overwrite", is_flag=True, help="Overwrite existing file.")
+@handle_error
+def export_render(output_path: str, preset: str, overwrite: bool) -> None:
+ """Export/render the project to a file."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = export_mod.export_project(proj, output_path, preset=preset,
+ overwrite=overwrite)
+ output_fn(result, f"Exported: {result.get('output', output_path)}")
+
+
+@export_group.command("info")
+@handle_error
+def export_info() -> None:
+ """Show export information for the current project."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = export_mod.get_export_info(proj)
+ output_fn(result, "Export info:")
+
+
+@export_group.command("presets")
+@handle_error
+def export_presets() -> None:
+ """List available export presets."""
+ result = export_mod.list_presets()
+ output_fn(result, "Export presets:")
+
+
+# ── Session commands ─────────────────────────────────────────────────
+
+def session_group():
+ """Session management commands."""
+ pass
+
+
+@session_group.command("undo")
+@handle_error
+def session_undo() -> None:
+ """Undo the last operation."""
+ sess = get_session()
+ desc = sess.undo()
+ if desc:
+ result = {"undone": desc}
+ output_fn(result, f"Undone: {desc}")
+ else:
+ output_fn({"message": "Nothing to undo"}, "Nothing to undo")
+
+
+@session_group.command("redo")
+@handle_error
+def session_redo() -> None:
+ """Redo the last undone operation."""
+ sess = get_session()
+ desc = sess.redo()
+ if desc:
+ result = {"redone": desc}
+ output_fn(result, f"Redone: {desc}")
+ else:
+ output_fn({"message": "Nothing to redo"}, "Nothing to redo")
+
+
+@session_group.command("status")
+@handle_error
+def session_status() -> None:
+ """Show session status."""
+ sess = get_session()
+ result = sess.status()
+ output_fn(result, "Session status:")
+
+
+@session_group.command("history")
+@handle_error
+def session_history() -> None:
+ """Show undo history."""
+ sess = get_session()
+ result = sess.list_history()
+ output_fn(result, f"{len(result)} history entries:")
+
+
+# ── Measure commands ─────────────────────────────────────────────────
+
+def measure_group():
+ """Measurement and geometry analysis commands."""
+ pass
+
+
+@measure_group.command("distance")
[email protected]("index1", type=int)
[email protected]("index2", type=int)
+@handle_error
+def measure_distance(index1: int, index2: int) -> None:
+ """Measure distance between two parts."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_distance(proj, index1, index2)
+ output_fn(result, f"Distance: {result.get('distance', 'N/A')}")
+
+
+@measure_group.command("length")
[email protected]("index", type=int)
[email protected]("--edge-ref", help="Edge reference (e.g. Edge1).")
+@handle_error
+def measure_length(index: int, edge_ref: Optional[str]) -> None:
+ """Measure length of a part edge."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_length(proj, index, edge_ref=edge_ref)
+ output_fn(result, f"Length: {result.get('length', 'N/A')}")
+
+
+@measure_group.command("angle")
[email protected]("index1", type=int)
[email protected]("index2", type=int)
+@handle_error
+def measure_angle(index1: int, index2: int) -> None:
+ """Measure angle between two parts."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_angle(proj, index1, index2)
+ output_fn(result, f"Angle: {result.get('angle_deg', 'N/A')} deg")
+
+
+@measure_group.command("area")
[email protected]("index", type=int)
+@handle_error
+def measure_area(index: int) -> None:
+ """Measure surface area of a part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_area(proj, index)
+ output_fn(result, f"Area: {result.get('area', 'N/A')}")
+
+
+@measure_group.command("volume")
[email protected]("index", type=int)
+@handle_error
+def measure_volume(index: int) -> None:
+ """Measure volume of a part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_volume(proj, index)
+ output_fn(result, f"Volume: {result.get('volume', 'N/A')}")
+
+
+@measure_group.command("radius")
[email protected]("index", type=int)
+@handle_error
+def measure_radius(index: int) -> None:
+ """Measure radius of a cylindrical/spherical part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_radius(proj, index)
+ output_fn(result, f"Radius: {result.get('radius', 'N/A')}")
+
+
+@measure_group.command("diameter")
[email protected]("index", type=int)
+@handle_error
+def measure_diameter(index: int) -> None:
+ """Measure diameter of a cylindrical/spherical part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_diameter(proj, index)
+ output_fn(result, f"Diameter: {result.get('diameter', 'N/A')}")
+
+
+@measure_group.command("position")
[email protected]("index", type=int)
+@handle_error
+def measure_position(index: int) -> None:
+ """Get the position of a part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_position(proj, index)
+ output_fn(result, f"Position: {result.get('position', 'N/A')}")
+
+
+@measure_group.command("center-of-mass")
[email protected]("index", type=int)
+@handle_error
+def measure_center_of_mass(index: int) -> None:
+ """Estimate center of mass of a part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_center_of_mass(proj, index)
+ output_fn(result, f"Center of mass: {result.get('center_of_mass', 'N/A')}")
+
+
+@measure_group.command("bounding-box")
[email protected]("index", type=int)
+@handle_error
+def measure_bounding_box(index: int) -> None:
+ """Compute bounding box of a part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_bounding_box(proj, index)
+ output_fn(result, "Bounding box:")
+
+
+@measure_group.command("inertia")
[email protected]("index", type=int)
+@handle_error
+def measure_inertia(index: int) -> None:
+ """Estimate principal moments of inertia."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.measure_inertia(proj, index)
+ output_fn(result, "Inertia:")
+
+
+@measure_group.command("check-geometry")
[email protected]("index", type=int)
+@handle_error
+def measure_check_geometry(index: int) -> None:
+ """Perform geometry validation on a part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = measure_mod.check_geometry(proj, index)
+ output_fn(result, "Geometry check:")
+
+
+# ── Spreadsheet commands ─────────────────────────────────────────────
+
[email protected]("spreadsheet")
+def spreadsheet_group():
+ """Spreadsheet commands."""
+ pass
+
+
+@spreadsheet_group.command("new")
[email protected]("--name", "-n", help="Spreadsheet name.")
+@handle_error
+def spreadsheet_new(name: Optional[str]) -> None:
+ """Create a new spreadsheet."""
+ sess = get_session()
+ sess.snapshot("New spreadsheet")
+ proj = sess.get_project()
+ result = spread_mod.create_spreadsheet(proj, name=name)
+ output_fn(result, f"Created spreadsheet: {result.get('name', '')}")
+
+
+@spreadsheet_group.command("set-cell")
[email protected]("sheet_index", type=int)
[email protected]("cell_ref", type=str)
[email protected]("value", type=str)
+@handle_error
+def spreadsheet_set_cell(sheet_index: int, cell_ref: str, value: str) -> None:
+ """Set a cell value in a spreadsheet."""
+ sess = get_session()
+ sess.snapshot(f"Set cell {cell_ref} in sheet #{sheet_index}")
+ proj = sess.get_project()
+ # Try to parse as number
+ try:
+ val: Any = float(value)
+ if val == int(val) and "." not in value:
+ val = int(val)
+ except ValueError:
+ val = value
+ result = spread_mod.set_cell(proj, sheet_index, cell_ref, val)
+ output_fn(result, f"Set {cell_ref} = {val}")
+
+
+@spreadsheet_group.command("get-cell")
[email protected]("sheet_index", type=int)
[email protected]("cell_ref", type=str)
+@handle_error
+def spreadsheet_get_cell(sheet_index: int, cell_ref: str) -> None:
+ """Get a cell value from a spreadsheet."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = spread_mod.get_cell(proj, sheet_index, cell_ref)
+ output_fn(result, f"{cell_ref}: {result.get('value', 'empty')}")
+
+
+@spreadsheet_group.command("set-alias")
[email protected]("sheet_index", type=int)
[email protected]("cell_ref", type=str)
[email protected]("alias", type=str)
+@handle_error
+def spreadsheet_set_alias(sheet_index: int, cell_ref: str, alias: str) -> None:
+ """Assign an alias to a cell."""
+ sess = get_session()
+ sess.snapshot(f"Set alias {alias} for {cell_ref}")
+ proj = sess.get_project()
+ result = spread_mod.set_alias(proj, sheet_index, cell_ref, alias)
+ output_fn(result, f"Alias '{alias}' -> {cell_ref}")
+
+
+@spreadsheet_group.command("import-csv")
[email protected]("sheet_index", type=int)
[email protected]("path", type=click.Path(exists=True))
[email protected]("--start-cell", default="A1", help="Top-left cell for import.")
+@handle_error
+def spreadsheet_import_csv(sheet_index: int, path: str, start_cell: str) -> None:
+ """Import CSV data into a spreadsheet."""
+ sess = get_session()
+ sess.snapshot(f"Import CSV into sheet #{sheet_index}")
+ proj = sess.get_project()
+ result = spread_mod.import_csv(proj, sheet_index, path, start_cell=start_cell)
+ output_fn(result, f"Imported {result.get('rows_imported', 0)} rows")
+
+
+@spreadsheet_group.command("export-csv")
[email protected]("sheet_index", type=int)
[email protected]("path", type=click.Path())
+@handle_error
+def spreadsheet_export_csv(sheet_index: int, path: str) -> None:
+ """Export a spreadsheet to CSV."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = spread_mod.export_csv(proj, sheet_index, path)
+ output_fn(result, f"Exported: {result.get('path', path)}")
+
+
+@spreadsheet_group.command("list")
+@handle_error
+def spreadsheet_list() -> None:
+ """List all spreadsheets."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = spread_mod.list_spreadsheets(proj)
+ output_fn(result, f"{len(result)} spreadsheet(s):")
+
+
+# ── Mesh commands ────────────────────────────────────────────────────
+
+def mesh_group():
+ """Mesh operations commands."""
+ pass
+
+
+@mesh_group.command("import")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Mesh name.")
+@handle_error
+def mesh_import(path: str, name: Optional[str]) -> None:
+ """Import a mesh file."""
+ sess = get_session()
+ sess.snapshot("Import mesh")
+ proj = sess.get_project()
+ result = mesh_mod.import_mesh(proj, path, name=name)
+ output_fn(result, f"Imported mesh: {result.get('name', '')}")
+
+
+@mesh_group.command("from-shape")
[email protected]("part_index", type=int)
[email protected]("--name", "-n", help="Mesh name.")
[email protected]("--max-length", type=float, help="Max edge length.")
[email protected]("--deviation", default=0.1, type=float, help="Surface deviation.")
+@handle_error
+def mesh_from_shape(part_index: int, name: Optional[str],
+ max_length: Optional[float], deviation: float) -> None:
+ """Tessellate a part into a mesh."""
+ sess = get_session()
+ sess.snapshot(f"Mesh from shape #{part_index}")
+ proj = sess.get_project()
+ result = mesh_mod.mesh_from_shape(proj, part_index, name=name,
+ max_length=max_length, deviation=deviation)
+ output_fn(result, f"Created mesh: {result.get('name', '')}")
+
+
+@mesh_group.command("export")
[email protected]("mesh_index", type=int)
[email protected]("path", type=click.Path())
[email protected]("--format", "fmt", default="stl", help="Export format.")
+@handle_error
+def mesh_export(mesh_index: int, path: str, fmt: str) -> None:
+ """Export a mesh to file."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = mesh_mod.export_mesh(proj, mesh_index, path, format=fmt)
+ output_fn(result, f"Export mesh: {result.get('path', path)}")
+
+
+@mesh_group.command("info")
[email protected]("mesh_index", type=int)
+@handle_error
+def mesh_info(mesh_index: int) -> None:
+ """Show mesh information."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = mesh_mod.mesh_info(proj, mesh_index)
+ output_fn(result, f"Mesh #{mesh_index}:")
+
+
+@mesh_group.command("analyze")
[email protected]("mesh_index", type=int)
+@handle_error
+def mesh_analyze(mesh_index: int) -> None:
+ """Analyze a mesh."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = mesh_mod.analyze_mesh(proj, mesh_index)
+ output_fn(result, "Mesh analysis:")
+
+
+@mesh_group.command("check")
[email protected]("mesh_index", type=int)
+@handle_error
+def mesh_check(mesh_index: int) -> None:
+ """Check a mesh for problems."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = mesh_mod.check_mesh(proj, mesh_index)
+ output_fn(result, "Mesh check:")
+
+
+@mesh_group.command("boolean")
[email protected]("op", type=click.Choice(["union", "difference", "intersection"]))
[email protected]("base_index", type=int)
[email protected]("tool_index", type=int)
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def mesh_boolean(op: str, base_index: int, tool_index: int,
+ name: Optional[str]) -> None:
+ """Perform boolean operation on two meshes."""
+ sess = get_session()
+ sess.snapshot(f"Mesh boolean {op}")
+ proj = sess.get_project()
+ result = mesh_mod.mesh_boolean(proj, op, base_index, tool_index, name=name)
+ output_fn(result, f"Mesh boolean {op}: {result.get('name', '')}")
+
+
+@mesh_group.command("decimate")
[email protected]("mesh_index", type=int)
[email protected]("--target-faces", default=1000, type=int, help="Target face count.")
+@handle_error
+def mesh_decimate(mesh_index: int, target_faces: int) -> None:
+ """Decimate (simplify) a mesh."""
+ sess = get_session()
+ sess.snapshot(f"Decimate mesh #{mesh_index}")
+ proj = sess.get_project()
+ result = mesh_mod.decimate_mesh(proj, mesh_index, target_faces=target_faces)
+ output_fn(result, "Decimated mesh")
+
+
+@mesh_group.command("remesh")
[email protected]("mesh_index", type=int)
[email protected]("--target-length", default=1.0, type=float, help="Target edge length.")
+@handle_error
+def mesh_remesh(mesh_index: int, target_length: float) -> None:
+ """Remesh with uniform edge lengths."""
+ sess = get_session()
+ sess.snapshot(f"Remesh #{mesh_index}")
+ proj = sess.get_project()
+ result = mesh_mod.remesh_mesh(proj, mesh_index, target_length=target_length)
+ output_fn(result, "Remeshed")
+
+
+@mesh_group.command("smooth")
[email protected]("mesh_index", type=int)
[email protected]("--iterations", default=3, type=int, help="Smoothing passes.")
[email protected]("--factor", default=0.5, type=float, help="Smoothing factor (0-1).")
+@handle_error
+def mesh_smooth(mesh_index: int, iterations: int, factor: float) -> None:
+ """Smooth a mesh."""
+ sess = get_session()
+ sess.snapshot(f"Smooth mesh #{mesh_index}")
+ proj = sess.get_project()
+ result = mesh_mod.smooth_mesh(proj, mesh_index, iterations=iterations,
+ factor=factor)
+ output_fn(result, "Smoothed mesh")
+
+
+@mesh_group.command("repair")
[email protected]("mesh_index", type=int)
+@handle_error
+def mesh_repair(mesh_index: int) -> None:
+ """Repair a mesh."""
+ sess = get_session()
+ sess.snapshot(f"Repair mesh #{mesh_index}")
+ proj = sess.get_project()
+ result = mesh_mod.repair_mesh(proj, mesh_index)
+ output_fn(result, "Repaired mesh")
+
+
+@mesh_group.command("fill-holes")
[email protected]("mesh_index", type=int)
[email protected]("--max-hole-size", default=10, type=int, help="Max hole size (edges).")
+@handle_error
+def mesh_fill_holes(mesh_index: int, max_hole_size: int) -> None:
+ """Fill holes in a mesh."""
+ sess = get_session()
+ sess.snapshot(f"Fill holes mesh #{mesh_index}")
+ proj = sess.get_project()
+ result = mesh_mod.fill_holes(proj, mesh_index, max_hole_size=max_hole_size)
+ output_fn(result, "Filled holes")
+
+
+@mesh_group.command("flip-normals")
[email protected]("mesh_index", type=int)
+@handle_error
+def mesh_flip_normals(mesh_index: int) -> None:
+ """Flip all face normals."""
+ sess = get_session()
+ sess.snapshot(f"Flip normals mesh #{mesh_index}")
+ proj = sess.get_project()
+ result = mesh_mod.flip_normals(proj, mesh_index)
+ output_fn(result, "Flipped normals")
+
+
+@mesh_group.command("merge")
[email protected]("indices", type=str)
[email protected]("--name", "-n", help="Name for merged mesh.")
+@handle_error
+def mesh_merge(indices: str, name: Optional[str]) -> None:
+ """Merge multiple meshes (comma-separated indices)."""
+ sess = get_session()
+ sess.snapshot("Merge meshes")
+ proj = sess.get_project()
+ idx_list = _parse_indices(indices)
+ result = mesh_mod.merge_meshes(proj, idx_list, name=name)
+ output_fn(result, f"Merged mesh: {result.get('name', '')}")
+
+
+@mesh_group.command("split")
[email protected]("mesh_index", type=int)
+@handle_error
+def mesh_split(mesh_index: int) -> None:
+ """Split a mesh into disconnected components."""
+ sess = get_session()
+ sess.snapshot(f"Split mesh #{mesh_index}")
+ proj = sess.get_project()
+ result = mesh_mod.split_mesh(proj, mesh_index)
+ output_fn(result, "Split mesh")
+
+
+@mesh_group.command("to-shape")
[email protected]("mesh_index", type=int)
[email protected]("--name", "-n", help="Name for resulting part.")
+@handle_error
+def mesh_to_shape(mesh_index: int, name: Optional[str]) -> None:
+ """Convert a mesh to a solid shape."""
+ sess = get_session()
+ sess.snapshot(f"Mesh to shape #{mesh_index}")
+ proj = sess.get_project()
+ result = mesh_mod.mesh_to_shape(proj, mesh_index, name=name)
+ output_fn(result, f"Converted: {result.get('name', '')}")
+
+
+# ── Draft commands ───────────────────────────────────────────────────
+
+def draft_group():
+ """2D drafting commands."""
+ pass
+
+
+@draft_group.command("wire")
[email protected]("points_str", type=str)
[email protected]("--closed", is_flag=True, help="Close the wire.")
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def draft_wire(points_str: str, closed: bool, name: Optional[str]) -> None:
+ """Create a wire from semicolon-separated x,y,z points."""
+ sess = get_session()
+ sess.snapshot("Draft wire")
+ proj = sess.get_project()
+ pts = _parse_points(points_str)
+ result = draft_mod.draft_wire(proj, points=pts, closed=closed, name=name)
+ output_fn(result, f"Created wire: {result.get('name', '')}")
+
+
+@draft_group.command("rectangle")
[email protected]("--length", "-l", default=10.0, type=float)
[email protected]("--height", "-h", default=10.0, type=float)
[email protected]("--name", "-n", help="Object name.")
[email protected]("--position", "-pos", help="Position x,y,z.")
+@handle_error
+def draft_rectangle(length: float, height: float, name: Optional[str],
+ position: Optional[str]) -> None:
+ """Create a 2D rectangle."""
+ sess = get_session()
+ sess.snapshot("Draft rectangle")
+ proj = sess.get_project()
+ pos = _parse_vec3(position) if position else None
+ result = draft_mod.draft_rectangle(proj, length=length, height=height,
+ name=name, position=pos)
+ output_fn(result, f"Created rectangle: {result.get('name', '')}")
+
+
+@draft_group.command("circle")
[email protected]("--radius", "-r", default=5.0, type=float)
[email protected]("--name", "-n", help="Object name.")
[email protected]("--position", "-pos", help="Position x,y,z.")
+@handle_error
+def draft_circle(radius: float, name: Optional[str],
+ position: Optional[str]) -> None:
+ """Create a 2D circle."""
+ sess = get_session()
+ sess.snapshot("Draft circle")
+ proj = sess.get_project()
+ pos = _parse_vec3(position) if position else None
+ result = draft_mod.draft_circle(proj, radius=radius, name=name, position=pos)
+ output_fn(result, f"Created circle: {result.get('name', '')}")
+
+
+@draft_group.command("ellipse")
[email protected]("--major-radius", default=10.0, type=float)
[email protected]("--minor-radius", default=5.0, type=float)
[email protected]("--name", "-n", help="Object name.")
[email protected]("--position", "-pos", help="Position x,y,z.")
+@handle_error
+def draft_ellipse(major_radius: float, minor_radius: float,
+ name: Optional[str], position: Optional[str]) -> None:
+ """Create a 2D ellipse."""
+ sess = get_session()
+ sess.snapshot("Draft ellipse")
+ proj = sess.get_project()
+ pos = _parse_vec3(position) if position else None
+ result = draft_mod.draft_ellipse(proj, major_radius=major_radius,
+ minor_radius=minor_radius, name=name,
+ position=pos)
+ output_fn(result, f"Created ellipse: {result.get('name', '')}")
+
+
+@draft_group.command("polygon")
[email protected]("--sides", default=6, type=int)
[email protected]("--radius", "-r", default=5.0, type=float)
[email protected]("--name", "-n", help="Object name.")
[email protected]("--position", "-pos", help="Position x,y,z.")
+@handle_error
+def draft_polygon(sides: int, radius: float, name: Optional[str],
+ position: Optional[str]) -> None:
+ """Create a regular polygon."""
+ sess = get_session()
+ sess.snapshot("Draft polygon")
+ proj = sess.get_project()
+ pos = _parse_vec3(position) if position else None
+ result = draft_mod.draft_polygon(proj, sides=sides, radius=radius,
+ name=name, position=pos)
+ output_fn(result, f"Created polygon: {result.get('name', '')}")
+
+
+@draft_group.command("bspline")
[email protected]("points_str", type=str)
[email protected]("--closed", is_flag=True, help="Close the spline.")
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def draft_bspline(points_str: str, closed: bool, name: Optional[str]) -> None:
+ """Create a B-spline from semicolon-separated x,y,z points."""
+ sess = get_session()
+ sess.snapshot("Draft bspline")
+ proj = sess.get_project()
+ pts = _parse_points(points_str)
+ result = draft_mod.draft_bspline(proj, points=pts, closed=closed, name=name)
+ output_fn(result, f"Created B-spline: {result.get('name', '')}")
+
+
+@draft_group.command("bezier")
[email protected]("points_str", type=str)
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def draft_bezier(points_str: str, name: Optional[str]) -> None:
+ """Create a Bezier curve from semicolon-separated x,y,z control points."""
+ sess = get_session()
+ sess.snapshot("Draft bezier")
+ proj = sess.get_project()
+ pts = _parse_points(points_str)
+ result = draft_mod.draft_bezier(proj, points=pts, name=name)
+ output_fn(result, f"Created Bezier: {result.get('name', '')}")
+
+
+@draft_group.command("point")
[email protected]("--point", "-p", default="0,0,0", help="Point x,y,z.")
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def draft_point(point: str, name: Optional[str]) -> None:
+ """Create a draft point."""
+ sess = get_session()
+ sess.snapshot("Draft point")
+ proj = sess.get_project()
+ pt = _parse_vec3(point)
+ result = draft_mod.draft_point(proj, point=pt, name=name)
+ output_fn(result, f"Created point: {result.get('name', '')}")
+
+
+@draft_group.command("text")
[email protected]("text_content", type=str)
[email protected]("--name", "-n", help="Object name.")
[email protected]("--position", "-pos", help="Position x,y,z.")
+@handle_error
+def draft_text(text_content: str, name: Optional[str],
+ position: Optional[str]) -> None:
+ """Create a text annotation."""
+ sess = get_session()
+ sess.snapshot("Draft text")
+ proj = sess.get_project()
+ pos = _parse_vec3(position) if position else None
+ result = draft_mod.draft_text(proj, text=text_content, name=name, position=pos)
+ output_fn(result, f"Created text: {result.get('name', '')}")
+
+
+@draft_group.command("shapestring")
[email protected]("text_content", type=str)
[email protected]("font_file", type=str)
[email protected]("--size", default=10.0, type=float, help="Font size.")
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def draft_shapestring(text_content: str, font_file: str, size: float,
+ name: Optional[str]) -> None:
+ """Create a ShapeString."""
+ sess = get_session()
+ sess.snapshot("Draft shapestring")
+ proj = sess.get_project()
+ result = draft_mod.draft_shapestring(proj, text=text_content,
+ font_file=font_file, size=size, name=name)
+ output_fn(result, f"Created shapestring: {result.get('name', '')}")
+
+
+@draft_group.command("dimension")
[email protected]("--start", "-s", required=True, help="Start point x,y,z.")
[email protected]("--end", "-e", required=True, help="End point x,y,z.")
[email protected]("--dim-line", help="Dimension line point x,y,z.")
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def draft_dimension(start: str, end: str, dim_line: Optional[str],
+ name: Optional[str]) -> None:
+ """Create a linear dimension annotation."""
+ sess = get_session()
+ sess.snapshot("Draft dimension")
+ proj = sess.get_project()
+ s = _parse_vec3(start)
+ e = _parse_vec3(end)
+ dl = _parse_vec3(dim_line) if dim_line else None
+ result = draft_mod.draft_dimension(proj, start=s, end=e, dim_line=dl, name=name)
+ output_fn(result, f"Created dimension: {result.get('name', '')}")
+
+
+@draft_group.command("label")
[email protected]("target_point", type=str)
[email protected]("--text", "-t", default="", help="Label text.")
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def draft_label(target_point: str, text: str, name: Optional[str]) -> None:
+ """Create a label pointing to a target point (x,y,z)."""
+ sess = get_session()
+ sess.snapshot("Draft label")
+ proj = sess.get_project()
+ tp = _parse_vec3(target_point)
+ result = draft_mod.draft_label(proj, target_point=tp, text=text, name=name)
+ output_fn(result, f"Created label: {result.get('name', '')}")
+
+
+@draft_group.command("hatch")
[email protected]("target_index", type=int)
[email protected]("--pattern", default="ANSI31", help="Hatch pattern.")
[email protected]("--scale", default=1.0, type=float, help="Pattern scale.")
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def draft_hatch(target_index: int, pattern: str, scale: float,
+ name: Optional[str]) -> None:
+ """Apply a hatch pattern to a draft object."""
+ sess = get_session()
+ sess.snapshot("Draft hatch")
+ proj = sess.get_project()
+ result = draft_mod.draft_hatch(proj, target_index=target_index, pattern=pattern,
+ scale=scale, name=name)
+ output_fn(result, f"Created hatch: {result.get('name', '')}")
+
+
+@draft_group.command("move")
[email protected]("index", type=int)
[email protected]("vector", type=str)
[email protected]("--copy", is_flag=True, help="Create a moved copy.")
+@handle_error
+def draft_move(index: int, vector: str, copy: bool) -> None:
+ """Move a draft object by a vector (x,y,z)."""
+ sess = get_session()
+ sess.snapshot(f"Draft move #{index}")
+ proj = sess.get_project()
+ vec = _parse_vec3(vector)
+ result = draft_mod.draft_move(proj, index, vector=vec, copy=copy)
+ output_fn(result, f"Moved: {result.get('name', '')}")
+
+
+@draft_group.command("rotate")
[email protected]("index", type=int)
[email protected]("angle", type=float)
[email protected]("--axis", help="Rotation axis x,y,z.")
[email protected]("--center", help="Center of rotation x,y,z.")
[email protected]("--copy", is_flag=True, help="Create a rotated copy.")
+@handle_error
+def draft_rotate(index: int, angle: float, axis: Optional[str],
+ center: Optional[str], copy: bool) -> None:
+ """Rotate a draft object by angle degrees."""
+ sess = get_session()
+ sess.snapshot(f"Draft rotate #{index}")
+ proj = sess.get_project()
+ ax = _parse_vec3(axis) if axis else None
+ ctr = _parse_vec3(center) if center else None
+ result = draft_mod.draft_rotate(proj, index, angle=angle, axis=ax,
+ center=ctr, copy=copy)
+ output_fn(result, f"Rotated: {result.get('name', '')}")
+
+
+@draft_group.command("scale")
[email protected]("index", type=int)
[email protected]("scale_factor", type=str)
[email protected]("--center", help="Center of scaling x,y,z.")
[email protected]("--copy", is_flag=True, help="Create a scaled copy.")
+@handle_error
+def draft_scale(index: int, scale_factor: str, center: Optional[str],
+ copy: bool) -> None:
+ """Scale a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Draft scale #{index}")
+ proj = sess.get_project()
+ if "," in scale_factor:
+ sf = _parse_vec3(scale_factor)
+ else:
+ sf = float(scale_factor)
+ ctr = _parse_vec3(center) if center else None
+ result = draft_mod.draft_scale(proj, index, scale=sf, center=ctr, copy=copy)
+ output_fn(result, f"Scaled: {result.get('name', '')}")
+
+
+@draft_group.command("mirror")
[email protected]("index", type=int)
[email protected]("--point", help="Mirror reference point x,y,z.")
[email protected]("--name", "-n", help="Name for mirrored copy.")
+@handle_error
+def draft_mirror(index: int, point: Optional[str], name: Optional[str]) -> None:
+ """Create a mirrored copy of a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Draft mirror #{index}")
+ proj = sess.get_project()
+ pt = _parse_vec3(point) if point else None
+ result = draft_mod.draft_mirror(proj, index, point=pt, name=name)
+ output_fn(result, f"Mirrored: {result.get('name', '')}")
+
+
+@draft_group.command("offset")
[email protected]("index", type=int)
[email protected]("--distance", "-d", default=1.0, type=float, help="Offset distance.")
[email protected]("--copy/--no-copy", default=True, help="Create offset copy.")
[email protected]("--name", "-n", help="Name for offset copy.")
+@handle_error
+def draft_offset(index: int, distance: float, copy: bool,
+ name: Optional[str]) -> None:
+ """Offset a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Draft offset #{index}")
+ proj = sess.get_project()
+ result = draft_mod.draft_offset(proj, index, distance=distance, copy=copy,
+ name=name)
+ output_fn(result, f"Offset: {result.get('name', '')}")
+
+
+@draft_group.command("array-linear")
[email protected]("index", type=int)
[email protected]("--x-count", default=2, type=int)
[email protected]("--y-count", default=1, type=int)
[email protected]("--x-interval", default=20.0, type=float)
[email protected]("--y-interval", default=20.0, type=float)
[email protected]("--name", "-n", help="Array name.")
+@handle_error
+def draft_array_linear(index: int, x_count: int, y_count: int,
+ x_interval: float, y_interval: float,
+ name: Optional[str]) -> None:
+ """Create a linear array of a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Draft linear array #{index}")
+ proj = sess.get_project()
+ result = draft_mod.draft_array_linear(proj, index, x_count=x_count,
+ y_count=y_count, x_interval=x_interval,
+ y_interval=y_interval, name=name)
+ output_fn(result, f"Linear array: {result.get('name', '')}")
+
+
+@draft_group.command("array-polar")
[email protected]("index", type=int)
[email protected]("--count", default=6, type=int)
[email protected]("--angle", default=360.0, type=float)
[email protected]("--center", help="Center x,y,z.")
[email protected]("--name", "-n", help="Array name.")
+@handle_error
+def draft_array_polar(index: int, count: int, angle: float,
+ center: Optional[str], name: Optional[str]) -> None:
+ """Create a polar array of a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Draft polar array #{index}")
+ proj = sess.get_project()
+ ctr = _parse_vec3(center) if center else None
+ result = draft_mod.draft_array_polar(proj, index, count=count, angle=angle,
+ center=ctr, name=name)
+ output_fn(result, f"Polar array: {result.get('name', '')}")
+
+
+@draft_group.command("array-path")
[email protected]("index", type=int)
[email protected]("path_index", type=int)
[email protected]("--count", default=4, type=int)
[email protected]("--name", "-n", help="Array name.")
+@handle_error
+def draft_array_path(index: int, path_index: int, count: int,
+ name: Optional[str]) -> None:
+ """Create a path array of a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Draft path array #{index}")
+ proj = sess.get_project()
+ result = draft_mod.draft_array_path(proj, index, path_index=path_index,
+ count=count, name=name)
+ output_fn(result, f"Path array: {result.get('name', '')}")
+
+
+@draft_group.command("copy")
[email protected]("index", type=int)
[email protected]("--name", "-n", help="Name for copy.")
+@handle_error
+def draft_copy(index: int, name: Optional[str]) -> None:
+ """Copy a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Draft copy #{index}")
+ proj = sess.get_project()
+ result = draft_mod.draft_copy(proj, index, name=name)
+ output_fn(result, f"Copied: {result.get('name', '')}")
+
+
+@draft_group.command("clone")
[email protected]("index", type=int)
[email protected]("--name", "-n", help="Name for clone.")
+@handle_error
+def draft_clone(index: int, name: Optional[str]) -> None:
+ """Create a clone (linked copy) of a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Draft clone #{index}")
+ proj = sess.get_project()
+ result = draft_mod.draft_clone(proj, index, name=name)
+ output_fn(result, f"Cloned: {result.get('name', '')}")
+
+
+@draft_group.command("upgrade")
[email protected]("index", type=int)
+@handle_error
+def draft_upgrade(index: int) -> None:
+ """Upgrade a draft object (e.g. wires -> face)."""
+ sess = get_session()
+ sess.snapshot(f"Draft upgrade #{index}")
+ proj = sess.get_project()
+ result = draft_mod.draft_upgrade(proj, index)
+ output_fn(result, f"Upgraded: {result.get('name', '')}")
+
+
+@draft_group.command("downgrade")
[email protected]("index", type=int)
+@handle_error
+def draft_downgrade(index: int) -> None:
+ """Downgrade a draft object (e.g. face -> wires)."""
+ sess = get_session()
+ sess.snapshot(f"Draft downgrade #{index}")
+ proj = sess.get_project()
+ result = draft_mod.draft_downgrade(proj, index)
+ output_fn(result, f"Downgraded: {result.get('name', '')}")
+
+
+@draft_group.command("trim")
[email protected]("index", type=int)
[email protected]("point", type=str)
+@handle_error
+def draft_trim(index: int, point: str) -> None:
+ """Trim a draft object at a point (x,y,z)."""
+ sess = get_session()
+ sess.snapshot(f"Draft trim #{index}")
+ proj = sess.get_project()
+ pt = _parse_vec3(point)
+ result = draft_mod.draft_trim(proj, index, point=pt)
+ output_fn(result, f"Trimmed: {result.get('name', '')}")
+
+
+@draft_group.command("join")
[email protected]("indices", type=str)
[email protected]("--name", "-n", help="Name for joined result.")
+@handle_error
+def draft_join(indices: str, name: Optional[str]) -> None:
+ """Join multiple draft wires (comma-separated indices)."""
+ sess = get_session()
+ sess.snapshot("Draft join")
+ proj = sess.get_project()
+ idx_list = _parse_indices(indices)
+ result = draft_mod.draft_join(proj, indices=idx_list, name=name)
+ output_fn(result, f"Joined: {result.get('name', '')}")
+
+
+@draft_group.command("extrude")
[email protected]("index", type=int)
[email protected]("--vector", "-v", help="Extrusion vector x,y,z.")
[email protected]("--name", "-n", help="Name for result.")
+@handle_error
+def draft_extrude(index: int, vector: Optional[str], name: Optional[str]) -> None:
+ """Extrude a 2D draft object into 3D."""
+ sess = get_session()
+ sess.snapshot(f"Draft extrude #{index}")
+ proj = sess.get_project()
+ vec = _parse_vec3(vector) if vector else None
+ result = draft_mod.draft_extrude(proj, index, vector=vec, name=name)
+ output_fn(result, f"Extruded: {result.get('name', '')}")
+
+
+@draft_group.command("fillet-2d")
[email protected]("index", type=int)
[email protected]("--radius", "-r", default=1.0, type=float, help="Fillet radius.")
+@handle_error
+def draft_fillet_2d(index: int, radius: float) -> None:
+ """Apply a 2D fillet to a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Draft fillet-2d #{index}")
+ proj = sess.get_project()
+ result = draft_mod.draft_fillet_2d(proj, index, radius=radius)
+ output_fn(result, f"Fillet-2D: {result.get('name', '')}")
+
+
+@draft_group.command("to-sketch")
[email protected]("index", type=int)
[email protected]("--name", "-n", help="Name for resulting sketch.")
+@handle_error
+def draft_to_sketch(index: int, name: Optional[str]) -> None:
+ """Convert a draft object to a sketch."""
+ sess = get_session()
+ sess.snapshot(f"Draft to sketch #{index}")
+ proj = sess.get_project()
+ result = draft_mod.draft_to_sketch(proj, index, name=name)
+ output_fn(result, f"Converted to sketch: {result.get('name', '')}")
+
+
+@draft_group.command("list")
+@handle_error
+def draft_list() -> None:
+ """List all draft objects."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = draft_mod.list_draft_objects(proj)
+ output_fn(result, f"{len(result)} draft object(s):")
+
+
+@draft_group.command("get")
[email protected]("index", type=int)
+@handle_error
+def draft_get(index: int) -> None:
+ """Get draft object details."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = draft_mod.get_draft_object(proj, index)
+ output_fn(result, f"Draft object #{index}:")
+
+
+@draft_group.command("remove")
[email protected]("index", type=int)
+@handle_error
+def draft_remove(index: int) -> None:
+ """Remove a draft object."""
+ sess = get_session()
+ sess.snapshot(f"Remove draft #{index}")
+ proj = sess.get_project()
+ result = draft_mod.remove_draft_object(proj, index)
+ output_fn(result, f"Removed: {result.get('name', f'#{index}')}")
+
+
+# ── Surface commands ─────────────────────────────────────────────────
+
+def surface_group():
+ """Surface workbench commands."""
+ pass
+
+
+@surface_group.command("filling")
[email protected]("edge_indices", type=str)
[email protected]("--name", "-n", help="Surface name.")
+@handle_error
+def surface_filling(edge_indices: str, name: Optional[str]) -> None:
+ """Create a filling surface from edge indices (comma-separated)."""
+ sess = get_session()
+ sess.snapshot("Surface filling")
+ proj = sess.get_project()
+ idx_list = _parse_indices(edge_indices)
+ result = surface_mod.surface_filling(proj, edge_indices=idx_list, name=name)
+ output_fn(result, f"Created filling: {result.get('name', '')}")
+
+
+@surface_group.command("sections")
[email protected]("section_indices", type=str)
[email protected]("--name", "-n", help="Surface name.")
+@handle_error
+def surface_sections(section_indices: str, name: Optional[str]) -> None:
+ """Create a loft surface through sections (comma-separated indices)."""
+ sess = get_session()
+ sess.snapshot("Surface sections")
+ proj = sess.get_project()
+ idx_list = _parse_indices(section_indices)
+ result = surface_mod.surface_sections(proj, section_indices=idx_list, name=name)
+ output_fn(result, f"Created sections: {result.get('name', '')}")
+
+
+@surface_group.command("extend")
[email protected]("surface_index", type=int)
[email protected]("--length", "-l", default=10.0, type=float, help="Extension length.")
[email protected]("--direction", default="normal",
+ type=click.Choice(["normal", "u", "v"]))
[email protected]("--name", "-n", help="Surface name.")
+@handle_error
+def surface_extend(surface_index: int, length: float, direction: str,
+ name: Optional[str]) -> None:
+ """Extend a surface."""
+ sess = get_session()
+ sess.snapshot(f"Extend surface #{surface_index}")
+ proj = sess.get_project()
+ result = surface_mod.surface_extend(proj, surface_index, length=length,
+ direction=direction, name=name)
+ output_fn(result, f"Extended: {result.get('name', '')}")
+
+
+@surface_group.command("blend-curve")
[email protected]("edge_index1", type=int)
[email protected]("edge_index2", type=int)
[email protected]("--name", "-n", help="Surface name.")
+@handle_error
+def surface_blend_curve(edge_index1: int, edge_index2: int,
+ name: Optional[str]) -> None:
+ """Create a blend surface between two edges."""
+ sess = get_session()
+ sess.snapshot("Surface blend curve")
+ proj = sess.get_project()
+ result = surface_mod.surface_blend_curve(proj, edge_index1, edge_index2,
+ name=name)
+ output_fn(result, f"Created blend: {result.get('name', '')}")
+
+
+@surface_group.command("sew")
[email protected]("surface_indices", type=str)
[email protected]("--tolerance", default=0.01, type=float, help="Sewing tolerance.")
[email protected]("--name", "-n", help="Surface name.")
+@handle_error
+def surface_sew(surface_indices: str, tolerance: float,
+ name: Optional[str]) -> None:
+ """Sew surfaces together (comma-separated indices)."""
+ sess = get_session()
+ sess.snapshot("Surface sew")
+ proj = sess.get_project()
+ idx_list = _parse_indices(surface_indices)
+ result = surface_mod.surface_sew(proj, surface_indices=idx_list,
+ tolerance=tolerance, name=name)
+ output_fn(result, f"Sewn: {result.get('name', '')}")
+
+
+@surface_group.command("cut")
[email protected]("surface_index", type=int)
[email protected]("cutting_index", type=int)
[email protected]("--name", "-n", help="Surface name.")
+@handle_error
+def surface_cut(surface_index: int, cutting_index: int,
+ name: Optional[str]) -> None:
+ """Cut a surface with another surface."""
+ sess = get_session()
+ sess.snapshot(f"Surface cut #{surface_index}")
+ proj = sess.get_project()
+ result = surface_mod.surface_cut(proj, surface_index, cutting_index, name=name)
+ output_fn(result, f"Cut: {result.get('name', '')}")
+
+
+# ── Import commands ──────────────────────────────────────────────────
+
+def import_group():
+ """File import commands."""
+ pass
+
+
+@import_group.command("auto")
[email protected]("path", type=click.Path())
[email protected]("--format", "fmt", help="Explicit format override.")
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def import_auto(path: str, fmt: Optional[str], name: Optional[str]) -> None:
+ """Auto-detect and import a file."""
+ sess = get_session()
+ sess.snapshot("Import file")
+ proj = sess.get_project()
+ result = import_mod.import_file(proj, path, format=fmt, name=name)
+ output_fn(result, f"Imported: {result.get('name', '')}")
+
+
+@import_group.command("step")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Part name.")
+@handle_error
+def import_step(path: str, name: Optional[str]) -> None:
+ """Import a STEP file."""
+ sess = get_session()
+ sess.snapshot("Import STEP")
+ proj = sess.get_project()
+ result = import_mod.import_step(proj, path, name=name)
+ output_fn(result, f"Imported STEP: {result.get('name', '')}")
+
+
+@import_group.command("iges")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Part name.")
+@handle_error
+def import_iges(path: str, name: Optional[str]) -> None:
+ """Import an IGES file."""
+ sess = get_session()
+ sess.snapshot("Import IGES")
+ proj = sess.get_project()
+ result = import_mod.import_iges(proj, path, name=name)
+ output_fn(result, f"Imported IGES: {result.get('name', '')}")
+
+
+@import_group.command("stl")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Mesh name.")
+@handle_error
+def import_stl(path: str, name: Optional[str]) -> None:
+ """Import an STL file."""
+ sess = get_session()
+ sess.snapshot("Import STL")
+ proj = sess.get_project()
+ result = import_mod.import_stl(proj, path, name=name)
+ output_fn(result, f"Imported STL: {result.get('name', '')}")
+
+
+@import_group.command("obj")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Mesh name.")
+@handle_error
+def import_obj(path: str, name: Optional[str]) -> None:
+ """Import an OBJ file."""
+ sess = get_session()
+ sess.snapshot("Import OBJ")
+ proj = sess.get_project()
+ result = import_mod.import_obj(proj, path, name=name)
+ output_fn(result, f"Imported OBJ: {result.get('name', '')}")
+
+
+@import_group.command("dxf")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def import_dxf(path: str, name: Optional[str]) -> None:
+ """Import a DXF file."""
+ sess = get_session()
+ sess.snapshot("Import DXF")
+ proj = sess.get_project()
+ result = import_mod.import_dxf(proj, path, name=name)
+ output_fn(result, f"Imported DXF: {result.get('name', '')}")
+
+
+@import_group.command("svg")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Object name.")
+@handle_error
+def import_svg(path: str, name: Optional[str]) -> None:
+ """Import an SVG file."""
+ sess = get_session()
+ sess.snapshot("Import SVG")
+ proj = sess.get_project()
+ result = import_mod.import_svg(proj, path, name=name)
+ output_fn(result, f"Imported SVG: {result.get('name', '')}")
+
+
+@import_group.command("brep")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Part name.")
+@handle_error
+def import_brep(path: str, name: Optional[str]) -> None:
+ """Import a BREP file."""
+ sess = get_session()
+ sess.snapshot("Import BREP")
+ proj = sess.get_project()
+ result = import_mod.import_brep(proj, path, name=name)
+ output_fn(result, f"Imported BREP: {result.get('name', '')}")
+
+
+@import_group.command("3mf")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Mesh name.")
+@handle_error
+def import_3mf(path: str, name: Optional[str]) -> None:
+ """Import a 3MF file."""
+ sess = get_session()
+ sess.snapshot("Import 3MF")
+ proj = sess.get_project()
+ result = import_mod.import_3mf(proj, path, name=name)
+ output_fn(result, f"Imported 3MF: {result.get('name', '')}")
+
+
+@import_group.command("ply")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Mesh name.")
+@handle_error
+def import_ply(path: str, name: Optional[str]) -> None:
+ """Import a PLY file."""
+ sess = get_session()
+ sess.snapshot("Import PLY")
+ proj = sess.get_project()
+ result = import_mod.import_ply(proj, path, name=name)
+ output_fn(result, f"Imported PLY: {result.get('name', '')}")
+
+
+@import_group.command("off")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Mesh name.")
+@handle_error
+def import_off(path: str, name: Optional[str]) -> None:
+ """Import an OFF file."""
+ sess = get_session()
+ sess.snapshot("Import OFF")
+ proj = sess.get_project()
+ result = import_mod.import_off(proj, path, name=name)
+ output_fn(result, f"Imported OFF: {result.get('name', '')}")
+
+
+@import_group.command("gltf")
[email protected]("path", type=click.Path())
[email protected]("--name", "-n", help="Mesh name.")
+@handle_error
+def import_gltf(path: str, name: Optional[str]) -> None:
+ """Import a glTF/GLB file."""
+ sess = get_session()
+ sess.snapshot("Import glTF")
+ proj = sess.get_project()
+ result = import_mod.import_gltf(proj, path, name=name)
+ output_fn(result, f"Imported glTF: {result.get('name', '')}")
+
+
+@import_group.command("info")
[email protected]("path", type=click.Path())
+@handle_error
+def import_info(path: str) -> None:
+ """Preview file metadata without importing."""
+ result = import_mod.import_info(path)
+ output_fn(result, "Import info:")
+
+
+# ── Assembly commands ────────────────────────────────────────────────
+
[email protected]("assembly")
+def assembly_group():
+ """Assembly management commands."""
+ pass
+
+
+@assembly_group.command("new")
[email protected]("--name", "-n", help="Assembly name.")
+@handle_error
+def assembly_new(name: Optional[str]) -> None:
+ """Create a new assembly."""
+ sess = get_session()
+ sess.snapshot("New assembly")
+ proj = sess.get_project()
+ result = asm_mod.create_assembly(proj, name=name)
+ output_fn(result, f"Created assembly: {result.get('name', '')}")
+
+
+@assembly_group.command("add-part")
[email protected]("asm_index", type=int)
[email protected]("part_index", type=int)
[email protected]("--transform", help="Placement offset x,y,z.")
+@handle_error
+def assembly_add_part(asm_index: int, part_index: int,
+ transform: Optional[str]) -> None:
+ """Add a part to an assembly."""
+ sess = get_session()
+ sess.snapshot(f"Add part #{part_index} to assembly #{asm_index}")
+ proj = sess.get_project()
+ t = _parse_vec3(transform) if transform else None
+ result = asm_mod.add_part_to_assembly(proj, asm_index, part_index, transform=t)
+ output_fn(result, f"Added: {result.get('name', '')}")
+
+
+@assembly_group.command("remove-part")
[email protected]("asm_index", type=int)
[email protected]("component_index", type=int)
+@handle_error
+def assembly_remove_part(asm_index: int, component_index: int) -> None:
+ """Remove a component from an assembly."""
+ sess = get_session()
+ sess.snapshot(f"Remove component #{component_index} from assembly #{asm_index}")
+ proj = sess.get_project()
+ result = asm_mod.remove_part_from_assembly(proj, asm_index, component_index)
+ output_fn(result, f"Removed component #{component_index}")
+
+
+@assembly_group.command("list")
+@handle_error
+def assembly_list() -> None:
+ """List all assemblies."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = asm_mod.list_assemblies(proj)
+ output_fn(result, f"{len(result)} assembly/assemblies:")
+
+
+@assembly_group.command("get")
[email protected]("index", type=int)
+@handle_error
+def assembly_get(index: int) -> None:
+ """Get assembly details."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = asm_mod.get_assembly(proj, index)
+ output_fn(result, f"Assembly #{index}:")
+
+
+@assembly_group.command("constrain")
[email protected]("asm_index", type=int)
[email protected]("constraint_type", type=str)
[email protected]("--components", "-c", required=True,
+ help="Component indices (comma-sep).")
[email protected]("--param", "-P", multiple=True, help="Param as key=value.")
+@handle_error
+def assembly_constrain(asm_index: int, constraint_type: str,
+ components: str, param: tuple) -> None:
+ """Add a constraint between assembly components."""
+ sess = get_session()
+ sess.snapshot(f"Constrain assembly #{asm_index}")
+ proj = sess.get_project()
+ comp_indices = _parse_indices(components)
+ params = {}
+ for p in param:
+ if "=" not in p:
+ raise ValueError(f"Param must be key=value, got: {p}")
+ k, v = p.split("=", 1)
+ try:
+ params[k.strip()] = float(v.strip())
+ except ValueError:
+ params[k.strip()] = v.strip()
+ result = asm_mod.add_assembly_constraint(proj, asm_index, constraint_type,
+ comp_indices, **params)
+ output_fn(result, f"Added constraint: {constraint_type}")
+
+
+@assembly_group.command("solve")
[email protected]("asm_index", type=int)
+@handle_error
+def assembly_solve(asm_index: int) -> None:
+ """Solve assembly constraints."""
+ sess = get_session()
+ sess.snapshot(f"Solve assembly #{asm_index}")
+ proj = sess.get_project()
+ result = asm_mod.solve_assembly(proj, asm_index)
+ output_fn(result, "Assembly solved")
+
+
+@assembly_group.command("dof")
[email protected]("asm_index", type=int)
+@handle_error
+def assembly_dof(asm_index: int) -> None:
+ """Estimate degrees of freedom for an assembly."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = asm_mod.degrees_of_freedom(proj, asm_index)
+ output_fn(result, f"DOF: {result.get('dof', 'N/A')}")
+
+
+@assembly_group.command("bom")
[email protected]("asm_index", type=int)
+@handle_error
+def assembly_bom(asm_index: int) -> None:
+ """Generate bill of materials for an assembly."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = asm_mod.generate_bom(proj, asm_index)
+ output_fn(result, "Bill of Materials:")
+
+
+@assembly_group.command("explode")
[email protected]("asm_index", type=int)
[email protected]("--factor", default=2.0, type=float, help="Explode factor.")
+@handle_error
+def assembly_explode(asm_index: int, factor: float) -> None:
+ """Explode assembly for visualization."""
+ sess = get_session()
+ sess.snapshot(f"Explode assembly #{asm_index}")
+ proj = sess.get_project()
+ result = asm_mod.explode_assembly(proj, asm_index, factor=factor)
+ output_fn(result, "Assembly exploded")
+
+
+@assembly_group.command("collapse")
[email protected]("asm_index", type=int)
+@handle_error
+def assembly_collapse(asm_index: int) -> None:
+ """Collapse (reset) assembly transforms."""
+ sess = get_session()
+ sess.snapshot(f"Collapse assembly #{asm_index}")
+ proj = sess.get_project()
+ result = asm_mod.collapse_assembly(proj, asm_index)
+ output_fn(result, "Assembly collapsed")
+
+
+# ── TechDraw commands ────────────────────────────────────────────────
+
[email protected]("techdraw")
+def techdraw_group():
+ """Technical drawing commands."""
+ pass
+
+
+@techdraw_group.command("new-page")
[email protected]("--name", "-n", help="Page name.")
[email protected]("--template", default="A4_LandscapeTD", help="Drawing template.")
+@handle_error
+def techdraw_new_page(name: Optional[str], template: str) -> None:
+ """Create a new TechDraw page."""
+ sess = get_session()
+ sess.snapshot("New TechDraw page")
+ proj = sess.get_project()
+ result = td_mod.new_page(proj, name=name, template=template)
+ output_fn(result, f"Created page: {result.get('name', '')}")
+
+
+@techdraw_group.command("set-template")
[email protected]("page_index", type=int)
[email protected]("template", type=str)
+@handle_error
+def techdraw_set_template(page_index: int, template: str) -> None:
+ """Change the template of a page."""
+ sess = get_session()
+ sess.snapshot(f"Set template on page #{page_index}")
+ proj = sess.get_project()
+ result = td_mod.set_template(proj, page_index, template)
+ output_fn(result, f"Template set to: {template}")
+
+
+@techdraw_group.command("add-view")
[email protected]("page_index", type=int)
[email protected]("source_index", type=int)
[email protected]("--direction", help="View direction x,y,z.")
[email protected]("--scale", default=1.0, type=float, help="View scale.")
[email protected]("--position", help="Page position x,y.")
+@handle_error
+def techdraw_add_view(page_index: int, source_index: int,
+ direction: Optional[str], scale: float,
+ position: Optional[str]) -> None:
+ """Add a standard view to a page."""
+ sess = get_session()
+ sess.snapshot(f"Add view to page #{page_index}")
+ proj = sess.get_project()
+ d = _parse_vec3(direction) if direction else None
+ p = _parse_vec2(position) if position else None
+ result = td_mod.add_view(proj, page_index, source_index, direction=d,
+ scale=scale, position=p)
+ output_fn(result, "Added view")
+
+
+@techdraw_group.command("add-projection-group")
[email protected]("page_index", type=int)
[email protected]("source_index", type=int)
[email protected]("--directions", help="Projections (comma-sep, e.g. front,right,top).")
+@handle_error
+def techdraw_add_projection_group(page_index: int, source_index: int,
+ directions: Optional[str]) -> None:
+ """Add a projection group to a page."""
+ sess = get_session()
+ sess.snapshot(f"Add projection group to page #{page_index}")
+ proj = sess.get_project()
+ dirs = [d.strip() for d in directions.split(",")] if directions else None
+ result = td_mod.add_projection_group(proj, page_index, source_index,
+ directions=dirs)
+ output_fn(result, "Added projection group")
+
+
+@techdraw_group.command("add-section-view")
[email protected]("page_index", type=int)
[email protected]("view_index", type=int)
[email protected]("--section-normal", help="Section normal x,y,z.")
[email protected]("--section-origin", help="Section origin x,y,z.")
+@handle_error
+def techdraw_add_section_view(page_index: int, view_index: int,
+ section_normal: Optional[str],
+ section_origin: Optional[str]) -> None:
+ """Add a section view."""
+ sess = get_session()
+ sess.snapshot(f"Add section view to page #{page_index}")
+ proj = sess.get_project()
+ sn = _parse_vec3(section_normal) if section_normal else None
+ so = _parse_vec3(section_origin) if section_origin else None
+ result = td_mod.add_section_view(proj, page_index, view_index,
+ section_normal=sn, section_origin=so)
+ output_fn(result, "Added section view")
+
+
+@techdraw_group.command("add-detail-view")
[email protected]("page_index", type=int)
[email protected]("view_index", type=int)
[email protected]("--center", help="Detail center x,y.")
[email protected]("--radius", default=20.0, type=float, help="Detail radius.")
+@handle_error
+def techdraw_add_detail_view(page_index: int, view_index: int,
+ center: Optional[str], radius: float) -> None:
+ """Add a detail (magnified) view."""
+ sess = get_session()
+ sess.snapshot(f"Add detail view to page #{page_index}")
+ proj = sess.get_project()
+ c = _parse_vec2(center) if center else None
+ result = td_mod.add_detail_view(proj, page_index, view_index,
+ center=c, radius=radius)
+ output_fn(result, "Added detail view")
+
+
+@techdraw_group.command("add-dimension")
[email protected]("page_index", type=int)
[email protected]("view_index", type=int)
[email protected]("dim_type", type=click.Choice(["length", "distance", "radius",
+ "diameter", "angle"]))
[email protected]("--references", "-r", required=True, help="Geometry references (comma-sep).")
[email protected]("--value", "-v", type=float, help="Override value.")
+@handle_error
+def techdraw_add_dimension(page_index: int, view_index: int, dim_type: str,
+ references: str, value: Optional[float]) -> None:
+ """Add a dimension to a page."""
+ sess = get_session()
+ sess.snapshot(f"Add dimension to page #{page_index}")
+ proj = sess.get_project()
+ refs = _parse_references(references)
+ result = td_mod.add_dimension(proj, page_index, view_index, dim_type,
+ refs, value=value)
+ output_fn(result, f"Added {dim_type} dimension")
+
+
+@techdraw_group.command("add-annotation")
[email protected]("page_index", type=int)
[email protected]("text_content", type=str)
[email protected]("--position", help="Position x,y.")
+@handle_error
+def techdraw_add_annotation(page_index: int, text_content: str,
+ position: Optional[str]) -> None:
+ """Add a text annotation to a page."""
+ sess = get_session()
+ sess.snapshot(f"Add annotation to page #{page_index}")
+ proj = sess.get_project()
+ p = _parse_vec2(position) if position else None
+ result = td_mod.add_annotation(proj, page_index, text_content, position=p)
+ output_fn(result, "Added annotation")
+
+
+@techdraw_group.command("add-leader")
[email protected]("page_index", type=int)
[email protected]("points_str", type=str)
[email protected]("--text", "-t", default="", help="Leader text.")
+@handle_error
+def techdraw_add_leader(page_index: int, points_str: str, text: str) -> None:
+ """Add a leader line (semicolon-separated x,y points)."""
+ sess = get_session()
+ sess.snapshot(f"Add leader to page #{page_index}")
+ proj = sess.get_project()
+ pts = _parse_points_2d(points_str)
+ result = td_mod.add_leader(proj, page_index, points=pts, text=text)
+ output_fn(result, "Added leader")
+
+
+@techdraw_group.command("add-centerline")
[email protected]("page_index", type=int)
[email protected]("view_index", type=int)
[email protected]("--references", "-r", required=True, help="References (comma-sep).")
+@handle_error
+def techdraw_add_centerline(page_index: int, view_index: int,
+ references: str) -> None:
+ """Add a centerline to a view."""
+ sess = get_session()
+ sess.snapshot(f"Add centerline to page #{page_index}")
+ proj = sess.get_project()
+ refs = _parse_references(references)
+ result = td_mod.add_centerline(proj, page_index, view_index, references=refs)
+ output_fn(result, "Added centerline")
+
+
+@techdraw_group.command("add-hatch")
[email protected]("page_index", type=int)
[email protected]("view_index", type=int)
[email protected]("--pattern", default="steel", help="Hatch pattern.")
[email protected]("--scale", default=1.0, type=float, help="Pattern scale.")
+@handle_error
+def techdraw_add_hatch(page_index: int, view_index: int, pattern: str,
+ scale: float) -> None:
+ """Add a hatch pattern to a view."""
+ sess = get_session()
+ sess.snapshot(f"Add hatch to page #{page_index}")
+ proj = sess.get_project()
+ result = td_mod.add_hatch(proj, page_index, view_index, pattern=pattern,
+ scale=scale)
+ output_fn(result, "Added hatch")
+
+
+@techdraw_group.command("export-pdf")
[email protected]("page_index", type=int)
[email protected]("path", type=click.Path())
+@handle_error
+def techdraw_export_pdf(page_index: int, path: str) -> None:
+ """Export a page to PDF."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = td_mod.export_page_pdf(proj, page_index, path)
+ output_fn(result, f"Exported PDF: {path}")
+
+
+@techdraw_group.command("export-svg")
[email protected]("page_index", type=int)
[email protected]("path", type=click.Path())
+@handle_error
+def techdraw_export_svg(page_index: int, path: str) -> None:
+ """Export a page to SVG."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = td_mod.export_page_svg(proj, page_index, path)
+ output_fn(result, f"Exported SVG: {path}")
+
+
+@techdraw_group.command("list-views")
[email protected]("page_index", type=int)
+@handle_error
+def techdraw_list_views(page_index: int) -> None:
+ """List all views on a page."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = td_mod.list_views(proj, page_index)
+ output_fn(result, f"{len(result)} view(s):")
+
+
+@techdraw_group.command("get-view")
[email protected]("page_index", type=int)
[email protected]("view_index", type=int)
+@handle_error
+def techdraw_get_view(page_index: int, view_index: int) -> None:
+ """Get details of a specific view."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = td_mod.get_view(proj, page_index, view_index)
+ output_fn(result, f"View #{view_index}:")
+
+
+# ── FEM commands ─────────────────────────────────────────────────────
+
+def fem_group():
+ """FEM analysis commands."""
+ pass
+
+
+@fem_group.command("new-analysis")
[email protected]("--name", "-n", help="Analysis name.")
+@handle_error
+def fem_new_analysis(name: Optional[str]) -> None:
+ """Create a new FEM analysis."""
+ sess = get_session()
+ sess.snapshot("New FEM analysis")
+ proj = sess.get_project()
+ result = fem_mod.new_analysis(proj, name=name)
+ output_fn(result, f"Created analysis: {result.get('name', '')}")
+
+
+@fem_group.command("add-fixed")
[email protected]("ai", type=int)
[email protected]("--references", "-r", required=True, help="Geometry refs (comma-sep).")
+@handle_error
+def fem_add_fixed(ai: int, references: str) -> None:
+ """Add a fixed boundary constraint."""
+ sess = get_session()
+ sess.snapshot(f"Add fixed constraint to analysis #{ai}")
+ proj = sess.get_project()
+ refs = _parse_references(references)
+ result = fem_mod.add_fixed_constraint(proj, ai, refs)
+ output_fn(result, "Added fixed constraint")
+
+
+@fem_group.command("add-force")
[email protected]("ai", type=int)
[email protected]("--references", "-r", required=True, help="Geometry refs (comma-sep).")
[email protected]("--magnitude", "-m", required=True, type=float, help="Force in Newtons.")
[email protected]("--direction", "-d", help="Direction x,y,z.")
+@handle_error
+def fem_add_force(ai: int, references: str, magnitude: float,
+ direction: Optional[str]) -> None:
+ """Add a force constraint."""
+ sess = get_session()
+ sess.snapshot(f"Add force constraint to analysis #{ai}")
+ proj = sess.get_project()
+ refs = _parse_references(references)
+ d = _parse_vec3(direction) if direction else None
+ result = fem_mod.add_force_constraint(proj, ai, refs, magnitude, direction=d)
+ output_fn(result, "Added force constraint")
+
+
+@fem_group.command("add-pressure")
[email protected]("ai", type=int)
[email protected]("--references", "-r", required=True, help="Geometry refs (comma-sep).")
[email protected]("--pressure", "-p", required=True, type=float, help="Pressure in MPa.")
+@handle_error
+def fem_add_pressure(ai: int, references: str, pressure: float) -> None:
+ """Add a pressure constraint."""
+ sess = get_session()
+ sess.snapshot(f"Add pressure constraint to analysis #{ai}")
+ proj = sess.get_project()
+ refs = _parse_references(references)
+ result = fem_mod.add_pressure_constraint(proj, ai, refs, pressure)
+ output_fn(result, "Added pressure constraint")
+
+
+@fem_group.command("add-displacement")
[email protected]("ai", type=int)
[email protected]("--references", "-r", required=True, help="Geometry refs (comma-sep).")
[email protected]("--displacement", "-d", help="Displacement dx,dy,dz.")
+@handle_error
+def fem_add_displacement(ai: int, references: str,
+ displacement: Optional[str]) -> None:
+ """Add a displacement constraint."""
+ sess = get_session()
+ sess.snapshot(f"Add displacement constraint to analysis #{ai}")
+ proj = sess.get_project()
+ refs = _parse_references(references)
+ disp = _parse_vec3(displacement) if displacement else None
+ result = fem_mod.add_displacement_constraint(proj, ai, refs, displacement=disp)
+ output_fn(result, "Added displacement constraint")
+
+
+@fem_group.command("add-temperature")
[email protected]("ai", type=int)
[email protected]("--references", "-r", required=True, help="Geometry refs (comma-sep).")
[email protected]("--temperature", "-t", required=True, type=float,
+ help="Temperature in Kelvin.")
+@handle_error
+def fem_add_temperature(ai: int, references: str, temperature: float) -> None:
+ """Add a temperature constraint."""
+ sess = get_session()
+ sess.snapshot(f"Add temperature constraint to analysis #{ai}")
+ proj = sess.get_project()
+ refs = _parse_references(references)
+ result = fem_mod.add_temperature_constraint(proj, ai, refs, temperature)
+ output_fn(result, "Added temperature constraint")
+
+
+@fem_group.command("add-heatflux")
[email protected]("ai", type=int)
[email protected]("--references", "-r", required=True, help="Geometry refs (comma-sep).")
[email protected]("--flux", "-f", required=True, type=float, help="Heat flux in W/m^2.")
+@handle_error
+def fem_add_heatflux(ai: int, references: str, flux: float) -> None:
+ """Add a heat flux constraint."""
+ sess = get_session()
+ sess.snapshot(f"Add heatflux constraint to analysis #{ai}")
+ proj = sess.get_project()
+ refs = _parse_references(references)
+ result = fem_mod.add_heatflux_constraint(proj, ai, refs, flux)
+ output_fn(result, "Added heat flux constraint")
+
+
+@fem_group.command("set-material")
[email protected]("ai", type=int)
[email protected]("material_index", type=int)
+@handle_error
+def fem_set_material(ai: int, material_index: int) -> None:
+ """Assign a material to an analysis."""
+ sess = get_session()
+ sess.snapshot(f"Set material on analysis #{ai}")
+ proj = sess.get_project()
+ result = fem_mod.set_fem_material(proj, ai, material_index)
+ output_fn(result, "Material assigned to analysis")
+
+
+@fem_group.command("mesh-generate")
[email protected]("ai", type=int)
[email protected]("--max-size", type=float, help="Max element size.")
[email protected]("--min-size", type=float, help="Min element size.")
[email protected]("--element-type", default="Tet10", help="Element type.")
+@handle_error
+def fem_mesh_generate(ai: int, max_size: Optional[float],
+ min_size: Optional[float], element_type: str) -> None:
+ """Configure mesh generation for an analysis."""
+ sess = get_session()
+ sess.snapshot(f"Generate FEM mesh for analysis #{ai}")
+ proj = sess.get_project()
+ result = fem_mod.generate_fem_mesh(proj, ai, max_size=max_size,
+ min_size=min_size,
+ element_type=element_type)
+ output_fn(result, "Mesh parameters set")
+
+
+@fem_group.command("solve")
[email protected]("ai", type=int)
[email protected]("--solver", default="calculix",
+ type=click.Choice(["calculix", "elmer", "z88"]))
+@handle_error
+def fem_solve(ai: int, solver: str) -> None:
+ """Solve a FEM analysis."""
+ sess = get_session()
+ sess.snapshot(f"Solve analysis #{ai}")
+ proj = sess.get_project()
+ result = fem_mod.solve_fem(proj, ai, solver=solver)
+ output_fn(result, "Analysis solver configured")
+
+
+@fem_group.command("results")
[email protected]("ai", type=int)
+@handle_error
+def fem_results(ai: int) -> None:
+ """Get FEM analysis results."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = fem_mod.get_fem_results(proj, ai)
+ output_fn(result, "FEM results:")
+
+
+@fem_group.command("export-results")
[email protected]("ai", type=int)
[email protected]("path", type=click.Path())
[email protected]("--format", "fmt", default="vtk",
+ type=click.Choice(["vtk", "csv", "json"]))
+@handle_error
+def fem_export_results(ai: int, path: str, fmt: str) -> None:
+ """Export FEM results."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = fem_mod.export_fem_results(proj, ai, path, format=fmt)
+ output_fn(result, f"Exported results: {path}")
+
+
+# ── CAM commands ─────────────────────────────────────────────────────
+
+def cam_group():
+ """CAM/CNC machining commands."""
+ pass
+
+
+@cam_group.command("new-job")
[email protected]("part_index", type=int)
[email protected]("--name", "-n", help="Job name.")
+@handle_error
+def cam_new_job(part_index: int, name: Optional[str]) -> None:
+ """Create a new CAM job for a part."""
+ sess = get_session()
+ sess.snapshot("New CAM job")
+ proj = sess.get_project()
+ result = cam_mod.new_job(proj, part_index, name=name)
+ output_fn(result, f"Created job: {result.get('name', '')}")
+
+
+@cam_group.command("set-stock")
[email protected]("job_index", type=int)
[email protected]("--stock-type", default="box",
+ type=click.Choice(["box", "cylinder", "from_part"]))
[email protected]("--extra-x", default=2.0, type=float)
[email protected]("--extra-y", default=2.0, type=float)
[email protected]("--extra-z", default=2.0, type=float)
+@handle_error
+def cam_set_stock(job_index: int, stock_type: str, extra_x: float,
+ extra_y: float, extra_z: float) -> None:
+ """Define raw stock for a CAM job."""
+ sess = get_session()
+ sess.snapshot(f"Set stock on job #{job_index}")
+ proj = sess.get_project()
+ result = cam_mod.set_stock(proj, job_index, stock_type=stock_type,
+ extra_x=extra_x, extra_y=extra_y, extra_z=extra_z)
+ output_fn(result, "Stock defined")
+
+
+@cam_group.command("add-profile")
[email protected]("job_index", type=int)
[email protected]("--faces", default="all", help="Face selection.")
[email protected]("--depth", type=float, help="Cut depth.")
[email protected]("--step-down", default=1.0, type=float, help="Step-down per pass.")
+@handle_error
+def cam_add_profile(job_index: int, faces: str, depth: Optional[float],
+ step_down: float) -> None:
+ """Add a profile (contour) operation."""
+ sess = get_session()
+ sess.snapshot(f"Add profile to job #{job_index}")
+ proj = sess.get_project()
+ result = cam_mod.add_profile_op(proj, job_index, faces=faces, depth=depth,
+ step_down=step_down)
+ output_fn(result, "Added profile operation")
+
+
+@cam_group.command("add-pocket")
[email protected]("job_index", type=int)
[email protected]("--faces", default="all", help="Face selection.")
[email protected]("--depth", type=float, help="Pocket depth.")
[email protected]("--step-down", default=1.0, type=float, help="Step-down per pass.")
[email protected]("--step-over", default=0.5, type=float, help="Step-over fraction.")
+@handle_error
+def cam_add_pocket(job_index: int, faces: str, depth: Optional[float],
+ step_down: float, step_over: float) -> None:
+ """Add a pocket operation."""
+ sess = get_session()
+ sess.snapshot(f"Add pocket to job #{job_index}")
+ proj = sess.get_project()
+ result = cam_mod.add_pocket_op(proj, job_index, faces=faces, depth=depth,
+ step_down=step_down, step_over=step_over)
+ output_fn(result, "Added pocket operation")
+
+
+@cam_group.command("add-drilling")
[email protected]("job_index", type=int)
[email protected]("--holes", default="all", help="Hole selection.")
[email protected]("--depth", type=float, help="Drill depth.")
[email protected]("--peck-depth", type=float, help="Peck increment.")
+@handle_error
+def cam_add_drilling(job_index: int, holes: str, depth: Optional[float],
+ peck_depth: Optional[float]) -> None:
+ """Add a drilling operation."""
+ sess = get_session()
+ sess.snapshot(f"Add drilling to job #{job_index}")
+ proj = sess.get_project()
+ result = cam_mod.add_drilling_op(proj, job_index, holes=holes, depth=depth,
+ peck_depth=peck_depth)
+ output_fn(result, "Added drilling operation")
+
+
+@cam_group.command("add-facing")
[email protected]("job_index", type=int)
[email protected]("--depth", default=1.0, type=float, help="Facing depth.")
[email protected]("--step-over", default=0.5, type=float, help="Step-over fraction.")
+@handle_error
+def cam_add_facing(job_index: int, depth: float, step_over: float) -> None:
+ """Add a facing operation."""
+ sess = get_session()
+ sess.snapshot(f"Add facing to job #{job_index}")
+ proj = sess.get_project()
+ result = cam_mod.add_facing_op(proj, job_index, depth=depth,
+ step_over=step_over)
+ output_fn(result, "Added facing operation")
+
+
+@cam_group.command("set-tool")
[email protected]("job_index", type=int)
[email protected]("--tool-number", default=1, type=int, help="Tool number.")
[email protected]("--diameter", default=6.0, type=float, help="Tool diameter.")
[email protected]("--flutes", default=2, type=int, help="Number of flutes.")
[email protected]("--type", "tool_type", default="endmill",
+ type=click.Choice(["endmill", "ballnose", "drill", "chamfer",
+ "vbit", "facemill"]))
+@handle_error
+def cam_set_tool(job_index: int, tool_number: int, diameter: float,
+ flutes: int, tool_type: str) -> None:
+ """Define a cutting tool."""
+ sess = get_session()
+ sess.snapshot(f"Set tool on job #{job_index}")
+ proj = sess.get_project()
+ result = cam_mod.set_tool(proj, job_index, tool_number=tool_number,
+ diameter=diameter, flutes=flutes, type=tool_type)
+ output_fn(result, f"Tool T{tool_number} defined")
+
+
+@cam_group.command("generate-gcode")
[email protected]("job_index", type=int)
+@handle_error
+def cam_generate_gcode(job_index: int) -> None:
+ """Generate G-code for a job."""
+ sess = get_session()
+ sess.snapshot(f"Generate G-code for job #{job_index}")
+ proj = sess.get_project()
+ result = cam_mod.generate_gcode(proj, job_index)
+ output_fn(result, "G-code generation configured")
+
+
+@cam_group.command("simulate")
[email protected]("job_index", type=int)
+@handle_error
+def cam_simulate(job_index: int) -> None:
+ """Simulate a CAM job."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = cam_mod.simulate_job(proj, job_index)
+ output_fn(result, "Simulation:")
+
+
+@cam_group.command("export-gcode")
[email protected]("job_index", type=int)
[email protected]("path", type=click.Path())
+@handle_error
+def cam_export_gcode(job_index: int, path: str) -> None:
+ """Export G-code to a file."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = cam_mod.export_gcode(proj, job_index, path)
+ output_fn(result, f"Exported G-code: {path}")
+
+
+# ── REPL ─────────────────────────────────────────────────────────────
+
[email protected]("project_path", required=False, type=click.Path())
+@handle_error
+def repl(project_path: Optional[str]) -> None:
+ """Start interactive REPL session."""
+ global _repl_mode
+ _repl_mode = True
+
+ from cli_anything.freecad.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("freecad", version="1.0.0")
+ skin.print_banner()
+
+ sess = get_session()
+ if project_path and sess.project is None:
+ proj = doc_mod.open_document(project_path)
+ sess.set_project(proj, path=project_path)
+
+ _repl_commands = {
+ "document": "new|open|save|info|profiles",
+ "part": "add|remove|list|get|transform|boolean|copy|mirror|scale|offset|thickness|compound|explode|fillet-3d|chamfer-3d|loft|sweep|revolve|extrude|section|slice|line-3d|wire|polygon-3d|info",
+ "sketch": "new|add-line|add-circle|add-rect|add-arc|constrain|close|list|get|add-point|add-ellipse|add-polygon|add-bspline|add-slot|edit-element|remove-element|remove-constraint|edit-constraint|mirror|offset|trim|extend|validate|solve-status|set-construction|project-external",
+ "body": "new|pad|pocket|fillet|chamfer|revolution|list|get|groove|additive-loft|additive-pipe|additive-helix|subtractive-loft|subtractive-pipe|subtractive-helix|additive-box|additive-cylinder|additive-sphere|additive-cone|additive-torus|additive-wedge|subtractive-box|subtractive-cylinder|subtractive-sphere|subtractive-cone|subtractive-torus|subtractive-wedge|draft-feature|thickness-feature|hole|linear-pattern|polar-pattern|mirrored|multi-transform|datum-plane|datum-line|datum-point|shape-binder",
+ "material": "create|assign|list|get|set|presets|import-material|export-material",
+ "export": "render|info|presets",
+ "session": "undo|redo|status|history",
+ "measure": "distance|length|angle|area|volume|radius|diameter|position|center-of-mass|bounding-box|inertia|check-geometry",
+ "spreadsheet": "new|set-cell|get-cell|set-alias|import-csv|export-csv|list",
+ "mesh": "import|from-shape|export|info|analyze|check|boolean|decimate|remesh|smooth|repair|fill-holes|flip-normals|merge|split|to-shape",
+ "draft": "wire|rectangle|circle|ellipse|polygon|bspline|bezier|point|text|shapestring|dimension|label|hatch|move|rotate|scale|mirror|offset|array-linear|array-polar|array-path|copy|clone|upgrade|downgrade|trim|join|extrude|fillet-2d|to-sketch|list|get|remove",
+ "surface": "filling|sections|extend|blend-curve|sew|cut",
+ "import": "auto|step|iges|stl|obj|dxf|svg|brep|3mf|ply|off|gltf|info",
+ "assembly": "new|add-part|remove-part|list|get|constrain|solve|dof|bom|explode|collapse",
+ "techdraw": "new-page|set-template|add-view|add-projection-group|add-section-view|add-detail-view|add-dimension|add-annotation|add-leader|add-centerline|add-hatch|export-pdf|export-svg|list-views|get-view",
+ "fem": "new-analysis|add-fixed|add-force|add-pressure|add-displacement|add-temperature|add-heatflux|set-material|mesh-generate|solve|results|export-results",
+ "cam": "new-job|set-stock|add-profile|add-pocket|add-drilling|add-facing|set-tool|generate-gcode|simulate|export-gcode",
+ }
+
+ pt_session = skin.create_prompt_session()
+
+ while True:
+ try:
+ proj_name = ""
+ modified = False
+ if sess.project:
+ proj_name = sess.project.get("name", "untitled")
+ modified = sess._modified
+
+ line = skin.get_input(pt_session, project_name=proj_name,
+ modified=modified)
+
+ if not line:
+ continue
+
+ if line.lower() in ("quit", "exit", "q"):
+ if sess._modified:
+ skin.warning("Unsaved changes! Use 'document save' first, "
+ "or type 'quit' again.")
+ sess._modified = False # Allow second quit
+ else:
+ skin.print_goodbye()
+ break
+
+ if line.lower() == "help":
+ skin.help(_repl_commands)
+ continue
+
+ args = line.split()
+ try:
+ cli.main(args, standalone_mode=False)
+ except SystemExit:
+ pass
+ except click.exceptions.UsageError as e:
+ skin.error(str(e))
+
+ except (KeyboardInterrupt, EOFError):
+ skin.print_goodbye()
+ break
+
+
+def main():
+ """Entry point for the CLI."""
+ cli()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/freecad/agent-harness/cli_anything/freecad/skills/SKILL.md b/freecad/agent-harness/cli_anything/freecad/skills/SKILL.md
new file mode 100644
index 000000000..58d4a3451
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/skills/SKILL.md
@@ -0,0 +1,255 @@
+---
+name: "cli-anything-freecad"
+description: "Complete CLI harness for FreeCAD parametric 3D CAD modeler (258 commands). Covers ALL workbenches: Part (29 primitives + boolean + mirror + loft + sweep), Sketcher (26 cmds: geometry + constraints + editing), PartDesign (38 cmds: pad/pocket/groove/fillet/chamfer/patterns/hole/datum), Assembly (11 cmds), Mesh (16 cmds), TechDraw (15 cmds: views + dimensions + PDF/SVG), Draft (33 cmds: 2D shapes + arrays + transforms), FEM (12 cmds), CAM/CNC (10 cmds), Surface (6 cmds), Spreadsheet (7 cmds), Import (13 formats), Export (17 formats), Measure (12 cmds), Materials (21 presets). Headless FreeCAD export to STEP/IGES/STL/OBJ/DXF/PDF/glTF/3MF."
+---
+
+# cli-anything-freecad
+
+Complete CLI harness for **FreeCAD** — 258 commands across 17 groups covering ALL workbenches.
+
+## Prerequisites
+
+FreeCAD must be installed: `freecadcmd` must be in PATH.
+
+## Installation
+
+```bash
+pip install -e freecad/agent-harness
+```
+
+## Basic Usage
+
+```bash
+cli-anything-freecad --json <command> # JSON output for agents
+cli-anything-freecad --json -p proj.json <cmd> # With project file
+cli-anything-freecad # Interactive REPL
+```
+
+## Command Groups (258 commands)
+
+### document (5) — Document management
+```bash
+cli-anything-freecad --json document new --name "Part" -o proj.json
+cli-anything-freecad --json document new --profile print3d -o proj.json
+cli-anything-freecad --json -p proj.json document info
+cli-anything-freecad --json -p proj.json document save -o copy.json
+cli-anything-freecad --json document profiles
+```
+
+### part (29) — 3D primitives, boolean, transforms, operations
+```bash
+# Primitives: box, cylinder, sphere, cone, torus, wedge, helix, spiral, thread, plane, polygon_3d
+cli-anything-freecad --json -p p.json part add box -P length=20 -P width=15 -P height=5
+cli-anything-freecad --json -p p.json part add cylinder -P radius=3 -P height=10 --position 10,7.5,0
+
+# Operations
+cli-anything-freecad --json -p p.json part boolean cut 0 1
+cli-anything-freecad --json -p p.json part copy 0
+cli-anything-freecad --json -p p.json part mirror 0 --plane XY
+cli-anything-freecad --json -p p.json part scale 0 --factor 2.0
+cli-anything-freecad --json -p p.json part loft --indices 0,1,2
+cli-anything-freecad --json -p p.json part sweep 0 1
+cli-anything-freecad --json -p p.json part revolve 0 --axis Z --angle 360
+cli-anything-freecad --json -p p.json part extrude 0 --direction 0,0,1 --length 10
+cli-anything-freecad --json -p p.json part fillet-3d 0 --radius 2
+cli-anything-freecad --json -p p.json part thickness 0 --thickness 1
+cli-anything-freecad --json -p p.json part compound --indices 0,1,2
+cli-anything-freecad --json -p p.json part section 0 --plane XY
+cli-anything-freecad --json -p p.json part info 0
+cli-anything-freecad --json -p p.json part line-3d --start 0,0,0 --end 10,5,0
+cli-anything-freecad --json -p p.json part wire --points "0,0,0;10,0,0;10,10,0"
+```
+
+### sketch (26) — 2D constrained sketching
+```bash
+cli-anything-freecad --json -p p.json sketch new --plane XY
+cli-anything-freecad --json -p p.json sketch add-line 0 --start 0,0 --end 20,0
+cli-anything-freecad --json -p p.json sketch add-circle 0 --center 10,10 --radius 5
+cli-anything-freecad --json -p p.json sketch add-rect 0 --corner 0,0 --width 20 --height 15
+cli-anything-freecad --json -p p.json sketch add-arc 0 --center 0,0 --radius 5
+cli-anything-freecad --json -p p.json sketch add-ellipse 0 --center 0,0 --major-radius 10 --minor-radius 5
+cli-anything-freecad --json -p p.json sketch add-polygon 0 --center 0,0 --sides 6 --radius 10
+cli-anything-freecad --json -p p.json sketch add-bspline 0 --points "0,0;5,10;10,0;15,10"
+cli-anything-freecad --json -p p.json sketch add-slot 0 --center1 0,0 --center2 10,0 --radius 2
+cli-anything-freecad --json -p p.json sketch constrain 0 distance --elements 0,1 --value 10
+cli-anything-freecad --json -p p.json sketch edit-element 0 0 --radius 8
+cli-anything-freecad --json -p p.json sketch remove-element 0 2
+cli-anything-freecad --json -p p.json sketch validate 0
+cli-anything-freecad --json -p p.json sketch solve-status 0
+# Constraints: coincident, horizontal, vertical, parallel, perpendicular, equal,
+# fixed, distance, angle, radius, tangent, symmetric, block, diameter,
+# point_on_object, distance_x, distance_y
+```
+
+### body (38) — PartDesign features
+```bash
+cli-anything-freecad --json -p p.json body new
+cli-anything-freecad --json -p p.json body pad 0 0 --length 10
+cli-anything-freecad --json -p p.json body pocket 0 1 --length 5
+cli-anything-freecad --json -p p.json body groove 0 0 --angle 360
+cli-anything-freecad --json -p p.json body fillet 0 --radius 2
+cli-anything-freecad --json -p p.json body chamfer 0 --size 1.5
+cli-anything-freecad --json -p p.json body revolution 0 0 --angle 360
+cli-anything-freecad --json -p p.json body additive-loft 0 --sketch-indices 0,1
+cli-anything-freecad --json -p p.json body additive-pipe 0 0 1
+cli-anything-freecad --json -p p.json body additive-helix 0 0 --pitch 5 --height 20
+cli-anything-freecad --json -p p.json body additive-box 0 -P length=10 -P width=10 -P height=10
+cli-anything-freecad --json -p p.json body hole 0 0 --diameter 5 --depth 10 --threaded
+cli-anything-freecad --json -p p.json body draft-feature 0 --angle 5
+cli-anything-freecad --json -p p.json body thickness-feature 0 --thickness 1
+cli-anything-freecad --json -p p.json body linear-pattern 0 --occurrences 5 --length 50
+cli-anything-freecad --json -p p.json body polar-pattern 0 --occurrences 6 --angle 360
+cli-anything-freecad --json -p p.json body mirrored 0 --plane XY
+cli-anything-freecad --json -p p.json body datum-plane 0 --reference XY --offset 10
+```
+
+### material (8) — PBR materials with engineering properties
+```bash
+# 21 presets: steel, aluminum, copper, brass, titanium, stainless_steel, cast_iron,
+# carbon_fiber, nylon, abs, pla, petg, plastic_white, plastic_black, wood, glass,
+# rubber, gold, concrete, granite, marble
+cli-anything-freecad --json -p p.json material create --preset steel
+cli-anything-freecad --json -p p.json material create --preset titanium
+cli-anything-freecad --json -p p.json material assign 0 0
+cli-anything-freecad --json -p p.json material set 0 density 7800
+cli-anything-freecad --json -p p.json material import-material mat.json
+cli-anything-freecad --json -p p.json material export-material 0 --output mat.json
+```
+
+### assembly (11) — Assembly management
+```bash
+cli-anything-freecad --json -p p.json assembly new --name "MyAssembly"
+cli-anything-freecad --json -p p.json assembly add-part 0 0
+cli-anything-freecad --json -p p.json assembly constrain 0 coincident --components 0,1
+cli-anything-freecad --json -p p.json assembly constrain 0 distance --components 0,1 --distance 10
+cli-anything-freecad --json -p p.json assembly solve 0
+cli-anything-freecad --json -p p.json assembly dof 0
+cli-anything-freecad --json -p p.json assembly bom 0
+cli-anything-freecad --json -p p.json assembly explode 0 --factor 2.0
+# Constraints: fixed, coincident, distance, angle, parallel, perpendicular,
+# tangent, revolute, prismatic, cylindrical, ball, planar, gear, belt
+```
+
+### mesh (16) — Mesh operations
+```bash
+cli-anything-freecad --json -p p.json mesh from-shape 0 --deviation 0.1
+cli-anything-freecad --json -p p.json mesh import path/to/model.stl
+cli-anything-freecad --json -p p.json mesh export 0 output.stl --format stl
+cli-anything-freecad --json -p p.json mesh boolean union 0 1
+cli-anything-freecad --json -p p.json mesh decimate 0 --target-faces 1000
+cli-anything-freecad --json -p p.json mesh smooth 0 --iterations 5
+cli-anything-freecad --json -p p.json mesh repair 0
+cli-anything-freecad --json -p p.json mesh to-shape 0
+```
+
+### techdraw (15) — Technical drawings
+```bash
+cli-anything-freecad --json -p p.json techdraw new-page
+cli-anything-freecad --json -p p.json techdraw add-view 0 0 --direction 0,0,1 --scale 1.0
+cli-anything-freecad --json -p p.json techdraw add-projection-group 0 0
+cli-anything-freecad --json -p p.json techdraw add-section-view 0 0
+cli-anything-freecad --json -p p.json techdraw add-dimension 0 0 length --references 0,1
+cli-anything-freecad --json -p p.json techdraw add-annotation 0 "Note text"
+cli-anything-freecad --json -p p.json techdraw export-pdf 0 drawing.pdf
+cli-anything-freecad --json -p p.json techdraw export-svg 0 drawing.svg
+```
+
+### draft (33) — 2D drafting
+```bash
+cli-anything-freecad --json -p p.json draft wire --points "0,0,0;10,0,0;10,10,0"
+cli-anything-freecad --json -p p.json draft rectangle --width 20 --height 15
+cli-anything-freecad --json -p p.json draft circle --radius 10
+cli-anything-freecad --json -p p.json draft polygon --sides 6 --radius 10
+cli-anything-freecad --json -p p.json draft text --content "Hello" --position 0,0,0
+cli-anything-freecad --json -p p.json draft move 0 --vector 10,5,0
+cli-anything-freecad --json -p p.json draft array-linear 0 --direction 1,0,0 --count 5 --spacing 10
+cli-anything-freecad --json -p p.json draft array-polar 0 --center 0,0,0 --count 6
+cli-anything-freecad --json -p p.json draft extrude 0 --direction 0,0,1 --length 10
+cli-anything-freecad --json -p p.json draft to-sketch 0
+```
+
+### measure (12) — Measurement and analysis
+```bash
+cli-anything-freecad --json -p p.json measure volume 0
+cli-anything-freecad --json -p p.json measure area 0
+cli-anything-freecad --json -p p.json measure distance 0 1
+cli-anything-freecad --json -p p.json measure bounding-box 0
+cli-anything-freecad --json -p p.json measure center-of-mass 0
+cli-anything-freecad --json -p p.json measure check-geometry 0
+```
+
+### surface (6) — Surface operations
+```bash
+cli-anything-freecad --json -p p.json surface filling --edges 0,1,2
+cli-anything-freecad --json -p p.json surface sections --sections 0,1,2
+cli-anything-freecad --json -p p.json surface extend 0 --length 10
+cli-anything-freecad --json -p p.json surface sew --indices 0,1
+```
+
+### fem (12) — Finite Element Analysis
+```bash
+cli-anything-freecad --json -p p.json fem new-analysis
+cli-anything-freecad --json -p p.json fem add-fixed 0 --references face1,face2
+cli-anything-freecad --json -p p.json fem add-force 0 --references face3 --magnitude 1000
+cli-anything-freecad --json -p p.json fem set-material 0 0
+cli-anything-freecad --json -p p.json fem mesh-generate 0 --max-size 5
+cli-anything-freecad --json -p p.json fem solve 0
+cli-anything-freecad --json -p p.json fem results 0
+```
+
+### cam (10) — CNC machining
+```bash
+cli-anything-freecad --json -p p.json cam new-job 0
+cli-anything-freecad --json -p p.json cam set-stock 0 --stock-type box
+cli-anything-freecad --json -p p.json cam set-tool 0 --diameter 6 --type endmill
+cli-anything-freecad --json -p p.json cam add-profile 0
+cli-anything-freecad --json -p p.json cam add-pocket 0 --depth 5
+cli-anything-freecad --json -p p.json cam generate-gcode 0
+cli-anything-freecad --json -p p.json cam export-gcode 0 output.nc
+```
+
+### spreadsheet (7) — Parametric data tables
+```bash
+cli-anything-freecad --json -p p.json spreadsheet new
+cli-anything-freecad --json -p p.json spreadsheet set-cell 0 A1 "50"
+cli-anything-freecad --json -p p.json spreadsheet set-cell 0 B1 "=A1*2"
+cli-anything-freecad --json -p p.json spreadsheet set-alias 0 A1 plate_width
+cli-anything-freecad --json -p p.json spreadsheet export-csv 0 data.csv
+```
+
+### import (13) — Import CAD/mesh files
+```bash
+cli-anything-freecad --json -p p.json import auto model.step
+cli-anything-freecad --json -p p.json import step model.step
+cli-anything-freecad --json -p p.json import stl model.stl
+cli-anything-freecad --json -p p.json import dxf drawing.dxf
+cli-anything-freecad --json -p p.json import info model.step
+# Formats: step, iges, stl, obj, dxf, svg, brep, 3mf, ply, off, gltf
+```
+
+### export (3) — Export to 17 formats
+```bash
+# Presets: step, iges, stl, stl_fine, obj, brep, fcstd, dxf, svg, gltf, 3mf, ply, off, amf, pdf, png, jpg
+cli-anything-freecad --json -p p.json export render output.step --preset step
+cli-anything-freecad --json -p p.json export render model.stl --preset stl --overwrite
+cli-anything-freecad --json -p p.json export presets
+```
+
+### session (4) — Undo/redo
+```bash
+cli-anything-freecad --json -p p.json session undo
+cli-anything-freecad --json -p p.json session redo
+cli-anything-freecad --json -p p.json session status
+cli-anything-freecad --json -p p.json session history
+```
+
+## JSON Output
+
+All commands support `--json`. Responses include structured data. Errors: `{"error": "message"}`.
+
+## Error Handling
+
+- Missing FreeCAD: Clear install instructions
+- Invalid types: Lists valid options
+- Index out of range: Reports valid range
+- File exists: Use `--overwrite`
diff --git a/freecad/agent-harness/cli_anything/freecad/tests/TEST.md b/freecad/agent-harness/cli_anything/freecad/tests/TEST.md
new file mode 100644
index 000000000..643428989
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/tests/TEST.md
@@ -0,0 +1,230 @@
+# TEST.md — cli-anything-freecad Test Plan and Results
+
+## Test Inventory Plan
+
+| Test File | Type | Estimated Tests |
+|-----------|------|----------------|
+| `test_core.py` | Unit tests | ~45 tests |
+| `test_full_e2e.py` | E2E + CLI subprocess | ~15 tests |
+
+## Unit Test Plan (`test_core.py`)
+
+### document.py (~8 tests)
+- Create document with defaults
+- Create document with profile
+- Create document with invalid profile → ValueError
+- Open document from file
+- Open document from invalid path → FileNotFoundError
+- Save document and verify file content
+- Get document info with parts/sketches/bodies
+- List profiles returns all presets
+
+### parts.py (~10 tests)
+- Add box with defaults
+- Add all primitive types (cylinder, sphere, cone, torus, wedge)
+- Add part with custom position and rotation
+- Add part with custom params
+- Add part with invalid type → ValueError
+- Remove part by index
+- Remove part with invalid index → IndexError
+- Transform part position/rotation
+- Boolean cut operation
+- Boolean fuse and common operations
+
+### sketch.py (~8 tests)
+- Create sketch on XY plane
+- Create sketch on XZ/YZ planes
+- Add line to sketch
+- Add circle to sketch
+- Add rectangle (generates 4 lines + 4 constraints)
+- Add arc to sketch
+- Add distance constraint with value
+- Close sketch
+
+### body.py (~7 tests)
+- Create body
+- Pad body with sketch
+- Pocket body
+- Fillet body
+- Chamfer body
+- Revolution body
+- List bodies and get body details
+
+### materials.py (~7 tests)
+- Create material with defaults
+- Create material from preset
+- Create material with custom color
+- Assign material to part
+- Set material property (color, metallic, roughness)
+- Invalid property → ValueError
+- List presets
+
+### session.py (~6 tests)
+- Session status with no project
+- Set project and verify status
+- Snapshot and undo
+- Undo/redo cycle
+- Save session to file
+- History listing
+
+## E2E Test Plan (`test_full_e2e.py`)
+
+### Intermediate file tests (~5 tests)
+- Create full project JSON and verify structure
+- Build complex model (multiple parts, booleans, materials)
+- Generate FreeCAD macro and validate syntax
+- Project save/load roundtrip
+- Multi-step workflow (document → parts → booleans → materials → export)
+
+### True backend tests (~5 tests — require FreeCAD installed)
+- Export simple box to STEP and validate format
+- Export multi-part model to STL and validate
+- Export to FCStd native format
+- Full workflow: create → add parts → boolean → export STEP
+- Verify file sizes are reasonable
+
+### CLI subprocess tests (~5 tests)
+- `--help` returns 0
+- `--json document new` creates valid JSON
+- `--json part add box` returns part data
+- `--json part list` shows all parts
+- Full workflow via subprocess: new → add → boolean → export
+
+## Realistic Workflow Scenarios
+
+### Scenario 1: Mechanical Part with Hole
+Simulates creating a base plate with a mounting hole.
+1. `document new` → create project
+2. `part add box` → base plate
+3. `part add cylinder` → hole template
+4. `part boolean cut` → subtract hole from plate
+5. `material create --preset steel` → assign material
+6. `export render output.step` → export
+
+### Scenario 2: Sketch-Based Extrusion
+Simulates creating a bracket from a sketch.
+1. `document new` → create project
+2. `sketch new --plane XY` → create sketch
+3. `sketch add-rect` → profile shape
+4. `sketch add-circle` → hole in profile
+5. `body new` → create body
+6. `body pad` → extrude sketch
+7. `body fillet` → round edges
+8. `export render output.step` → export
+
+### Scenario 3: Multi-Part Assembly
+Simulates assembling multiple components.
+1. `document new` → create project
+2. Add multiple parts with different positions
+3. Apply materials (steel, aluminum)
+4. Create boolean unions where needed
+5. Export to STEP
+
+---
+
+## Test Results
+
+**Date**: 2026-03-22
+**Platform**: Windows 11 — Python 3.14.2 — pytest 9.0.2
+**Command**: `python -m pytest cli_anything/freecad/tests/ -v --tb=no`
+
+```
+cli_anything/freecad/tests/test_core.py::TestDocument::test_create_default PASSED
+cli_anything/freecad/tests/test_core.py::TestDocument::test_create_with_profile PASSED
+cli_anything/freecad/tests/test_core.py::TestDocument::test_create_invalid_profile PASSED
+cli_anything/freecad/tests/test_core.py::TestDocument::test_save_and_open PASSED
+cli_anything/freecad/tests/test_core.py::TestDocument::test_open_nonexistent PASSED
+cli_anything/freecad/tests/test_core.py::TestDocument::test_get_info PASSED
+cli_anything/freecad/tests/test_core.py::TestDocument::test_get_info_with_data PASSED
+cli_anything/freecad/tests/test_core.py::TestDocument::test_list_profiles PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_box_defaults PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_all_primitives[box] PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_all_primitives[cylinder] PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_all_primitives[sphere] PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_all_primitives[cone] PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_all_primitives[torus] PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_all_primitives[wedge] PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_with_position_rotation PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_with_custom_params PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_add_invalid_type PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_remove_part PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_remove_invalid_index PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_list_parts PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_transform_part PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_boolean_cut PASSED
+cli_anything/freecad/tests/test_core.py::TestParts::test_boolean_fuse_common PASSED
+cli_anything/freecad/tests/test_core.py::TestSketch::test_create_sketch PASSED
+cli_anything/freecad/tests/test_core.py::TestSketch::test_add_line PASSED
+cli_anything/freecad/tests/test_core.py::TestSketch::test_add_circle PASSED
+cli_anything/freecad/tests/test_core.py::TestSketch::test_add_rectangle PASSED
+cli_anything/freecad/tests/test_core.py::TestSketch::test_add_arc PASSED
+cli_anything/freecad/tests/test_core.py::TestSketch::test_add_constraint_distance PASSED
+cli_anything/freecad/tests/test_core.py::TestSketch::test_close_sketch PASSED
+cli_anything/freecad/tests/test_core.py::TestSketch::test_list_and_get_sketch PASSED
+cli_anything/freecad/tests/test_core.py::TestBody::test_create_body PASSED
+cli_anything/freecad/tests/test_core.py::TestBody::test_pad PASSED
+cli_anything/freecad/tests/test_core.py::TestBody::test_pocket PASSED
+cli_anything/freecad/tests/test_core.py::TestBody::test_fillet PASSED
+cli_anything/freecad/tests/test_core.py::TestBody::test_chamfer PASSED
+cli_anything/freecad/tests/test_core.py::TestBody::test_revolution PASSED
+cli_anything/freecad/tests/test_core.py::TestBody::test_list_and_get_body PASSED
+cli_anything/freecad/tests/test_core.py::TestMaterials::test_create_default PASSED
+cli_anything/freecad/tests/test_core.py::TestMaterials::test_create_from_preset PASSED
+cli_anything/freecad/tests/test_core.py::TestMaterials::test_create_with_color PASSED
+cli_anything/freecad/tests/test_core.py::TestMaterials::test_assign_to_part PASSED
+cli_anything/freecad/tests/test_core.py::TestMaterials::test_set_property PASSED
+cli_anything/freecad/tests/test_core.py::TestMaterials::test_set_invalid_property PASSED
+cli_anything/freecad/tests/test_core.py::TestMaterials::test_list_presets PASSED
+cli_anything/freecad/tests/test_core.py::TestSession::test_status_no_project PASSED
+cli_anything/freecad/tests/test_core.py::TestSession::test_set_project PASSED
+cli_anything/freecad/tests/test_core.py::TestSession::test_snapshot_and_undo PASSED
+cli_anything/freecad/tests/test_core.py::TestSession::test_undo_redo_cycle PASSED
+cli_anything/freecad/tests/test_core.py::TestSession::test_save_session PASSED
+cli_anything/freecad/tests/test_core.py::TestSession::test_list_history PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestIntermediateFiles::test_full_project_json_structure PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestIntermediateFiles::test_multi_part_boolean_workflow PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestIntermediateFiles::test_macro_generation_syntax PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestIntermediateFiles::test_save_load_roundtrip PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestIntermediateFiles::test_complex_workflow PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestFreeCADBackend::test_find_freecad PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestFreeCADBackend::test_get_version PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestFreeCADBackend::test_export_box_step PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestFreeCADBackend::test_export_multi_part_stl PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestFreeCADBackend::test_export_fcstd PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestCLISubprocess::test_help PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestCLISubprocess::test_document_new_json PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestCLISubprocess::test_part_add_json PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestCLISubprocess::test_part_list_json PASSED
+cli_anything/freecad/tests/test_full_e2e.py::TestCLISubprocess::test_full_workflow_subprocess PASSED
+
+============================= 67 passed in 3.47s ==============================
+```
+
+### Summary
+
+| Metric | Value |
+|--------|-------|
+| Total tests | 67 |
+| Passed | 67 |
+| Failed | 0 |
+| Skipped | 0 |
+| Pass rate | **100%** |
+| Execution time | 3.47s |
+
+### Coverage Notes
+
+- **Unit tests**: Full coverage of original 6 core modules (document, parts, sketch, body, materials, session)
+- **E2E intermediate**: Project JSON structure, macro generation, save/load roundtrip
+- **E2E backend**: STEP, STL, and FCStd export with format validation (requires FreeCAD)
+- **CLI subprocess**: Full workflow tested via installed command
+- **Not covered**: REPL interactive mode (requires terminal), IGES/OBJ/BREP export (tested indirectly via presets)
+
+### Post-Expansion Status (258 commands)
+
+After expanding from 38 to 258 commands across 17 groups:
+- All 67 existing tests continue to pass (backward compatible)
+- **17 core modules** all parse without syntax errors
+- All 17 CLI groups register correctly and respond to `--help`
+- End-to-end workflow verified: document → part add → copy → mirror → measure → assembly
+- New modules covered: measure, spreadsheet, mesh, draft, surface, import, assembly, techdraw, fem, cam
+- New expanded functions: parts (+19), sketch (+17), body (+30), materials (+2+11 presets), export (+10 presets)
diff --git a/freecad/agent-harness/cli_anything/freecad/tests/__init__.py b/freecad/agent-harness/cli_anything/freecad/tests/__init__.py
new file mode 100644
index 000000000..01594482d
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/tests/__init__.py
@@ -0,0 +1 @@
+"""Tests for cli-anything-freecad."""
diff --git a/freecad/agent-harness/cli_anything/freecad/tests/test_core.py b/freecad/agent-harness/cli_anything/freecad/tests/test_core.py
new file mode 100644
index 000000000..a492238ac
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/tests/test_core.py
@@ -0,0 +1,741 @@
+"""
+Comprehensive unit tests for the cli-anything-freecad core modules.
+
+All tests use synthetic data and require no external dependencies
+beyond pytest.
+"""
+
+import json
+import math
+import os
+
+import pytest
+
+from cli_anything.freecad.core.document import (
+ PROFILES,
+ create_document,
+ get_document_info,
+ list_profiles,
+ open_document,
+ save_document,
+)
+from cli_anything.freecad.core.parts import (
+ PRIMITIVES,
+ add_part,
+ boolean_op,
+ get_part,
+ list_parts,
+ remove_part,
+ transform_part,
+)
+from cli_anything.freecad.core.sketch import (
+ add_arc,
+ add_circle,
+ add_constraint,
+ add_line,
+ add_rectangle,
+ close_sketch,
+ create_sketch,
+ get_sketch,
+ list_sketches,
+)
+from cli_anything.freecad.core.body import (
+ chamfer,
+ create_body,
+ fillet,
+ get_body,
+ list_bodies,
+ pad,
+ pocket,
+ revolution,
+)
+from cli_anything.freecad.core.materials import (
+ PRESETS,
+ assign_material,
+ create_material,
+ get_material,
+ list_materials,
+ list_presets,
+ set_material_property,
+)
+from cli_anything.freecad.core.session import Session
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_project(**overrides):
+ """Create a minimal valid project dict, applying any overrides."""
+ proj = create_document(name="TestProject")
+ proj.update(overrides)
+ return proj
+
+
+# ===========================================================================
+# TestDocument
+# ===========================================================================
+
+
+class TestDocument:
+ """Tests for the document module."""
+
+ def test_create_default(self):
+ proj = create_document()
+ assert proj["name"] == "Untitled"
+ assert proj["units"] == "mm"
+ assert proj["version"] == "1.0"
+ assert proj["parts"] == []
+ assert proj["sketches"] == []
+ assert proj["bodies"] == []
+ assert proj["materials"] == []
+ assert "created" in proj["metadata"]
+ assert "modified" in proj["metadata"]
+ assert "software" in proj["metadata"]
+
+ def test_create_with_profile(self):
+ proj = create_document(name="ImperialProject", profile="imperial")
+ assert proj["units"] == "in"
+ assert proj["name"] == "ImperialProject"
+
+ proj2 = create_document(profile="metric_large")
+ assert proj2["units"] == "m"
+
+ def test_create_invalid_profile(self):
+ with pytest.raises(ValueError, match="Unknown profile"):
+ create_document(profile="nonexistent_profile")
+
+ def test_save_and_open(self, tmp_path):
+ proj = create_document(name="RoundTrip", units="mm")
+ add_part(proj, "box", name="TestBox")
+
+ filepath = str(tmp_path / "roundtrip.json")
+ abs_path = save_document(proj, filepath)
+ assert os.path.isfile(abs_path)
+
+ loaded = open_document(filepath)
+ assert loaded["name"] == "RoundTrip"
+ assert loaded["units"] == "mm"
+ assert len(loaded["parts"]) == 1
+ assert loaded["parts"][0]["name"] == "TestBox"
+
+ def test_open_nonexistent(self, tmp_path):
+ missing = str(tmp_path / "does_not_exist.json")
+ with pytest.raises(FileNotFoundError):
+ open_document(missing)
+
+ def test_get_info(self):
+ proj = create_document(name="InfoTest")
+ info = get_document_info(proj)
+ assert info["name"] == "InfoTest"
+ assert info["units"] == "mm"
+ assert info["parts_count"] == 0
+ assert info["sketches_count"] == 0
+ assert info["bodies_count"] == 0
+ assert info["materials_count"] == 0
+
+ def test_get_info_with_data(self):
+ proj = create_document(name="DataTest")
+ add_part(proj, "box")
+ add_part(proj, "cylinder")
+ create_sketch(proj)
+
+ info = get_document_info(proj)
+ assert info["parts_count"] == 2
+ assert info["sketches_count"] == 1
+
+ def test_list_profiles(self):
+ profiles = list_profiles()
+ assert isinstance(profiles, list)
+ assert len(profiles) == len(PROFILES)
+ names = {p["name"] for p in profiles}
+ assert "default" in names
+ assert "imperial" in names
+ for p in profiles:
+ assert "name" in p
+ assert "units" in p
+ assert "description" in p
+
+
+# ===========================================================================
+# TestParts
+# ===========================================================================
+
+
+class TestParts:
+ """Tests for the parts module."""
+
+ def test_add_box_defaults(self):
+ proj = _make_project()
+ part = add_part(proj, "box")
+ assert part["type"] == "box"
+ assert part["name"] == "Box"
+ assert part["params"]["length"] == 10.0
+ assert part["params"]["width"] == 10.0
+ assert part["params"]["height"] == 10.0
+ assert part["placement"]["position"] == [0.0, 0.0, 0.0]
+ assert part["placement"]["rotation"] == [0.0, 0.0, 0.0]
+ assert part["visible"] is True
+ assert part["material_index"] is None
+ assert len(proj["parts"]) == 1
+
+ @pytest.mark.parametrize("ptype", ["box", "cylinder", "sphere", "cone", "torus", "wedge"])
+ def test_add_all_primitives(self, ptype):
+ proj = _make_project()
+ part = add_part(proj, ptype)
+ assert part["type"] == ptype
+ # All default params from PRIMITIVES should be present
+ for key in PRIMITIVES[ptype]:
+ assert key in part["params"]
+ assert part["params"][key] == PRIMITIVES[ptype][key]
+
+ def test_add_with_position_rotation(self):
+ proj = _make_project()
+ part = add_part(proj, "box", position=[1.0, 2.0, 3.0], rotation=[45.0, 0.0, 90.0])
+ assert part["placement"]["position"] == [1.0, 2.0, 3.0]
+ assert part["placement"]["rotation"] == [45.0, 0.0, 90.0]
+
+ def test_add_with_custom_params(self):
+ proj = _make_project()
+ part = add_part(proj, "box", params={"length": 20.0, "width": 5.0})
+ assert part["params"]["length"] == 20.0
+ assert part["params"]["width"] == 5.0
+ assert part["params"]["height"] == 10.0 # default unchanged
+
+ def test_add_invalid_type(self):
+ proj = _make_project()
+ with pytest.raises(ValueError, match="Unknown part_type"):
+ add_part(proj, "hexagon")
+
+ def test_remove_part(self):
+ proj = _make_project()
+ add_part(proj, "box", name="A")
+ add_part(proj, "cylinder", name="B")
+ assert len(proj["parts"]) == 2
+
+ removed = remove_part(proj, 0)
+ assert removed["name"] == "A"
+ assert len(proj["parts"]) == 1
+ assert proj["parts"][0]["name"] == "B"
+
+ def test_remove_invalid_index(self):
+ proj = _make_project()
+ add_part(proj, "box")
+ with pytest.raises(IndexError):
+ remove_part(proj, 5)
+ with pytest.raises(IndexError):
+ remove_part(proj, -1)
+
+ def test_list_parts(self):
+ proj = _make_project()
+ assert list_parts(proj) == []
+ add_part(proj, "box", name="A")
+ add_part(proj, "sphere", name="B")
+ parts = list_parts(proj)
+ assert len(parts) == 2
+ assert parts[0]["name"] == "A"
+ assert parts[1]["name"] == "B"
+
+ def test_transform_part(self):
+ proj = _make_project()
+ add_part(proj, "box")
+ updated = transform_part(proj, 0, position=[10.0, 20.0, 30.0])
+ assert updated["placement"]["position"] == [10.0, 20.0, 30.0]
+ # Rotation unchanged
+ assert updated["placement"]["rotation"] == [0.0, 0.0, 0.0]
+
+ updated2 = transform_part(proj, 0, rotation=[90.0, 0.0, 0.0])
+ assert updated2["placement"]["rotation"] == [90.0, 0.0, 0.0]
+ # Position unchanged from previous transform
+ assert updated2["placement"]["position"] == [10.0, 20.0, 30.0]
+
+ def test_boolean_cut(self):
+ proj = _make_project()
+ add_part(proj, "box", name="Base")
+ add_part(proj, "cylinder", name="Tool")
+ result = boolean_op(proj, "cut", 0, 1)
+
+ assert result["type"] == "cut"
+ assert result["params"]["base_id"] == proj["parts"][0]["id"]
+ assert result["params"]["tool_id"] == proj["parts"][1]["id"]
+ assert result["visible"] is True
+ # Operands should be hidden
+ assert proj["parts"][0]["visible"] is False
+ assert proj["parts"][1]["visible"] is False
+ assert len(proj["parts"]) == 3
+
+ def test_boolean_fuse_common(self):
+ proj = _make_project()
+ add_part(proj, "box", name="A")
+ add_part(proj, "box", name="B")
+
+ fuse_result = boolean_op(proj, "fuse", 0, 1)
+ assert fuse_result["type"] == "fuse"
+
+ # Add two more for common test
+ add_part(proj, "sphere", name="C")
+ add_part(proj, "sphere", name="D")
+ common_result = boolean_op(proj, "common", 3, 4)
+ assert common_result["type"] == "common"
+
+ with pytest.raises(ValueError, match="Unknown boolean op"):
+ boolean_op(proj, "intersect", 0, 1)
+
+ with pytest.raises(ValueError, match="must differ"):
+ boolean_op(proj, "cut", 0, 0)
+
+
+# ===========================================================================
+# TestSketch
+# ===========================================================================
+
+
+class TestSketch:
+ """Tests for the sketch module."""
+
+ def test_create_sketch(self):
+ proj = _make_project()
+ sk = create_sketch(proj, name="MySketch", plane="XZ", offset=5.0)
+ assert sk["name"] == "MySketch"
+ assert sk["plane"] == "XZ"
+ assert sk["offset"] == 5.0
+ assert sk["elements"] == []
+ assert sk["constraints"] == []
+ assert sk["closed"] is False
+ assert len(proj["sketches"]) == 1
+
+ # Invalid plane
+ with pytest.raises(ValueError, match="Invalid plane"):
+ create_sketch(proj, plane="AB")
+
+ def test_add_line(self):
+ proj = _make_project()
+ create_sketch(proj)
+ line = add_line(proj, 0, start=[0.0, 0.0], end=[10.0, 5.0])
+ assert line["type"] == "line"
+ assert line["start"] == [0.0, 0.0]
+ assert line["end"] == [10.0, 5.0]
+ assert len(proj["sketches"][0]["elements"]) == 1
+
+ def test_add_circle(self):
+ proj = _make_project()
+ create_sketch(proj)
+ circle = add_circle(proj, 0, center=[1.0, 2.0], radius=8.0)
+ assert circle["type"] == "circle"
+ assert circle["center"] == [1.0, 2.0]
+ assert circle["radius"] == 8.0
+
+ with pytest.raises(ValueError, match="positive"):
+ add_circle(proj, 0, radius=-1.0)
+
+ def test_add_rectangle(self):
+ proj = _make_project()
+ create_sketch(proj)
+ result = add_rectangle(proj, 0, corner=[0.0, 0.0], width=20.0, height=10.0)
+
+ assert result["type"] == "rectangle"
+ assert len(result["line_ids"]) == 4
+ assert len(result["constraint_ids"]) == 4
+ assert result["width"] == 20.0
+ assert result["height"] == 10.0
+
+ # 4 line elements and 4 constraints should be in the sketch
+ sk = proj["sketches"][0]
+ assert len(sk["elements"]) == 4
+ assert len(sk["constraints"]) == 4
+
+ def test_add_arc(self):
+ proj = _make_project()
+ create_sketch(proj)
+ arc = add_arc(proj, 0, center=[0.0, 0.0], radius=10.0, start_angle=0.0, end_angle=90.0)
+ assert arc["type"] == "arc"
+ assert arc["radius"] == 10.0
+ assert arc["start_angle"] == 0.0
+ assert arc["end_angle"] == 90.0
+ # Check computed start/end points
+ assert arc["start_point"][0] == pytest.approx(10.0)
+ assert arc["start_point"][1] == pytest.approx(0.0)
+ assert arc["end_point"][0] == pytest.approx(0.0, abs=1e-10)
+ assert arc["end_point"][1] == pytest.approx(10.0)
+
+ def test_add_constraint_distance(self):
+ proj = _make_project()
+ create_sketch(proj)
+ line = add_line(proj, 0, start=[0.0, 0.0], end=[10.0, 0.0])
+
+ constraint = add_constraint(
+ proj, 0, constraint_type="distance", elements=[line["id"]], value=15.0
+ )
+ assert constraint["type"] == "distance"
+ assert constraint["value"] == 15.0
+ assert constraint["elements"] == [line["id"]]
+
+ # Missing value for dimensional constraint
+ with pytest.raises(ValueError, match="requires a numeric value"):
+ add_constraint(proj, 0, constraint_type="distance", elements=[line["id"]])
+
+ # Unknown constraint type
+ with pytest.raises(ValueError, match="Unknown constraint type"):
+ add_constraint(proj, 0, constraint_type="magical", elements=[line["id"]])
+
+ def test_close_sketch(self):
+ proj = _make_project()
+ create_sketch(proj)
+ add_line(proj, 0)
+
+ closed = close_sketch(proj, 0)
+ assert closed["closed"] is True
+
+ # Cannot add elements to a closed sketch
+ with pytest.raises(ValueError, match="closed sketch"):
+ add_line(proj, 0)
+
+ # Cannot close an already closed sketch
+ with pytest.raises(ValueError, match="already closed"):
+ close_sketch(proj, 0)
+
+ def test_list_and_get_sketch(self):
+ proj = _make_project()
+ create_sketch(proj, name="S1", plane="XY")
+ create_sketch(proj, name="S2", plane="YZ")
+ add_line(proj, 0)
+
+ summaries = list_sketches(proj)
+ assert len(summaries) == 2
+ assert summaries[0]["name"] == "S1"
+ assert summaries[0]["plane"] == "XY"
+ assert summaries[0]["element_count"] == 1
+ assert summaries[1]["name"] == "S2"
+ assert summaries[1]["plane"] == "YZ"
+
+ sk = get_sketch(proj, 1)
+ assert sk["name"] == "S2"
+
+ with pytest.raises(IndexError):
+ get_sketch(proj, 99)
+
+
+# ===========================================================================
+# TestBody
+# ===========================================================================
+
+
+class TestBody:
+ """Tests for the body module."""
+
+ def _project_with_sketch(self):
+ """Return a project with one closed sketch containing a rectangle."""
+ proj = _make_project()
+ create_sketch(proj, name="BaseSketch")
+ add_rectangle(proj, 0, corner=[0, 0], width=10, height=10)
+ close_sketch(proj, 0)
+ return proj
+
+ def test_create_body(self):
+ proj = _make_project()
+ body = create_body(proj, name="MyBody")
+ assert body["name"] == "MyBody"
+ assert body["features"] == []
+ assert body["base_sketch_index"] is None
+ assert len(proj["bodies"]) == 1
+
+ # Auto-naming
+ body2 = create_body(proj)
+ assert body2["name"] == "Body" # first auto "Body" is taken by none; unique check
+
+ def test_pad(self):
+ proj = self._project_with_sketch()
+ create_body(proj, name="PadBody")
+ feature = pad(proj, body_index=0, sketch_index=0, length=15.0, symmetric=True)
+ assert feature["type"] == "pad"
+ assert feature["length"] == 15.0
+ assert feature["symmetric"] is True
+ assert feature["reversed"] is False
+ assert proj["bodies"][0]["base_sketch_index"] == 0
+
+ with pytest.raises(ValueError, match="positive"):
+ pad(proj, body_index=0, sketch_index=0, length=-5.0)
+
+ def test_pocket(self):
+ proj = self._project_with_sketch()
+ create_body(proj, name="PocketBody")
+ # Add a pad first so body has features
+ pad(proj, body_index=0, sketch_index=0, length=20.0)
+
+ # Create a second sketch for the pocket
+ create_sketch(proj, name="PocketSketch")
+ add_rectangle(proj, 1, corner=[2, 2], width=3, height=3)
+ close_sketch(proj, 1)
+
+ feature = pocket(proj, body_index=0, sketch_index=1, length=5.0)
+ assert feature["type"] == "pocket"
+ assert feature["length"] == 5.0
+
+ def test_fillet(self):
+ proj = self._project_with_sketch()
+ create_body(proj)
+ pad(proj, body_index=0, sketch_index=0, length=10.0)
+
+ feat = fillet(proj, body_index=0, radius=2.0, edges="all")
+ assert feat["type"] == "fillet"
+ assert feat["radius"] == 2.0
+ assert feat["edges"] == "all"
+
+ feat2 = fillet(proj, body_index=0, radius=1.0, edges=[0, 1, 2])
+ assert feat2["edges"] == [0, 1, 2]
+
+ with pytest.raises(ValueError, match="positive"):
+ fillet(proj, body_index=0, radius=-1.0)
+
+ def test_chamfer(self):
+ proj = self._project_with_sketch()
+ create_body(proj)
+ pad(proj, body_index=0, sketch_index=0, length=10.0)
+
+ feat = chamfer(proj, body_index=0, size=1.5, edges="all")
+ assert feat["type"] == "chamfer"
+ assert feat["size"] == 1.5
+ assert feat["edges"] == "all"
+
+ with pytest.raises(ValueError, match="positive"):
+ chamfer(proj, body_index=0, size=0.0)
+
+ def test_revolution(self):
+ proj = self._project_with_sketch()
+ create_body(proj)
+ feat = revolution(proj, body_index=0, sketch_index=0, angle=180.0, axis="Y")
+ assert feat["type"] == "revolution"
+ assert feat["angle"] == 180.0
+ assert feat["axis"] == "Y"
+ assert feat["reversed"] is False
+
+ with pytest.raises(ValueError, match="angle must be in"):
+ revolution(proj, body_index=0, sketch_index=0, angle=0.0)
+
+ with pytest.raises(ValueError, match="Invalid revolution axis"):
+ revolution(proj, body_index=0, sketch_index=0, axis="W")
+
+ def test_list_and_get_body(self):
+ proj = self._project_with_sketch()
+ create_body(proj, name="B1")
+ create_body(proj, name="B2")
+ pad(proj, body_index=0, sketch_index=0, length=10.0)
+
+ summaries = list_bodies(proj)
+ assert len(summaries) == 2
+ assert summaries[0]["name"] == "B1"
+ assert summaries[0]["feature_count"] == 1
+ assert summaries[1]["name"] == "B2"
+ assert summaries[1]["feature_count"] == 0
+
+ body = get_body(proj, 0)
+ assert body["name"] == "B1"
+
+ with pytest.raises(IndexError):
+ get_body(proj, 99)
+
+
+# ===========================================================================
+# TestMaterials
+# ===========================================================================
+
+
+class TestMaterials:
+ """Tests for the materials module."""
+
+ def test_create_default(self):
+ proj = _make_project()
+ mat = create_material(proj)
+ assert mat["name"] == "Material"
+ assert mat["preset"] is None
+ assert mat["color"] == [0.8, 0.8, 0.8, 1.0]
+ assert mat["metallic"] == 0.0
+ assert mat["roughness"] == 0.5
+ assert mat["assigned_to"] == []
+ assert len(proj["materials"]) == 1
+
+ def test_create_from_preset(self):
+ proj = _make_project()
+ mat = create_material(proj, preset="steel")
+ assert mat["preset"] == "steel"
+ assert mat["color"] == PRESETS["steel"]["color"]
+ assert mat["metallic"] == PRESETS["steel"]["metallic"]
+ assert mat["roughness"] == PRESETS["steel"]["roughness"]
+ # Name is derived from preset key
+ assert mat["name"] == "Steel"
+
+ with pytest.raises(ValueError, match="Unknown preset"):
+ create_material(proj, preset="unobtanium")
+
+ def test_create_with_color(self):
+ proj = _make_project()
+ mat = create_material(proj, name="Red", color=[1.0, 0.0, 0.0])
+ # 3-component color gets alpha appended
+ assert mat["color"] == [1.0, 0.0, 0.0, 1.0]
+
+ mat2 = create_material(proj, name="SemiRed", color=[1.0, 0.0, 0.0, 0.5])
+ assert mat2["color"] == [1.0, 0.0, 0.0, 0.5]
+
+ def test_assign_to_part(self):
+ proj = _make_project()
+ add_part(proj, "box", name="MyBox")
+ create_material(proj, name="BlueMat", color=[0.0, 0.0, 1.0])
+
+ result = assign_material(proj, material_index=0, part_index=0)
+ assert result["material"] == "BlueMat"
+ assert result["part"] == "MyBox"
+ # Material should track the assignment
+ assert 0 in proj["materials"][0]["assigned_to"]
+ # Part should reference the material
+ assert proj["parts"][0]["material_index"] == 0
+
+ def test_set_property(self):
+ proj = _make_project()
+ create_material(proj, name="Editable")
+
+ set_material_property(proj, 0, "roughness", 0.9)
+ assert proj["materials"][0]["roughness"] == 0.9
+
+ set_material_property(proj, 0, "name", "Renamed")
+ assert proj["materials"][0]["name"] == "Renamed"
+
+ set_material_property(proj, 0, "color", [0.1, 0.2, 0.3, 1.0])
+ assert proj["materials"][0]["color"] == [0.1, 0.2, 0.3, 1.0]
+
+ def test_set_invalid_property(self):
+ proj = _make_project()
+ create_material(proj)
+
+ with pytest.raises(ValueError):
+ set_material_property(proj, 0, "nonexistent_prop", 42)
+
+ with pytest.raises(ValueError, match="maximum"):
+ set_material_property(proj, 0, "metallic", 2.0)
+
+ def test_list_presets(self):
+ presets = list_presets()
+ assert isinstance(presets, list)
+ assert len(presets) == len(PRESETS)
+ names = {p["name"] for p in presets}
+ assert "steel" in names
+ assert "gold" in names
+ for p in presets:
+ assert "name" in p
+ assert "color" in p
+ assert "metallic" in p
+ assert "roughness" in p
+
+
+# ===========================================================================
+# TestSession
+# ===========================================================================
+
+
+class TestSession:
+ """Tests for the session module."""
+
+ def test_status_no_project(self):
+ session = Session()
+ status = session.status()
+ assert status["has_project"] is False
+ assert status["project_path"] is None
+ assert status["modified"] is False
+ assert status["undo_depth"] == 0
+ assert status["redo_depth"] == 0
+
+ with pytest.raises(RuntimeError, match="No project"):
+ session.get_project()
+
+ def test_set_project(self):
+ session = Session()
+ proj = create_document(name="SessionTest")
+ session.set_project(proj, path="/tmp/test.json")
+
+ assert session.get_project()["name"] == "SessionTest"
+ assert session.project_path == "/tmp/test.json"
+ status = session.status()
+ assert status["has_project"] is True
+ assert status["modified"] is False
+
+ def test_snapshot_and_undo(self):
+ session = Session()
+ proj = create_document(name="UndoTest")
+ session.set_project(proj)
+
+ # Take a snapshot, then mutate
+ session.snapshot("before adding box")
+ add_part(session.get_project(), "box", name="TempBox")
+ assert len(session.get_project()["parts"]) == 1
+
+ # Undo should restore the state before the mutation
+ desc = session.undo()
+ assert desc == "before adding box"
+ assert len(session.get_project()["parts"]) == 0
+
+ # Undo with empty stack returns None
+ assert session.undo() is None
+
+ def test_undo_redo_cycle(self):
+ session = Session()
+ proj = create_document(name="RedoTest")
+ session.set_project(proj)
+
+ # Snapshot -> mutate -> undo -> redo
+ session.snapshot("add cylinder")
+ add_part(session.get_project(), "cylinder", name="Cyl")
+ assert len(session.get_project()["parts"]) == 1
+
+ session.undo()
+ assert len(session.get_project()["parts"]) == 0
+ assert session.status()["redo_depth"] == 1
+
+ desc = session.redo()
+ assert desc == "add cylinder"
+ assert len(session.get_project()["parts"]) == 1
+
+ # Redo with empty stack returns None
+ assert session.redo() is None
+
+ def test_save_session(self, tmp_path):
+ session = Session()
+ proj = create_document(name="SaveTest")
+ session.set_project(proj)
+
+ filepath = str(tmp_path / "session_save.json")
+ saved_path = session.save_session(path=filepath)
+ assert os.path.isfile(saved_path)
+ assert session.status()["modified"] is False
+
+ # Verify the file contains valid JSON matching the project
+ with open(saved_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ assert data["name"] == "SaveTest"
+
+ # Save without path after initial save should use stored path
+ session.snapshot("mark modified")
+ saved_again = session.save_session()
+ assert saved_again == saved_path
+
+ def test_list_history(self):
+ session = Session()
+ proj = create_document(name="HistoryTest")
+ session.set_project(proj)
+
+ session.snapshot("step 1")
+ add_part(session.get_project(), "box")
+ session.snapshot("step 2")
+ add_part(session.get_project(), "cylinder")
+ session.snapshot("step 3")
+
+ history = session.list_history()
+ assert len(history) == 3
+ # Newest first
+ assert history[0]["description"] == "step 3"
+ assert history[1]["description"] == "step 2"
+ assert history[2]["description"] == "step 1"
+ # Each entry has required keys
+ for entry in history:
+ assert "index" in entry
+ assert "timestamp" in entry
+ assert "description" in entry
diff --git a/freecad/agent-harness/cli_anything/freecad/tests/test_full_e2e.py b/freecad/agent-harness/cli_anything/freecad/tests/test_full_e2e.py
new file mode 100644
index 000000000..e99111aac
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/tests/test_full_e2e.py
@@ -0,0 +1,659 @@
+"""
+Full end-to-end tests for the cli-anything-freecad harness.
+
+Covers three levels:
+ 1. TestIntermediateFiles -- JSON project + macro generation (no FreeCAD needed)
+ 2. TestFreeCADBackend -- headless FreeCAD export (skipped when not installed)
+ 3. TestCLISubprocess -- subprocess invocations of the CLI entry-point
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import os
+import struct
+import subprocess
+import sys
+from copy import deepcopy
+from typing import List
+
+import pytest
+
+# ---------------------------------------------------------------------------
+# Imports from the harness under test
+# ---------------------------------------------------------------------------
+from cli_anything.freecad.core.document import (
+ create_document,
+ open_document,
+ save_document,
+ get_document_info,
+)
+from cli_anything.freecad.core.parts import (
+ add_part,
+ list_parts,
+ get_part,
+ boolean_op,
+ transform_part,
+)
+from cli_anything.freecad.core.sketch import (
+ create_sketch,
+ add_line,
+ add_circle,
+ add_rectangle,
+ add_arc,
+ add_constraint,
+ close_sketch,
+ list_sketches,
+)
+from cli_anything.freecad.core.body import (
+ create_body,
+ pad,
+ pocket,
+ fillet,
+ chamfer,
+ revolution,
+ list_bodies,
+)
+from cli_anything.freecad.core.materials import (
+ create_material,
+ assign_material,
+ list_materials,
+)
+from cli_anything.freecad.core.export import export_project, get_export_info
+from cli_anything.freecad.utils.freecad_macro_gen import generate_macro
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _has_freecad() -> bool:
+ """Return True if FreeCAD headless backend can be located."""
+ try:
+ from cli_anything.freecad.utils.freecad_backend import find_freecad
+ find_freecad()
+ return True
+ except (RuntimeError, Exception):
+ return False
+
+
+def _resolve_cli(name: str) -> List[str]:
+ """Resolve the CLI entry-point for subprocess tests.
+
+ Prefers an installed command on PATH; falls back to ``python -m``
+ unless ``CLI_ANYTHING_FORCE_INSTALLED=1`` is set.
+ """
+ import shutil
+
+ force = os.environ.get("CLI_ANYTHING_FORCE_INSTALLED", "").strip() == "1"
+ path = shutil.which(name)
+ if path:
+ print(f"[_resolve_cli] Using installed command: {path}")
+ return [path]
+ if force:
+ raise RuntimeError(f"{name} not found in PATH. Install with: pip install -e .")
+ module = (
+ name.replace("cli-anything-", "cli_anything.")
+ .replace("-", "_")
+ + "."
+ + name.split("-")[-1]
+ + "_cli"
+ )
+ print(f"[_resolve_cli] Falling back to: {sys.executable} -m {module}")
+ return [sys.executable, "-m", module]
+
+
+# =========================================================================
+# 1. Intermediate-file tests (no FreeCAD required)
+# =========================================================================
+
+class TestIntermediateFiles:
+ """Verify project creation, manipulation, and macro generation
+ using only the Python API -- no FreeCAD binary needed."""
+
+ def test_full_project_json_structure(self, tmp_path):
+ """Create a complex project and verify the JSON schema."""
+ proj = create_document(name="StructureTest", units="mm")
+
+ # Add varied parts
+ add_part(proj, "box", name="MainBox", params={"length": 30, "width": 20, "height": 15})
+ add_part(proj, "cylinder", name="Shaft", params={"radius": 3, "height": 50})
+ add_part(proj, "sphere", name="Ball", params={"radius": 8})
+
+ # Add a sketch with elements
+ create_sketch(proj, name="BaseSketch", plane="XY")
+ add_rectangle(proj, 0, corner=[0, 0], width=20, height=10)
+
+ # Add a body with a pad
+ create_body(proj, name="MainBody")
+ pad(proj, 0, 0, length=15)
+
+ # Add a material
+ create_material(proj, preset="steel")
+
+ # Save and reload
+ path = str(tmp_path / "structure.json")
+ save_document(proj, path)
+
+ with open(path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+
+ # Top-level keys
+ required_keys = {"version", "name", "units", "parts", "sketches",
+ "bodies", "materials", "metadata"}
+ assert required_keys.issubset(data.keys()), (
+ f"Missing keys: {required_keys - set(data.keys())}"
+ )
+
+ assert data["name"] == "StructureTest"
+ assert data["units"] == "mm"
+ assert data["version"] == "1.0"
+ assert len(data["parts"]) == 3
+ assert len(data["sketches"]) == 1
+ assert len(data["bodies"]) == 1
+ assert len(data["materials"]) == 1
+
+ # Verify part structure
+ box = data["parts"][0]
+ assert box["type"] == "box"
+ assert box["name"] == "MainBox"
+ assert box["params"]["length"] == 30.0
+ assert "placement" in box
+ assert box["placement"]["position"] == [0.0, 0.0, 0.0]
+
+ # Metadata
+ assert "created" in data["metadata"]
+ assert "modified" in data["metadata"]
+ assert "software" in data["metadata"]
+
+ print(f"\n JSON structure validated: {path} ({os.path.getsize(path):,} bytes)")
+
+ def test_multi_part_boolean_workflow(self):
+ """Parts + booleans + materials, verify all state is consistent."""
+ proj = create_document(name="BooleanTest")
+
+ # Add base and tool
+ box = add_part(proj, "box", name="Base", params={"length": 20, "width": 20, "height": 20})
+ cyl = add_part(proj, "cylinder", name="Hole",
+ params={"radius": 5, "height": 30},
+ position=[10, 10, -5])
+
+ assert len(list_parts(proj)) == 2
+ assert box["id"] == 1
+ assert cyl["id"] == 2
+
+ # Boolean cut
+ cut_result = boolean_op(proj, "cut", base_index=0, tool_index=1, name="CutResult")
+ assert cut_result["type"] == "cut"
+ assert cut_result["params"]["base_id"] == box["id"]
+ assert cut_result["params"]["tool_id"] == cyl["id"]
+ assert cut_result["visible"] is True
+
+ # Source parts should now be hidden
+ assert get_part(proj, 0)["visible"] is False
+ assert get_part(proj, 1)["visible"] is False
+
+ # Total parts now 3 (box, cylinder, cut-result)
+ assert len(list_parts(proj)) == 3
+
+ # Create material and assign to cut result
+ mat = create_material(proj, preset="aluminum")
+ assignment = assign_material(proj, material_index=0, part_index=2)
+ assert assignment["material"] == mat["name"]
+ assert assignment["part"] == "CutResult"
+
+ # Verify material assignment on part
+ cut_part = get_part(proj, 2)
+ assert cut_part["material_index"] == 0
+
+ # Verify material tracking
+ materials = list_materials(proj)
+ assert len(materials) == 1
+ assert 2 in materials[0]["assigned_to"]
+
+ print("\n Boolean workflow verified: 2 primitives + cut + material assignment")
+
+ def test_macro_generation_syntax(self, tmp_path):
+ """Generate a macro and verify it is valid Python via ast.parse."""
+ proj = create_document(name="MacroTest")
+ add_part(proj, "box", name="TestBox", params={"length": 15, "width": 10, "height": 5})
+ add_part(proj, "cylinder", name="TestCyl", params={"radius": 3, "height": 20})
+ add_part(proj, "sphere", name="TestSphere", params={"radius": 7})
+
+ # Create body with features
+ create_sketch(proj, plane="XY")
+ add_rectangle(proj, 0, corner=[0, 0], width=10, height=10)
+ create_body(proj, name="ExtrudedBody")
+ pad(proj, 0, 0, length=10)
+
+ output_path = str(tmp_path / "output.step")
+ macro = generate_macro(proj, output_path, export_format="step")
+
+ # Must be non-empty
+ assert len(macro) > 100, f"Macro too short: {len(macro)} chars"
+
+ # Must be valid Python syntax
+ try:
+ ast.parse(macro)
+ except SyntaxError as exc:
+ pytest.fail(f"Generated macro has invalid Python syntax: {exc}\n\n{macro}")
+
+ # Must contain key FreeCAD imports
+ assert "import FreeCAD" in macro
+ assert "import Part" in macro
+ assert "doc.recompute()" in macro
+
+ # Should reference our parts
+ assert "TestBox" in macro
+ assert "TestCyl" in macro
+ assert "TestSphere" in macro
+
+ # Save macro for inspection
+ macro_path = str(tmp_path / "macro.py")
+ with open(macro_path, "w", encoding="utf-8") as f:
+ f.write(macro)
+
+ print(f"\n Macro: {macro_path} ({len(macro):,} chars, {macro.count(chr(10))} lines)")
+
+ def test_save_load_roundtrip(self, tmp_path):
+ """Save a project, reload it, verify contents are identical."""
+ proj = create_document(name="RoundTrip", units="in", profile="imperial")
+
+ add_part(proj, "box", name="BlockA", params={"length": 5, "width": 5, "height": 5})
+ add_part(proj, "cone", name="ConeB",
+ params={"radius1": 3, "radius2": 1, "height": 8})
+
+ create_sketch(proj, name="ProfileSketch", plane="XZ")
+ add_line(proj, 0, start=[0, 0], end=[10, 0])
+ add_circle(proj, 0, center=[5, 5], radius=3)
+
+ create_material(proj, name="CustomMat", color=[0.5, 0.3, 0.1, 1.0],
+ metallic=0.7, roughness=0.4)
+ assign_material(proj, 0, 0)
+
+ path = str(tmp_path / "roundtrip.json")
+ save_document(proj, path)
+
+ # Reload
+ loaded = open_document(path)
+
+ # Compare key fields (metadata.modified will differ slightly, so skip it)
+ assert loaded["name"] == proj["name"]
+ assert loaded["units"] == proj["units"]
+ assert loaded["version"] == proj["version"]
+ assert len(loaded["parts"]) == len(proj["parts"])
+ assert len(loaded["sketches"]) == len(proj["sketches"])
+ assert len(loaded["bodies"]) == len(proj["bodies"])
+ assert len(loaded["materials"]) == len(proj["materials"])
+
+ # Deep-compare parts
+ for i, (orig, reloaded) in enumerate(zip(proj["parts"], loaded["parts"])):
+ assert orig["name"] == reloaded["name"], f"Part {i} name mismatch"
+ assert orig["type"] == reloaded["type"], f"Part {i} type mismatch"
+ assert orig["params"] == reloaded["params"], f"Part {i} params mismatch"
+
+ # Deep-compare sketches
+ for i, (orig, reloaded) in enumerate(zip(proj["sketches"], loaded["sketches"])):
+ assert orig["name"] == reloaded["name"], f"Sketch {i} name mismatch"
+ assert orig["plane"] == reloaded["plane"], f"Sketch {i} plane mismatch"
+ assert len(orig["elements"]) == len(reloaded["elements"])
+
+ print(f"\n Round-trip verified: {path} ({os.path.getsize(path):,} bytes)")
+
+ def test_complex_workflow(self, tmp_path):
+ """Full pipeline: document -> parts -> sketch -> body -> materials."""
+ # 1. Create document
+ proj = create_document(name="ComplexWorkflow", profile="print3d")
+ assert proj["units"] == "mm"
+
+ # 2. Add multiple parts
+ box = add_part(proj, "box", name="Platform",
+ params={"length": 50, "width": 50, "height": 5})
+ cyl = add_part(proj, "cylinder", name="Pillar",
+ params={"radius": 5, "height": 40},
+ position=[25, 25, 5])
+ sphere = add_part(proj, "sphere", name="Top",
+ params={"radius": 8},
+ position=[25, 25, 45])
+
+ # 3. Transform a part
+ transform_part(proj, 2, position=[25, 25, 50], rotation=[0, 0, 45])
+ top = get_part(proj, 2)
+ assert top["placement"]["position"] == [25.0, 25.0, 50.0]
+ assert top["placement"]["rotation"] == [0.0, 0.0, 45.0]
+
+ # 4. Boolean fuse
+ fuse_result = boolean_op(proj, "fuse", 0, 1, name="PlatformPillar")
+ assert fuse_result["type"] == "fuse"
+ assert len(list_parts(proj)) == 4 # box, cyl, sphere, fuse
+
+ # 5. Create sketch with various elements
+ sk = create_sketch(proj, name="DetailSketch", plane="XY", offset=5.0)
+ assert sk["plane"] == "XY"
+ assert sk["offset"] == 5.0
+
+ add_rectangle(proj, 0, corner=[10, 10], width=30, height=30)
+ add_circle(proj, 0, center=[25, 25], radius=10)
+ add_arc(proj, 0, center=[25, 25], radius=15, start_angle=0, end_angle=180)
+
+ # Add a constraint
+ sketch_data = proj["sketches"][0]
+ line_ids = [el["id"] for el in sketch_data["elements"] if el["type"] == "line"]
+ assert len(line_ids) >= 2, "Should have at least 2 lines from rectangle"
+ add_constraint(proj, 0, "horizontal", [line_ids[0]])
+
+ # Close the sketch
+ closed = close_sketch(proj, 0)
+ assert closed["closed"] is True
+
+ sketches = list_sketches(proj)
+ assert len(sketches) == 1
+ assert sketches[0]["closed"] is True
+ assert sketches[0]["element_count"] >= 6 # 4 rect lines + circle + arc
+
+ # 6. Create body with features
+ body = create_body(proj, name="DetailBody")
+ # Create a new open sketch for the body
+ create_sketch(proj, name="BodySketch", plane="XY")
+ add_rectangle(proj, 1, corner=[0, 0], width=20, height=20)
+
+ pad_feat = pad(proj, 0, 1, length=20)
+ assert pad_feat["type"] == "pad"
+ assert pad_feat["length"] == 20.0
+
+ fillet_feat = fillet(proj, 0, radius=2.0)
+ assert fillet_feat["type"] == "fillet"
+ assert fillet_feat["radius"] == 2.0
+
+ bodies = list_bodies(proj)
+ assert len(bodies) == 1
+ assert bodies[0]["feature_count"] == 2
+
+ # 7. Materials
+ steel = create_material(proj, preset="steel")
+ copper = create_material(proj, preset="copper")
+ assert steel["preset"] == "steel"
+ assert copper["preset"] == "copper"
+
+ assign_material(proj, 0, 0) # steel -> Platform(box)
+ assign_material(proj, 1, 1) # copper -> Pillar(cylinder)
+
+ mats = list_materials(proj)
+ assert len(mats) == 2
+ assert 0 in mats[0]["assigned_to"]
+ assert 1 in mats[1]["assigned_to"]
+
+ # 8. Save and verify
+ path = str(tmp_path / "complex.json")
+ saved = save_document(proj, path)
+ assert os.path.isfile(saved)
+
+ info = get_document_info(proj)
+ assert info["parts_count"] == 4
+ assert info["sketches_count"] == 2
+ assert info["bodies_count"] == 1
+ assert info["materials_count"] == 2
+
+ # 9. Generate macro
+ macro = generate_macro(proj, str(tmp_path / "complex.step"))
+ ast.parse(macro) # valid Python
+
+ # 10. Export info
+ exp_info = get_export_info(proj)
+ assert exp_info["part_count"] == 4
+ assert "Platform" in exp_info["part_names"]
+
+ print(f"\n Complex workflow: {path} ({os.path.getsize(path):,} bytes)")
+ print(f" Parts: {info['parts_count']}, Sketches: {info['sketches_count']}, "
+ f"Bodies: {info['bodies_count']}, Materials: {info['materials_count']}")
+
+
+# =========================================================================
+# 2. FreeCAD backend tests (require FreeCAD installed)
+# =========================================================================
+
[email protected](not _has_freecad(), reason="FreeCAD not installed")
+class TestFreeCADBackend:
+ """Tests that require the real FreeCAD headless backend."""
+
+ def test_find_freecad(self):
+ """Verify that find_freecad returns a valid path."""
+ from cli_anything.freecad.utils.freecad_backend import find_freecad
+
+ path = find_freecad()
+ assert os.path.isfile(path), f"FreeCAD not found at: {path}"
+ print(f"\n FreeCAD found: {path}")
+
+ def test_get_version(self):
+ """Verify that get_version returns a version string."""
+ from cli_anything.freecad.utils.freecad_backend import get_version
+
+ version = get_version()
+ assert isinstance(version, str)
+ assert len(version) > 0
+ # Should contain at least one digit and a dot
+ assert any(c.isdigit() for c in version), f"No digits in version: {version}"
+ print(f"\n FreeCAD version: {version}")
+
+ def test_export_box_step(self, tmp_path):
+ """Create a project with a box, export to STEP, validate format."""
+ proj = create_document(name="StepExport")
+ add_part(proj, "box", name="ExportBox",
+ params={"length": 20, "width": 15, "height": 10})
+
+ output = str(tmp_path / "box.step")
+ result = export_project(proj, output, preset="step")
+
+ assert os.path.isfile(output)
+ size = os.path.getsize(output)
+ assert size > 0, "STEP file is empty"
+
+ # Validate STEP header
+ with open(output, "r", encoding="utf-8", errors="ignore") as f:
+ header = f.read(64)
+ assert header.strip().startswith("ISO-10303-21"), (
+ f"Invalid STEP header: {header[:40]!r}"
+ )
+
+ print(f"\n STEP: {output} ({size:,} bytes)")
+
+ def test_export_multi_part_stl(self, tmp_path):
+ """Export multiple parts to STL, validate format."""
+ proj = create_document(name="StlExport")
+ add_part(proj, "box", name="Block",
+ params={"length": 10, "width": 10, "height": 10})
+ add_part(proj, "cylinder", name="Rod",
+ params={"radius": 3, "height": 20},
+ position=[15, 0, 0])
+
+ output = str(tmp_path / "multi.stl")
+ result = export_project(proj, output, preset="stl")
+
+ assert os.path.isfile(output)
+ size = os.path.getsize(output)
+ assert size > 0, "STL file is empty"
+
+ # Validate STL: ASCII starts with "solid", binary has 80-byte header
+ with open(output, "rb") as f:
+ head = f.read(80)
+
+ text_head = head.decode("ascii", errors="ignore").strip().lower()
+ is_ascii = text_head.startswith("solid")
+
+ is_binary = False
+ if not is_ascii:
+ with open(output, "rb") as f:
+ f.seek(80)
+ count_bytes = f.read(4)
+ if len(count_bytes) == 4:
+ tri_count = struct.unpack("<I", count_bytes)[0]
+ is_binary = tri_count > 0
+
+ assert is_ascii or is_binary, "File is neither ASCII nor binary STL"
+
+ fmt = "ASCII" if is_ascii else "binary"
+ print(f"\n STL ({fmt}): {output} ({size:,} bytes)")
+
+ def test_export_fcstd(self, tmp_path):
+ """Export to native FCStd format."""
+ proj = create_document(name="FcstdExport")
+ add_part(proj, "box", name="NativeBox",
+ params={"length": 25, "width": 25, "height": 25})
+
+ output = str(tmp_path / "native.FCStd")
+ result = export_project(proj, output, preset="fcstd")
+
+ assert os.path.isfile(output)
+ size = os.path.getsize(output)
+ assert size > 0, "FCStd file is empty"
+
+ print(f"\n FCStd: {output} ({size:,} bytes)")
+
+
+# =========================================================================
+# 3. CLI subprocess tests
+# =========================================================================
+
+class TestCLISubprocess:
+ """Test the CLI entry-point via subprocess invocations."""
+
+ @pytest.fixture(autouse=True)
+ def _cli_cmd(self):
+ """Resolve the CLI command once for all tests."""
+ self.cli = _resolve_cli("cli-anything-freecad")
+
+ def _run(self, *args: str, **kwargs) -> subprocess.CompletedProcess:
+ """Run a CLI command and return the result."""
+ cmd = self.cli + list(args)
+ return subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ timeout=30,
+ **kwargs,
+ )
+
+ def test_help(self):
+ """--help returns exit code 0 and prints usage."""
+ result = self._run("--help")
+ assert result.returncode == 0, (
+ f"--help failed (rc={result.returncode}): {result.stderr}"
+ )
+ assert "freecad" in result.stdout.lower() or "usage" in result.stdout.lower(), (
+ f"Unexpected help output: {result.stdout[:200]}"
+ )
+ print(f"\n --help: rc={result.returncode}, {len(result.stdout)} chars")
+
+ def test_document_new_json(self, tmp_path):
+ """'--json document new -o <path>' creates valid JSON output."""
+ out_file = str(tmp_path / "new_doc.json")
+ result = self._run("--json", "document", "new",
+ "--name", "TestDoc", "-o", out_file)
+ assert result.returncode == 0, (
+ f"document new failed (rc={result.returncode}): {result.stderr}"
+ )
+
+ # stdout should be valid JSON
+ data = json.loads(result.stdout)
+ assert data["name"] == "TestDoc"
+ assert "version" in data
+
+ # File should exist
+ assert os.path.isfile(out_file)
+ print(f"\n document new: {out_file} ({os.path.getsize(out_file):,} bytes)")
+
+ def test_part_add_json(self, tmp_path):
+ """Create doc then add a part, verify JSON output."""
+ proj_file = str(tmp_path / "part_add.json")
+
+ # Create document
+ r1 = self._run("--json", "document", "new",
+ "--name", "PartTest", "-o", proj_file)
+ assert r1.returncode == 0, f"doc new failed: {r1.stderr}"
+
+ # Add a box part
+ r2 = self._run("--json", "-p", proj_file, "part", "add", "box",
+ "--name", "MyBox", "-P", "length=30")
+ assert r2.returncode == 0, f"part add failed: {r2.stderr}"
+
+ data = json.loads(r2.stdout)
+ assert data["type"] == "box"
+ assert data["name"] == "MyBox"
+ assert data["params"]["length"] == 30.0
+
+ print(f"\n part add: {data['name']} (type={data['type']})")
+
+ def test_part_list_json(self, tmp_path):
+ """Create doc, add parts, list them, verify count."""
+ proj_file = str(tmp_path / "part_list.json")
+
+ # Create document
+ self._run("--json", "document", "new",
+ "--name", "ListTest", "-o", proj_file)
+
+ # Add two parts
+ self._run("--json", "-p", proj_file, "part", "add", "box", "--name", "A")
+ self._run("--json", "-p", proj_file, "part", "add", "cylinder", "--name", "B")
+
+ # List parts
+ r = self._run("--json", "-p", proj_file, "part", "list")
+ assert r.returncode == 0, f"part list failed: {r.stderr}"
+
+ parts = json.loads(r.stdout)
+ assert isinstance(parts, list)
+ assert len(parts) == 2
+ names = {p["name"] for p in parts}
+ assert "A" in names
+ assert "B" in names
+
+ print(f"\n part list: {len(parts)} parts ({names})")
+
+ def test_full_workflow_subprocess(self, tmp_path):
+ """Full subprocess workflow: create -> box -> cylinder -> boolean cut -> list."""
+ proj_file = str(tmp_path / "workflow.json")
+
+ # 1. Create document
+ r = self._run("--json", "document", "new",
+ "--name", "WorkflowTest", "-o", proj_file)
+ assert r.returncode == 0, f"doc new: {r.stderr}"
+
+ # 2. Add box
+ r = self._run("--json", "-p", proj_file, "part", "add", "box",
+ "--name", "Base", "-P", "length=20", "-P", "width=20",
+ "-P", "height=20")
+ assert r.returncode == 0, f"add box: {r.stderr}"
+ box = json.loads(r.stdout)
+ assert box["name"] == "Base"
+
+ # 3. Add cylinder
+ r = self._run("--json", "-p", proj_file, "part", "add", "cylinder",
+ "--name", "Hole", "-P", "radius=5", "-P", "height=30",
+ "-pos", "10,10,-5")
+ assert r.returncode == 0, f"add cylinder: {r.stderr}"
+ cyl = json.loads(r.stdout)
+ assert cyl["name"] == "Hole"
+
+ # 4. Boolean cut
+ r = self._run("--json", "-p", proj_file,
+ "part", "boolean", "cut", "0", "1")
+ assert r.returncode == 0, f"boolean cut: {r.stderr}"
+ cut = json.loads(r.stdout)
+ assert cut["type"] == "cut"
+
+ # 5. List parts -- should have 3 (box, cylinder, cut-result)
+ r = self._run("--json", "-p", proj_file, "part", "list")
+ assert r.returncode == 0, f"part list: {r.stderr}"
+ parts = json.loads(r.stdout)
+ assert len(parts) == 3, f"Expected 3 parts, got {len(parts)}: {parts}"
+
+ # Verify visibility: first two hidden, cut result visible
+ visible_count = sum(1 for p in parts if p.get("visible", True))
+ assert visible_count >= 1, "At least the cut result should be visible"
+
+ type_names = [p["type"] for p in parts]
+ assert "cut" in type_names, f"No 'cut' part found in types: {type_names}"
+
+ print(f"\n Workflow complete: {len(parts)} parts")
+ for p in parts:
+ print(f" {p['name']}: type={p['type']}, visible={p.get('visible', '?')}")
diff --git a/freecad/agent-harness/cli_anything/freecad/utils/__init__.py b/freecad/agent-harness/cli_anything/freecad/utils/__init__.py
new file mode 100644
index 000000000..a9f558fb7
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/utils/__init__.py
@@ -0,0 +1 @@
+"""Utility modules for FreeCAD CLI harness."""
diff --git a/freecad/agent-harness/cli_anything/freecad/utils/freecad_backend.py b/freecad/agent-harness/cli_anything/freecad/utils/freecad_backend.py
new file mode 100644
index 000000000..e3c1deab7
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/utils/freecad_backend.py
@@ -0,0 +1,320 @@
+"""
+Backend module that wraps the real FreeCAD headless CLI (FreeCADCmd).
+
+Provides functions to locate the FreeCAD console executable and invoke it
+in headless mode for macro execution, export, and version queries.
+"""
+
+from __future__ import annotations
+
+import glob
+import os
+import platform
+import shutil
+import subprocess
+import tempfile
+import textwrap
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+
+# ---------------------------------------------------------------------------
+# FreeCAD discovery
+# ---------------------------------------------------------------------------
+
+_INSTALL_INSTRUCTIONS = textwrap.dedent("""\
+ FreeCAD console executable (FreeCADCmd) not found.
+
+ Install FreeCAD and make sure FreeCADCmd is on your PATH, or install
+ it to one of the standard locations:
+
+ Windows:
+ - C:\\Program Files\\FreeCAD*\\bin\\FreeCADCmd.exe
+ Download from https://www.freecad.org/downloads.php
+
+ macOS:
+ brew install --cask freecad
+ (or download from https://www.freecad.org/downloads.php)
+
+ Linux (Debian / Ubuntu):
+ sudo apt install freecad
+ Linux (Flatpak):
+ flatpak install flathub org.freecadweb.FreeCAD
+ Linux (Snap):
+ sudo snap install freecad
+ Linux (conda-forge):
+ conda install -c conda-forge freecad
+""")
+
+# Executable names to search for, in priority order
+_FREECAD_NAMES = ["freecadcmd", "FreeCADCmd", "freecad", "FreeCAD"]
+
+
+def find_freecad() -> str:
+ """Locate the FreeCAD console executable on the system.
+
+ Search order:
+ 1. ``FREECAD_PATH`` environment variable (explicit override).
+ 2. Known executable names on ``PATH`` (via :func:`shutil.which`).
+ 3. Common Windows install directories (glob-matched).
+ 4. Common macOS application bundle path.
+ 5. Common Linux paths.
+
+ Returns
+ -------
+ str
+ Absolute path to the FreeCAD console executable.
+
+ Raises
+ ------
+ RuntimeError
+ If FreeCAD cannot be found, with installation instructions in
+ the message.
+ """
+ # 1. Environment variable override
+ env_path = os.environ.get("FREECAD_PATH")
+ if env_path and os.path.isfile(env_path):
+ return os.path.abspath(env_path)
+
+ # 2. On PATH
+ for name in _FREECAD_NAMES:
+ which = shutil.which(name)
+ if which:
+ return os.path.abspath(which)
+
+ # 3. Windows common locations
+ if platform.system() == "Windows":
+ win_patterns = [
+ "C:/Program Files/FreeCAD*/bin/FreeCADCmd.exe",
+ "C:/Program Files (x86)/FreeCAD*/bin/FreeCADCmd.exe",
+ "C:/Program Files/FreeCAD*/bin/FreeCAD.exe",
+ "C:/Program Files (x86)/FreeCAD*/bin/FreeCAD.exe",
+ ]
+ for pattern in win_patterns:
+ matches = sorted(glob.glob(pattern), reverse=True)
+ if matches:
+ return os.path.abspath(matches[0])
+
+ # 4. macOS application bundle
+ if platform.system() == "Darwin":
+ mac_paths = [
+ "/Applications/FreeCAD.app/Contents/MacOS/FreeCADCmd",
+ "/Applications/FreeCAD.app/Contents/MacOS/FreeCAD",
+ ]
+ for mac_path in mac_paths:
+ if os.path.isfile(mac_path):
+ return mac_path
+
+ # 5. Common Linux paths
+ if platform.system() == "Linux":
+ linux_paths = [
+ "/usr/bin/freecadcmd",
+ "/usr/bin/freecad",
+ "/usr/local/bin/freecadcmd",
+ "/usr/local/bin/freecad",
+ "/snap/bin/freecad",
+ ]
+ for linux_path in linux_paths:
+ if os.path.isfile(linux_path):
+ return linux_path
+
+ raise RuntimeError(_INSTALL_INSTRUCTIONS)
+
+
+# ---------------------------------------------------------------------------
+# Internal helpers
+# ---------------------------------------------------------------------------
+
+
+def _run(
+ args: list[str],
+ *,
+ timeout: int = 120,
+ check: bool = False,
+) -> Dict[str, Any]:
+ """Run a subprocess and return a normalised result dict."""
+ try:
+ proc = subprocess.run(
+ args,
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ )
+ result: Dict[str, Any] = {
+ "ok": proc.returncode == 0,
+ "returncode": proc.returncode,
+ "stdout": proc.stdout.strip(),
+ "stderr": proc.stderr.strip(),
+ "command": " ".join(args),
+ }
+ if check and proc.returncode != 0:
+ raise subprocess.CalledProcessError(
+ proc.returncode, args, proc.stdout, proc.stderr,
+ )
+ return result
+ except FileNotFoundError as exc:
+ return {
+ "ok": False,
+ "returncode": -1,
+ "stdout": "",
+ "stderr": str(exc),
+ "command": " ".join(args),
+ }
+ except subprocess.TimeoutExpired:
+ return {
+ "ok": False,
+ "returncode": -1,
+ "stdout": "",
+ "stderr": f"FreeCAD process timed out after {timeout}s",
+ "command": " ".join(args),
+ }
+
+
+def _write_temp_script(content: str) -> str:
+ """Write *content* to a temporary ``.py`` file and return its path."""
+ fd, path = tempfile.mkstemp(suffix=".py", prefix="freecad_macro_")
+ try:
+ os.write(fd, content.encode("utf-8"))
+ finally:
+ os.close(fd)
+ return path
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def get_version() -> str:
+ """Return the FreeCAD version string (e.g. ``"0.21.2"``).
+
+ Runs ``FreeCADCmd --version`` and parses the output.
+
+ Returns
+ -------
+ str
+ Version string extracted from FreeCAD's output.
+
+ Raises
+ ------
+ RuntimeError
+ If the version cannot be determined.
+ """
+ freecad = find_freecad()
+ result = _run([freecad, "--version"])
+ if result["ok"] and result["stdout"]:
+ # Output is typically "FreeCAD 0.21.2" or similar
+ for line in result["stdout"].splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ # Try to extract version number
+ parts = line.split()
+ for part in parts:
+ # Look for something that looks like a version number
+ if any(c.isdigit() for c in part) and "." in part:
+ return part.strip(",").strip()
+ # Fallback: return the whole first line
+ return line
+ if result["stderr"]:
+ raise RuntimeError(f"Failed to get FreeCAD version: {result['stderr']}")
+ raise RuntimeError("Failed to get FreeCAD version (no output)")
+
+
+def run_macro(
+ script_path: str,
+ timeout: int = 120,
+) -> Dict[str, Any]:
+ """Execute a FreeCAD Python macro script headlessly.
+
+ Parameters
+ ----------
+ script_path : str
+ Path to the ``.py`` macro file to execute.
+ timeout : int
+ Maximum seconds to wait for execution.
+
+ Returns
+ -------
+ dict
+ ``{"command": str, "returncode": int, "stdout": str, "stderr": str}``
+ """
+ freecad = find_freecad()
+ script_path = str(Path(script_path).resolve())
+
+ result = _run([freecad, script_path], timeout=timeout)
+
+ return {
+ "command": result["command"],
+ "returncode": result["returncode"],
+ "stdout": result["stdout"],
+ "stderr": result["stderr"],
+ }
+
+
+def export_headless(
+ macro_content: str,
+ output_path: str,
+ timeout: int = 120,
+) -> Dict[str, Any]:
+ """Write a macro to a temp file, execute it, and verify the output.
+
+ This is a convenience wrapper that combines writing a macro script
+ to a temporary file, executing it via :func:`run_macro`, and verifying
+ that the expected output file was created.
+
+ Parameters
+ ----------
+ macro_content : str
+ Complete Python macro script content.
+ output_path : str
+ Expected output file path (the macro should write to this path).
+ timeout : int
+ Maximum seconds to wait for execution.
+
+ Returns
+ -------
+ dict
+ ``{"output": str, "format": str, "method": "freecad-headless",
+ "file_size": int}``
+
+ Raises
+ ------
+ RuntimeError
+ If the macro execution fails (non-zero exit code) or the output
+ file is not created.
+ """
+ output_path = os.path.abspath(output_path)
+ os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
+
+ script_path = _write_temp_script(macro_content)
+ try:
+ result = run_macro(script_path, timeout=timeout)
+ finally:
+ # Best-effort cleanup of the temp script
+ try:
+ os.unlink(script_path)
+ except OSError:
+ pass
+
+ if result["returncode"] != 0:
+ raise RuntimeError(
+ f"FreeCAD macro execution failed (exit code {result['returncode']}). "
+ f"stderr: {result['stderr']}"
+ )
+
+ if not os.path.isfile(output_path):
+ raise RuntimeError(
+ f"FreeCAD macro completed but output file was not created: "
+ f"{output_path}. stdout: {result['stdout']}"
+ )
+
+ ext = Path(output_path).suffix.lstrip(".")
+ file_size = os.path.getsize(output_path)
+
+ return {
+ "output": output_path,
+ "format": ext,
+ "method": "freecad-headless",
+ "file_size": file_size,
+ }
diff --git a/freecad/agent-harness/cli_anything/freecad/utils/freecad_macro_gen.py b/freecad/agent-harness/cli_anything/freecad/utils/freecad_macro_gen.py
new file mode 100644
index 000000000..a606d6a68
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/utils/freecad_macro_gen.py
@@ -0,0 +1,392 @@
+"""
+Macro generation module for the FreeCAD CLI harness.
+
+Generates complete FreeCAD Python macro scripts from JSON project state.
+The generated scripts can be executed headlessly via ``FreeCADCmd`` to
+create geometry and export to various CAD/mesh formats.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any, Dict, List, Optional
+
+
+# ---------------------------------------------------------------------------
+# Safe name helper
+# ---------------------------------------------------------------------------
+
+
+def _safe_name(name: str) -> str:
+ """Convert a user-supplied name into a valid FreeCAD object label.
+
+ Replaces non-alphanumeric characters with underscores and ensures the
+ name does not start with a digit.
+ """
+ safe = re.sub(r"[^A-Za-z0-9_]", "_", name)
+ if safe and safe[0].isdigit():
+ safe = f"_{safe}"
+ return safe or "Unnamed"
+
+
+# ---------------------------------------------------------------------------
+# Internal generators
+# ---------------------------------------------------------------------------
+
+
+def _gen_header() -> List[str]:
+ """Generate import statements and document creation."""
+ return [
+ "# Auto-generated FreeCAD macro by CLI-Anything FreeCAD harness",
+ "import sys",
+ "import os",
+ "import FreeCAD",
+ "import Part",
+ "",
+ "doc = FreeCAD.newDocument('ExportDoc')",
+ "",
+ ]
+
+
+def _gen_parts(project: dict) -> List[str]:
+ """Generate Part primitives (Box, Cylinder, Sphere, Cone, Torus)."""
+ lines: List[str] = []
+ parts = project.get("parts", [])
+
+ for part in parts:
+ part_type = part.get("type", "box").lower()
+ name = _safe_name(part.get("name", f"Part_{part_type}"))
+ props = part.get("params", part.get("properties", {}))
+
+ if part_type == "box":
+ length = props.get("length", props.get("Length", 10.0))
+ width = props.get("width", props.get("Width", 10.0))
+ height = props.get("height", props.get("Height", 10.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Box', '{name}')")
+ lines.append(f"obj_{name}.Length = {length}")
+ lines.append(f"obj_{name}.Width = {width}")
+ lines.append(f"obj_{name}.Height = {height}")
+
+ elif part_type == "cylinder":
+ radius = props.get("radius", props.get("Radius", 5.0))
+ height = props.get("height", props.get("Height", 10.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Cylinder', '{name}')")
+ lines.append(f"obj_{name}.Radius = {radius}")
+ lines.append(f"obj_{name}.Height = {height}")
+
+ elif part_type == "sphere":
+ radius = props.get("radius", props.get("Radius", 5.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Sphere', '{name}')")
+ lines.append(f"obj_{name}.Radius = {radius}")
+
+ elif part_type == "cone":
+ radius1 = props.get("radius1", props.get("Radius1", 5.0))
+ radius2 = props.get("radius2", props.get("Radius2", 0.0))
+ height = props.get("height", props.get("Height", 10.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Cone', '{name}')")
+ lines.append(f"obj_{name}.Radius1 = {radius1}")
+ lines.append(f"obj_{name}.Radius2 = {radius2}")
+ lines.append(f"obj_{name}.Height = {height}")
+
+ elif part_type == "torus":
+ radius1 = props.get("radius1", props.get("Radius1", 10.0))
+ radius2 = props.get("radius2", props.get("Radius2", 2.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Torus', '{name}')")
+ lines.append(f"obj_{name}.Radius1 = {radius1}")
+ lines.append(f"obj_{name}.Radius2 = {radius2}")
+
+ else:
+ lines.append(f"# WARNING: Unknown part type '{part_type}' for '{name}'")
+
+ lines.append("")
+
+ return lines
+
+
+def _gen_boolean_ops(project: dict) -> List[str]:
+ """Generate boolean operations (Cut, Fuse, Common)."""
+ lines: List[str] = []
+ boolean_ops = project.get("boolean_ops", [])
+
+ # Map user-friendly names to FreeCAD object types
+ op_type_map = {
+ "cut": "Part::Cut",
+ "subtract": "Part::Cut",
+ "fuse": "Part::Fuse",
+ "union": "Part::Fuse",
+ "common": "Part::Common",
+ "intersect": "Part::Common",
+ "intersection": "Part::Common",
+ }
+
+ for op in boolean_ops:
+ op_type = op.get("type", "fuse").lower()
+ name = _safe_name(op.get("name", f"BoolOp_{op_type}"))
+ base_name = _safe_name(op.get("base", ""))
+ tool_name = _safe_name(op.get("tool", ""))
+ fc_type = op_type_map.get(op_type, "Part::Fuse")
+
+ lines.append(f"obj_{name} = doc.addObject('{fc_type}', '{name}')")
+ lines.append(f"obj_{name}.Base = doc.getObject('{base_name}')")
+ lines.append(f"obj_{name}.Tool = doc.getObject('{tool_name}')")
+ lines.append("")
+
+ return lines
+
+
+def _gen_bodies(project: dict) -> List[str]:
+ """Generate PartDesign bodies with features (Pad, Pocket, etc.)."""
+ lines: List[str] = []
+ bodies = project.get("bodies", [])
+
+ if not bodies:
+ return lines
+
+ lines.append("import PartDesign")
+ lines.append("")
+
+ for body in bodies:
+ body_name = _safe_name(body.get("name", "Body"))
+ lines.append(
+ f"body_{body_name} = doc.addObject('PartDesign::Body', '{body_name}')"
+ )
+
+ features = body.get("features", [])
+ for feat in features:
+ feat_type = feat.get("type", "pad").lower()
+ feat_name = _safe_name(feat.get("name", f"Feature_{feat_type}"))
+ feat_props = feat.get("properties", {})
+
+ if feat_type == "pad":
+ length = feat_props.get("length", feat_props.get("Length", 10.0))
+ lines.append(
+ f"feat_{feat_name} = body_{body_name}.newObject("
+ f"'PartDesign::Pad', '{feat_name}')"
+ )
+ lines.append(f"feat_{feat_name}.Length = {length}")
+
+ elif feat_type == "pocket":
+ length = feat_props.get("length", feat_props.get("Length", 5.0))
+ lines.append(
+ f"feat_{feat_name} = body_{body_name}.newObject("
+ f"'PartDesign::Pocket', '{feat_name}')"
+ )
+ lines.append(f"feat_{feat_name}.Length = {length}")
+
+ elif feat_type == "revolution":
+ angle = feat_props.get("angle", feat_props.get("Angle", 360.0))
+ lines.append(
+ f"feat_{feat_name} = body_{body_name}.newObject("
+ f"'PartDesign::Revolution', '{feat_name}')"
+ )
+ lines.append(f"feat_{feat_name}.Angle = {angle}")
+
+ elif feat_type == "chamfer":
+ size = feat_props.get("size", feat_props.get("Size", 1.0))
+ lines.append(
+ f"feat_{feat_name} = body_{body_name}.newObject("
+ f"'PartDesign::Chamfer', '{feat_name}')"
+ )
+ lines.append(f"feat_{feat_name}.Size = {size}")
+
+ elif feat_type == "fillet":
+ radius = feat_props.get("radius", feat_props.get("Radius", 1.0))
+ lines.append(
+ f"feat_{feat_name} = body_{body_name}.newObject("
+ f"'PartDesign::Fillet', '{feat_name}')"
+ )
+ lines.append(f"feat_{feat_name}.Radius = {radius}")
+
+ else:
+ lines.append(
+ f"# WARNING: Unknown feature type '{feat_type}' "
+ f"for '{feat_name}'"
+ )
+
+ lines.append("")
+
+ return lines
+
+
+def _gen_placements(project: dict) -> List[str]:
+ """Generate placement (position and rotation) commands for parts."""
+ lines: List[str] = []
+ parts = project.get("parts", [])
+
+ for part in parts:
+ name = _safe_name(part.get("name", ""))
+ placement = part.get("placement", {})
+
+ if not placement:
+ continue
+
+ position = placement.get("position", {})
+ rotation = placement.get("rotation", {})
+
+ # Support both list [x, y, z] and dict {"x": ..., "y": ..., "z": ...}
+ if isinstance(position, (list, tuple)):
+ x = position[0] if len(position) > 0 else 0.0
+ y = position[1] if len(position) > 1 else 0.0
+ z = position[2] if len(position) > 2 else 0.0
+ else:
+ x = position.get("x", 0.0)
+ y = position.get("y", 0.0)
+ z = position.get("z", 0.0)
+
+ # Rotation: support list [rx, ry, rz] (Euler) or dict formats
+ if isinstance(rotation, (list, tuple)):
+ rx = rotation[0] if len(rotation) > 0 else 0.0
+ ry = rotation[1] if len(rotation) > 1 else 0.0
+ rz = rotation[2] if len(rotation) > 2 else 0.0
+ if rx != 0.0 or ry != 0.0 or rz != 0.0:
+ lines.append(
+ f"obj_{name}.Placement = FreeCAD.Placement("
+ f"FreeCAD.Vector({x}, {y}, {z}), "
+ f"FreeCAD.Rotation({rz}, {ry}, {rx}))"
+ )
+ else:
+ lines.append(
+ f"obj_{name}.Placement.Base = FreeCAD.Vector({x}, {y}, {z})"
+ )
+ elif "axis" in rotation and "angle" in rotation:
+ axis = rotation["axis"]
+ ax = axis.get("x", 0.0)
+ ay = axis.get("y", 0.0)
+ az = axis.get("z", 1.0)
+ angle = rotation["angle"]
+ lines.append(
+ f"obj_{name}.Placement = FreeCAD.Placement("
+ f"FreeCAD.Vector({x}, {y}, {z}), "
+ f"FreeCAD.Rotation(FreeCAD.Vector({ax}, {ay}, {az}), {angle}))"
+ )
+ elif any(k in rotation for k in ("yaw", "pitch", "roll")):
+ yaw = rotation.get("yaw", 0.0)
+ pitch = rotation.get("pitch", 0.0)
+ roll = rotation.get("roll", 0.0)
+ lines.append(
+ f"obj_{name}.Placement = FreeCAD.Placement("
+ f"FreeCAD.Vector({x}, {y}, {z}), "
+ f"FreeCAD.Rotation({yaw}, {pitch}, {roll}))"
+ )
+ else:
+ # Position only, no rotation
+ lines.append(
+ f"obj_{name}.Placement.Base = FreeCAD.Vector({x}, {y}, {z})"
+ )
+
+ lines.append("")
+
+ return lines
+
+
+def _gen_export(
+ project: dict,
+ output_path: str,
+ export_format: str,
+) -> List[str]:
+ """Generate export commands for the specified format.
+
+ Supported formats:
+ - ``step`` / ``iges``: via ``Part.export()``
+ - ``stl``: via ``Mesh.export()``
+ - ``obj``: via ``Mesh.export()``
+ - ``brep``: via ``Part.export()``
+ - ``fcstd``: via ``doc.saveAs()``
+ """
+ lines: List[str] = []
+
+ # Escape backslashes for Windows paths in the generated Python script
+ safe_path = output_path.replace("\\", "/")
+
+ # Recompute the document before exporting
+ lines.append("doc.recompute()")
+ lines.append("")
+
+ # Collect all visible shape objects for export
+ lines.append("# Collect all shape objects for export")
+ lines.append("export_objects = []")
+ lines.append("for obj in doc.Objects:")
+ lines.append(" if hasattr(obj, 'Shape') and obj.Shape.isValid():")
+ lines.append(" export_objects.append(obj)")
+ lines.append("")
+
+ fmt = export_format.lower()
+
+ if fmt in ("step", "iges", "brep"):
+ lines.append(f"Part.export(export_objects, '{safe_path}')")
+
+ elif fmt in ("stl", "obj"):
+ lines.append("import Mesh")
+ lines.append(f"Mesh.export(export_objects, '{safe_path}')")
+
+ elif fmt == "fcstd":
+ lines.append(f"doc.saveAs('{safe_path}')")
+
+ else:
+ # Fallback to Part.export for unknown formats
+ lines.append(f"# Unknown format '{fmt}', attempting Part.export")
+ lines.append(f"Part.export(export_objects, '{safe_path}')")
+
+ lines.append("")
+ lines.append("print('Export complete:', os.path.abspath('{safe_path}'))")
+ lines.append("")
+
+ return lines
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def generate_macro(
+ project: dict,
+ output_path: str,
+ export_format: str = "step",
+) -> str:
+ """Generate a complete FreeCAD Python macro script from project state.
+
+ The generated script, when executed by ``FreeCADCmd``, will:
+ 1. Create a new FreeCAD document.
+ 2. Add all parts/primitives defined in the project.
+ 3. Apply boolean operations.
+ 4. Create PartDesign bodies with features.
+ 5. Set placements (positions and rotations).
+ 6. Export to the requested format.
+
+ Parameters
+ ----------
+ project : dict
+ Project JSON state. Expected top-level keys:
+
+ - ``parts``: list of part definitions (type, name, properties,
+ placement).
+ - ``boolean_ops``: list of boolean operation definitions.
+ - ``bodies``: list of PartDesign body definitions with features.
+
+ output_path : str
+ Destination file path for the export.
+ export_format : str
+ Target format: ``"step"``, ``"iges"``, ``"stl"``, ``"obj"``,
+ ``"brep"``, or ``"fcstd"``.
+
+ Returns
+ -------
+ str
+ Complete Python macro script ready for execution by FreeCADCmd.
+ """
+ sections: List[List[str]] = [
+ _gen_header(),
+ _gen_parts(project),
+ _gen_boolean_ops(project),
+ _gen_bodies(project),
+ _gen_placements(project),
+ _gen_export(project, output_path, export_format),
+ ]
+
+ # Flatten all sections and join with newlines
+ all_lines: List[str] = []
+ for section in sections:
+ all_lines.extend(section)
+
+ return "\n".join(all_lines)
diff --git a/freecad/agent-harness/cli_anything/freecad/utils/repl_skin.py b/freecad/agent-harness/cli_anything/freecad/utils/repl_skin.py
new file mode 100644
index 000000000..962c97bb8
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/utils/repl_skin.py
@@ -0,0 +1,523 @@
+"""cli-anything REPL Skin — Unified terminal interface for all CLI harnesses.
+
+Copy this file into your CLI package at:
+ cli_anything/<software>/utils/repl_skin.py
+
+Usage:
+ from cli_anything.<software>.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("shotcut", version="1.0.0")
+ skin.print_banner() # auto-detects skills/SKILL.md inside the package
+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)
+ skin.success("Project saved")
+ skin.error("File not found")
+ skin.warning("Unsaved changes")
+ skin.info("Processing 24 clips...")
+ skin.status("Track 1", "3 clips, 00:02:30")
+ skin.table(headers, rows)
+ skin.print_goodbye()
+"""
+
+import os
+import sys
+
+# ── ANSI color codes (no external deps for core styling) ──────────────
+
+_RESET = "\033[0m"
+_BOLD = "\033[1m"
+_DIM = "\033[2m"
+_ITALIC = "\033[3m"
+_UNDERLINE = "\033[4m"
+
+# Brand colors
+_CYAN = "\033[38;5;80m" # cli-anything brand cyan
+_CYAN_BG = "\033[48;5;80m"
+_WHITE = "\033[97m"
+_GRAY = "\033[38;5;245m"
+_DARK_GRAY = "\033[38;5;240m"
+_LIGHT_GRAY = "\033[38;5;250m"
+
+# Software accent colors — each software gets a unique accent
+_ACCENT_COLORS = {
+ "gimp": "\033[38;5;214m", # warm orange
+ "blender": "\033[38;5;208m", # deep orange
+ "inkscape": "\033[38;5;39m", # bright blue
+ "audacity": "\033[38;5;33m", # navy blue
+ "libreoffice": "\033[38;5;40m", # green
+ "obs_studio": "\033[38;5;55m", # purple
+ "kdenlive": "\033[38;5;69m", # slate blue
+ "shotcut": "\033[38;5;35m", # teal green
+ "freecad": "\033[38;5;196m", # FreeCAD red
+}
+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue
+
+# Status colors
+_GREEN = "\033[38;5;78m"
+_YELLOW = "\033[38;5;220m"
+_RED = "\033[38;5;196m"
+_BLUE = "\033[38;5;75m"
+_MAGENTA = "\033[38;5;176m"
+
+# ── Brand icon ────────────────────────────────────────────────────────
+
+# The cli-anything icon: a small colored diamond/chevron mark
+_ICON = f"{_CYAN}{_BOLD}◆{_RESET}"
+_ICON_SMALL = f"{_CYAN}▸{_RESET}"
+
+# ── Box drawing characters ────────────────────────────────────────────
+
+_H_LINE = "─"
+_V_LINE = "│"
+_TL = "╭"
+_TR = "╮"
+_BL = "╰"
+_BR = "╯"
+_T_DOWN = "┬"
+_T_UP = "┴"
+_T_RIGHT = "├"
+_T_LEFT = "┤"
+_CROSS = "┼"
+
+
+def _strip_ansi(text: str) -> str:
+ """Remove ANSI escape codes for length calculation."""
+ import re
+ return re.sub(r"\033\[[^m]*m", "", text)
+
+
+def _visible_len(text: str) -> int:
+ """Get visible length of text (excluding ANSI codes)."""
+ return len(_strip_ansi(text))
+
+
+class ReplSkin:
+ """Unified REPL skin for cli-anything CLIs.
+
+ Provides consistent branding, prompts, and message formatting
+ across all CLI harnesses built with the cli-anything methodology.
+ """
+
+ def __init__(self, software: str, version: str = "1.0.0",
+ history_file: str | None = None, skill_path: str | None = None):
+ """Initialize the REPL skin.
+
+ Args:
+ software: Software name (e.g., "gimp", "shotcut", "blender").
+ version: CLI version string.
+ history_file: Path for persistent command history.
+ Defaults to ~/.cli-anything-<software>/history
+ skill_path: Path to the SKILL.md file for agent discovery.
+ Auto-detected from the package's skills/ directory if not provided.
+ Displayed in banner for AI agents to know where to read skill info.
+ """
+ self.software = software.lower().replace("-", "_")
+ self.display_name = software.replace("_", " ").title()
+ self.version = version
+
+ # Auto-detect skill path from package layout:
+ # cli_anything/<software>/utils/repl_skin.py (this file)
+ # cli_anything/<software>/skills/SKILL.md (target)
+ if skill_path is None:
+ from pathlib import Path
+ _auto = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"
+ if _auto.is_file():
+ skill_path = str(_auto)
+ self.skill_path = skill_path
+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)
+
+ # History file
+ if history_file is None:
+ from pathlib import Path
+ hist_dir = Path.home() / f".cli-anything-{self.software}"
+ hist_dir.mkdir(parents=True, exist_ok=True)
+ self.history_file = str(hist_dir / "history")
+ else:
+ self.history_file = history_file
+
+ # Detect terminal capabilities
+ self._color = self._detect_color_support()
+
+ def _detect_color_support(self) -> bool:
+ """Check if terminal supports color."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):
+ return False
+ if not hasattr(sys.stdout, "isatty"):
+ return False
+ return sys.stdout.isatty()
+
+ def _c(self, code: str, text: str) -> str:
+ """Apply color code if colors are supported."""
+ if not self._color:
+ return text
+ return f"{code}{text}{_RESET}"
+
+ # ── Banner ────────────────────────────────────────────────────────
+
+ def print_banner(self):
+ """Print the startup banner with branding."""
+ inner = 54
+
+ def _box_line(content: str) -> str:
+ """Wrap content in box drawing, padding to inner width."""
+ pad = inner - _visible_len(content)
+ vl = self._c(_DARK_GRAY, _V_LINE)
+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"
+
+ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")
+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")
+
+ # Title: ◆ cli-anything · Shotcut
+ icon = self._c(_CYAN + _BOLD, "◆")
+ brand = self._c(_CYAN + _BOLD, "cli-anything")
+ dot = self._c(_DARK_GRAY, "·")
+ name = self._c(self.accent + _BOLD, self.display_name)
+ title = f" {icon} {brand} {dot} {name}"
+
+ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"
+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"
+ empty = ""
+
+ # Skill path for agent discovery
+ skill_line = None
+ if self.skill_path:
+ skill_icon = self._c(_MAGENTA, "◇")
+ skill_label = self._c(_DARK_GRAY, " Skill:")
+ skill_path_display = self._c(_LIGHT_GRAY, self.skill_path)
+ skill_line = f" {skill_icon} {skill_label} {skill_path_display}"
+
+ print(top)
+ print(_box_line(title))
+ print(_box_line(ver))
+ if skill_line:
+ print(_box_line(skill_line))
+ print(_box_line(empty))
+ print(_box_line(tip))
+ print(bot)
+ print()
+
+ # ── Prompt ────────────────────────────────────────────────────────
+
+ def prompt(self, project_name: str = "", modified: bool = False,
+ context: str = "") -> str:
+ """Build a styled prompt string for prompt_toolkit or input().
+
+ Args:
+ project_name: Current project name (empty if none open).
+ modified: Whether the project has unsaved changes.
+ context: Optional extra context to show in prompt.
+
+ Returns:
+ Formatted prompt string.
+ """
+ parts = []
+
+ # Icon
+ if self._color:
+ parts.append(f"{_CYAN}◆{_RESET} ")
+ else:
+ parts.append("> ")
+
+ # Software name
+ parts.append(self._c(self.accent + _BOLD, self.software))
+
+ # Project context
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ parts.append(f" {self._c(_DARK_GRAY, '[')}")
+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))
+ parts.append(self._c(_DARK_GRAY, ']'))
+
+ parts.append(self._c(_GRAY, " ❯ "))
+
+ return "".join(parts)
+
+ def prompt_tokens(self, project_name: str = "", modified: bool = False,
+ context: str = ""):
+ """Build prompt_toolkit formatted text tokens for the prompt.
+
+ Use with prompt_toolkit's FormattedText for proper ANSI handling.
+
+ Returns:
+ list of (style, text) tuples for prompt_toolkit.
+ """
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+ tokens = []
+
+ tokens.append(("class:icon", "◆ "))
+ tokens.append(("class:software", self.software))
+
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ tokens.append(("class:bracket", " ["))
+ tokens.append(("class:context", f"{ctx}{mod}"))
+ tokens.append(("class:bracket", "]"))
+
+ tokens.append(("class:arrow", " ❯ "))
+
+ return tokens
+
+ def get_prompt_style(self):
+ """Get a prompt_toolkit Style object matching the skin.
+
+ Returns:
+ prompt_toolkit.styles.Style
+ """
+ try:
+ from prompt_toolkit.styles import Style
+ except ImportError:
+ return None
+
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+
+ return Style.from_dict({
+ "icon": "#5fdfdf bold", # cyan brand color
+ "software": f"{accent_hex} bold",
+ "bracket": "#585858",
+ "context": "#bcbcbc",
+ "arrow": "#808080",
+ # Completion menu
+ "completion-menu.completion": "bg:#303030 #bcbcbc",
+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",
+ "completion-menu.meta.completion": "bg:#303030 #808080",
+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",
+ # Auto-suggest
+ "auto-suggest": "#585858",
+ # Bottom toolbar
+ "bottom-toolbar": "bg:#1c1c1c #808080",
+ "bottom-toolbar.text": "#808080",
+ })
+
+ # ── Messages ──────────────────────────────────────────────────────
+
+ def success(self, message: str):
+ """Print a success message with green checkmark."""
+ icon = self._c(_GREEN + _BOLD, "✓")
+ print(f" {icon} {self._c(_GREEN, message)}")
+
+ def error(self, message: str):
+ """Print an error message with red cross."""
+ icon = self._c(_RED + _BOLD, "✗")
+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)
+
+ def warning(self, message: str):
+ """Print a warning message with yellow triangle."""
+ icon = self._c(_YELLOW + _BOLD, "⚠")
+ print(f" {icon} {self._c(_YELLOW, message)}")
+
+ def info(self, message: str):
+ """Print an info message with blue dot."""
+ icon = self._c(_BLUE, "●")
+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")
+
+ def hint(self, message: str):
+ """Print a subtle hint message."""
+ print(f" {self._c(_DARK_GRAY, message)}")
+
+ def section(self, title: str):
+ """Print a section header."""
+ print()
+ print(f" {self._c(self.accent + _BOLD, title)}")
+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")
+
+ # ── Status display ────────────────────────────────────────────────
+
+ def status(self, label: str, value: str):
+ """Print a key-value status line."""
+ lbl = self._c(_GRAY, f" {label}:")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def status_block(self, items: dict[str, str], title: str = ""):
+ """Print a block of status key-value pairs.
+
+ Args:
+ items: Dict of label -> value pairs.
+ title: Optional title for the block.
+ """
+ if title:
+ self.section(title)
+
+ max_key = max(len(k) for k in items) if items else 0
+ for label, value in items.items():
+ lbl = self._c(_GRAY, f" {label:<{max_key}}")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def progress(self, current: int, total: int, label: str = ""):
+ """Print a simple progress indicator.
+
+ Args:
+ current: Current step number.
+ total: Total number of steps.
+ label: Optional label for the progress.
+ """
+ pct = int(current / total * 100) if total > 0 else 0
+ bar_width = 20
+ filled = int(bar_width * current / total) if total > 0 else 0
+ bar = "█" * filled + "░" * (bar_width - filled)
+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"
+ if label:
+ text += f" {self._c(_LIGHT_GRAY, label)}"
+ print(text)
+
+ # ── Table display ─────────────────────────────────────────────────
+
+ def table(self, headers: list[str], rows: list[list[str]],
+ max_col_width: int = 40):
+ """Print a formatted table with box-drawing characters.
+
+ Args:
+ headers: Column header strings.
+ rows: List of rows, each a list of cell strings.
+ max_col_width: Maximum column width before truncation.
+ """
+ if not headers:
+ return
+
+ # Calculate column widths
+ col_widths = [min(len(h), max_col_width) for h in headers]
+ for row in rows:
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = min(
+ max(col_widths[i], len(str(cell))), max_col_width
+ )
+
+ def pad(text: str, width: int) -> str:
+ t = str(text)[:width]
+ return t + " " * (width - len(t))
+
+ # Header
+ header_cells = [
+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))
+ for i, h in enumerate(headers)
+ ]
+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ header_line = f" {sep.join(header_cells)}"
+ print(header_line)
+
+ # Separator
+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]
+ sep_line = self._c(_DARK_GRAY, f" {'───'.join([_H_LINE * w for w in col_widths])}")
+ print(sep_line)
+
+ # Rows
+ for row in rows:
+ cells = []
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))
+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ print(f" {row_sep.join(cells)}")
+
+ # ── Help display ──────────────────────────────────────────────────
+
+ def help(self, commands: dict[str, str]):
+ """Print a formatted help listing.
+
+ Args:
+ commands: Dict of command -> description pairs.
+ """
+ self.section("Commands")
+ max_cmd = max(len(c) for c in commands) if commands else 0
+ for cmd, desc in commands.items():
+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")
+ desc_styled = self._c(_GRAY, f" {desc}")
+ print(f"{cmd_styled}{desc_styled}")
+ print()
+
+ # ── Goodbye ───────────────────────────────────────────────────────
+
+ def print_goodbye(self):
+ """Print a styled goodbye message."""
+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")
+
+ # ── Prompt toolkit session factory ────────────────────────────────
+
+ def create_prompt_session(self):
+ """Create a prompt_toolkit PromptSession with skin styling.
+
+ Returns:
+ A configured PromptSession, or None if prompt_toolkit unavailable.
+ """
+ try:
+ from prompt_toolkit import PromptSession
+ from prompt_toolkit.history import FileHistory
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
+ from prompt_toolkit.formatted_text import FormattedText
+
+ style = self.get_prompt_style()
+
+ session = PromptSession(
+ history=FileHistory(self.history_file),
+ auto_suggest=AutoSuggestFromHistory(),
+ style=style,
+ enable_history_search=True,
+ )
+ return session
+ except ImportError:
+ return None
+
+ def get_input(self, pt_session, project_name: str = "",
+ modified: bool = False, context: str = "") -> str:
+ """Get input from user using prompt_toolkit or fallback.
+
+ Args:
+ pt_session: A prompt_toolkit PromptSession (or None).
+ project_name: Current project name.
+ modified: Whether project has unsaved changes.
+ context: Optional context string.
+
+ Returns:
+ User input string (stripped).
+ """
+ if pt_session is not None:
+ from prompt_toolkit.formatted_text import FormattedText
+ tokens = self.prompt_tokens(project_name, modified, context)
+ return pt_session.prompt(FormattedText(tokens)).strip()
+ else:
+ raw_prompt = self.prompt(project_name, modified, context)
+ return input(raw_prompt).strip()
+
+ # ── Toolbar builder ───────────────────────────────────────────────
+
+ def bottom_toolbar(self, items: dict[str, str]):
+ """Create a bottom toolbar callback for prompt_toolkit.
+
+ Args:
+ items: Dict of label -> value pairs to show in toolbar.
+
+ Returns:
+ A callable that returns FormattedText for the toolbar.
+ """
+ def toolbar():
+ from prompt_toolkit.formatted_text import FormattedText
+ parts = []
+ for i, (k, v) in enumerate(items.items()):
+ if i > 0:
+ parts.append(("class:bottom-toolbar.text", " │ "))
+ parts.append(("class:bottom-toolbar.text", f" {k}: "))
+ parts.append(("class:bottom-toolbar", v))
+ return FormattedText(parts)
+ return toolbar
+
+
+# ── ANSI 256-color to hex mapping (for prompt_toolkit styles) ─────────
+
+_ANSI_256_TO_HEX = {
+ "\033[38;5;33m": "#0087ff", # audacity navy blue
+ "\033[38;5;35m": "#00af5f", # shotcut teal
+ "\033[38;5;39m": "#00afff", # inkscape bright blue
+ "\033[38;5;40m": "#00d700", # libreoffice green
+ "\033[38;5;55m": "#5f00af", # obs purple
+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue
+ "\033[38;5;75m": "#5fafff", # default sky blue
+ "\033[38;5;80m": "#5fd7d7", # brand cyan
+ "\033[38;5;208m": "#ff8700", # blender deep orange
+ "\033[38;5;196m": "#ff0000", # freecad red
+ "\033[38;5;214m": "#ffaf00", # gimp warm orange
+}
diff --git a/freecad/agent-harness/setup.py b/freecad/agent-harness/setup.py
new file mode 100644
index 000000000..ee21a1999
--- /dev/null
+++ b/freecad/agent-harness/setup.py
@@ -0,0 +1,33 @@
+"""Setup for cli-anything-freecad — CLI harness for FreeCAD."""
+
+from setuptools import setup, find_namespace_packages
+
+setup(
+ name="cli-anything-freecad",
+ version="1.0.0",
+ description="CLI harness for FreeCAD parametric 3D CAD modeler",
+ long_description=open("cli_anything/freecad/README.md").read(),
+ long_description_content_type="text/markdown",
+ author="CLI-Anything Contributors",
+ license="Apache-2.0",
+ packages=find_namespace_packages(include=["cli_anything.*"]),
+ python_requires=">=3.10",
+ install_requires=[
+ "click>=8.0.0",
+ "prompt-toolkit>=3.0.0",
+ ],
+ entry_points={
+ "console_scripts": [
+ "cli-anything-freecad=cli_anything.freecad.freecad_cli:main",
+ ],
+ },
+ package_data={
+ "cli_anything.freecad": ["skills/*.md"],
+ },
+ classifiers=[
+ "Programming Language :: Python :: 3",
+ "License :: OSI Approved :: Apache Software License",
+ "Operating System :: OS Independent",
+ "Topic :: Scientific/Engineering :: Visualization",
+ ],
+)
diff --git a/registry.json b/registry.json
index 7d63fefbc..b6f091737 100644
--- a/registry.json
+++ b/registry.json
@@ -312,6 +312,20 @@
"category": "design",
"contributor": "zhangxilong-43",
"contributor_url": "https://github.com/zhangxilong-43"
+ },
+ {
+ "name": "freecad",
+ "display_name": "FreeCAD",
+ "version": "1.0.0",
+ "description": "Parametric 3D CAD modeling via FreeCAD CLI (258 commands: Part, Sketcher, PartDesign, Assembly, Mesh, TechDraw, Draft, FEM, CAM, and more)",
+ "requires": "FreeCAD >= 0.21 (freecad.org)",
+ "homepage": "https://www.freecad.org",
+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=freecad/agent-harness",
+ "entry_point": "cli-anything-freecad",
+ "skill_md": "freecad/agent-harness/cli_anything/freecad/skills/SKILL.md",
+ "category": "3d",
+ "contributor": "AlexGabbia",
+ "contributor_url": "https://github.com/AlexGabbia"
}
]
}