openforma 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. forma_cli/__init__.py +5 -0
  2. forma_cli/app.py +1139 -0
  3. forma_cli/config.py +112 -0
  4. forma_cli/credentials.py +141 -0
  5. forma_cli/local.py +562 -0
  6. forma_cli/metadata_api.py +138 -0
  7. forma_cli/project_artifacts.py +182 -0
  8. forma_cli/sdk.py +571 -0
  9. forma_core/__init__.py +9 -0
  10. forma_core/__main__.py +4 -0
  11. forma_core/_version.py +3 -0
  12. forma_core/agents/__init__.py +50 -0
  13. forma_core/agents/clarification.py +194 -0
  14. forma_core/agents/component_reconciliation.py +99 -0
  15. forma_core/agents/context_gathering.py +115 -0
  16. forma_core/agents/continuous.py +537 -0
  17. forma_core/agents/contracts.py +247 -0
  18. forma_core/agents/firecrawl_mcp.py +484 -0
  19. forma_core/agents/lattice.py +239 -0
  20. forma_core/agents/orchestrator.py +3724 -0
  21. forma_core/agents/pipeline.py +843 -0
  22. forma_core/agents/project_correction.py +83 -0
  23. forma_core/agents/prompt_compaction.py +428 -0
  24. forma_core/agents/system_architecture.py +345 -0
  25. forma_core/agents/video_correction.py +119 -0
  26. forma_core/agents/web_research_workflow.py +1256 -0
  27. forma_core/agents/workflows.py +176 -0
  28. forma_core/assets/__init__.py +1 -0
  29. forma_core/assets/models.py +156 -0
  30. forma_core/assets/project.py +17 -0
  31. forma_core/assets/repository.py +48 -0
  32. forma_core/assets/service.py +142 -0
  33. forma_core/assets/validation.py +35 -0
  34. forma_core/benchmarks/__init__.py +5 -0
  35. forma_core/benchmarks/ir_triad_v1.py +477 -0
  36. forma_core/biology/__init__.py +28 -0
  37. forma_core/biology/benchmark.py +80 -0
  38. forma_core/biology/ewart_liverchip.py +279 -0
  39. forma_core/biology/ir.py +25 -0
  40. forma_core/biology/liverbench.py +416 -0
  41. forma_core/biology/liverbench_assay.py +251 -0
  42. forma_core/biology/liverbench_baselines.py +133 -0
  43. forma_core/biology/liverbench_independent.py +229 -0
  44. forma_core/biology/liverchip_demo.py +154 -0
  45. forma_core/biology/liverchip_evidence.py +149 -0
  46. forma_core/biology/models.py +247 -0
  47. forma_core/biology/validation.py +72 -0
  48. forma_core/cad_migrations/__init__.py +6 -0
  49. forma_core/cad_migrations/cli.py +101 -0
  50. forma_core/cad_migrations/emitters.py +227 -0
  51. forma_core/cad_migrations/models.py +121 -0
  52. forma_core/cad_migrations/planner.py +68 -0
  53. forma_core/chemistry/__init__.py +5 -0
  54. forma_core/chemistry/models.py +215 -0
  55. forma_core/chemistry/stoichiometry.py +272 -0
  56. forma_core/chemistry/validation.py +179 -0
  57. forma_core/cli/__init__.py +1 -0
  58. forma_core/cli/__main__.py +4 -0
  59. forma_core/cli/main.py +370 -0
  60. forma_core/config/__init__.py +28 -0
  61. forma_core/config/compatibility.py +282 -0
  62. forma_core/config/contract.py +184 -0
  63. forma_core/config/environment.py +129 -0
  64. forma_core/config/parti.py +34 -0
  65. forma_core/config/runtime.py +303 -0
  66. forma_core/control/__init__.py +10 -0
  67. forma_core/control/actions.py +136 -0
  68. forma_core/control/adapters.py +36 -0
  69. forma_core/control/cli.py +49 -0
  70. forma_core/control/client.py +124 -0
  71. forma_core/control/models.py +168 -0
  72. forma_core/control/opencode_worker.py +80 -0
  73. forma_core/control/package.py +318 -0
  74. forma_core/control/rover_scene/__init__.py +1 -0
  75. forma_core/control/rover_scene/__main__.py +34 -0
  76. forma_core/control/rover_scene/assets.py +65 -0
  77. forma_core/control/rover_scene/fleet.py +214 -0
  78. forma_core/control/rover_scene/host.py +258 -0
  79. forma_core/control/rover_scene/kinematics.py +35 -0
  80. forma_core/control/rover_scene/machine.py +347 -0
  81. forma_core/control/rover_scene/robot.py +166 -0
  82. forma_core/control/rover_scene/scene.py +206 -0
  83. forma_core/control/rover_scene/view.py +80 -0
  84. forma_core/control/rover_scene/web/index.html +25 -0
  85. forma_core/control/rover_scene/web/viewer.js +148 -0
  86. forma_core/control/runtime.py +356 -0
  87. forma_core/control/so101.py +235 -0
  88. forma_core/control/tasks.py +287 -0
  89. forma_core/database.py +2362 -0
  90. forma_core/debug.py +314 -0
  91. forma_core/domains/__init__.py +7 -0
  92. forma_core/domains/agents.py +85 -0
  93. forma_core/domains/base.py +69 -0
  94. forma_core/domains/benchmark.py +87 -0
  95. forma_core/domains/cli.py +48 -0
  96. forma_core/domains/compatibility.py +234 -0
  97. forma_core/domains/composition.py +372 -0
  98. forma_core/domains/diagnostics.py +15 -0
  99. forma_core/domains/generation.py +479 -0
  100. forma_core/domains/interaction.py +301 -0
  101. forma_core/domains/planning.py +140 -0
  102. forma_core/domains/providers.py +214 -0
  103. forma_core/domains/registry.py +267 -0
  104. forma_core/domains/selection.py +75 -0
  105. forma_core/domains/storage.py +60 -0
  106. forma_core/domains/tools.py +180 -0
  107. forma_core/electronics/__init__.py +1 -0
  108. forma_core/electronics/models.py +84 -0
  109. forma_core/electronics/primitives.py +43 -0
  110. forma_core/electronics/rules.py +340 -0
  111. forma_core/external_sources.py +497 -0
  112. forma_core/fabricator/__init__.py +33 -0
  113. forma_core/fabricator/__main__.py +7 -0
  114. forma_core/fabricator/main.py +578 -0
  115. forma_core/firmware/__init__.py +60 -0
  116. forma_core/firmware/drivers.py +140 -0
  117. forma_core/firmware/examples.py +503 -0
  118. forma_core/firmware/generate.py +520 -0
  119. forma_core/firmware/models.py +34 -0
  120. forma_core/firmware/sil/__init__.py +5 -0
  121. forma_core/firmware/sil/adapter.py +71 -0
  122. forma_core/firmware/sil/build.py +49 -0
  123. forma_core/firmware/sil/native/CMakeLists.txt +9 -0
  124. forma_core/firmware/sil/native/bridge.cpp +112 -0
  125. forma_core/firmware/sil/native/controller.cpp +123 -0
  126. forma_core/firmware/sil/native/controller.h +49 -0
  127. forma_core/firmware/sil/simulator.py +139 -0
  128. forma_core/firmware/targets.py +111 -0
  129. forma_core/firmware/validation.py +130 -0
  130. forma_core/fluidics/__init__.py +6 -0
  131. forma_core/fluidics/benchmark.py +217 -0
  132. forma_core/fluidics/calculations.py +79 -0
  133. forma_core/fluidics/examples.py +54 -0
  134. forma_core/fluidics/ir.py +25 -0
  135. forma_core/fluidics/models.py +132 -0
  136. forma_core/fluidics/topology.py +47 -0
  137. forma_core/fluidics/validation.py +134 -0
  138. forma_core/generation.py +32 -0
  139. forma_core/geometry_bindings/__init__.py +20 -0
  140. forma_core/geometry_bindings/cad_adapter.py +80 -0
  141. forma_core/geometry_bindings/models.py +163 -0
  142. forma_core/geometry_bindings/resolution.py +340 -0
  143. forma_core/geometry_bindings/tools.py +125 -0
  144. forma_core/image_providers.py +3049 -0
  145. forma_core/images.py +3 -0
  146. forma_core/integrations/__init__.py +1 -0
  147. forma_core/integrations/huggingface/__init__.py +29 -0
  148. forma_core/integrations/huggingface/huggingface_artifacts.py +272 -0
  149. forma_core/jobs/__init__.py +1 -0
  150. forma_core/jobs/context.py +277 -0
  151. forma_core/jobs/continuous.py +719 -0
  152. forma_core/jobs/metrics.py +124 -0
  153. forma_core/jobs/migrations.py +161 -0
  154. forma_core/jobs/persistence.py +28 -0
  155. forma_core/jobs/repositories.py +422 -0
  156. forma_core/jobs/schema.py +28 -0
  157. forma_core/jobs/source_usage.py +230 -0
  158. forma_core/jobs/store.py +476 -0
  159. forma_core/llm.py +3 -0
  160. forma_core/llm_providers.py +2682 -0
  161. forma_core/logs.py +107 -0
  162. forma_core/mechanics/__init__.py +1 -0
  163. forma_core/mechanics/gear_benchmark.py +85 -0
  164. forma_core/mechanics/mechanism_benchmarks.py +345 -0
  165. forma_core/mechanics/models.py +72 -0
  166. forma_core/mechanics/primitives.py +109 -0
  167. forma_core/mechanics/solid_cad.py +83 -0
  168. forma_core/observability.py +237 -0
  169. forma_core/openai_streams.py +780 -0
  170. forma_core/opencode/__init__.py +25 -0
  171. forma_core/opencode/architecture.py +82 -0
  172. forma_core/opencode/capabilities.py +130 -0
  173. forma_core/opencode/models.py +419 -0
  174. forma_core/opencode/persistence.py +62 -0
  175. forma_core/opencode/public_events.py +91 -0
  176. forma_core/opencode/schema.py +28 -0
  177. forma_core/opencode/store.py +874 -0
  178. forma_core/persistence/__init__.py +16 -0
  179. forma_core/persistence/base.py +38 -0
  180. forma_core/persistence/images.py +598 -0
  181. forma_core/persistence/migrations.py +200 -0
  182. forma_core/persistence/models.py +439 -0
  183. forma_core/persistence/project_artifacts.py +341 -0
  184. forma_core/persistence/project_reconciliation.py +1094 -0
  185. forma_core/persistence/providers/__init__.py +4 -0
  186. forma_core/persistence/providers/sqlite.py +114 -0
  187. forma_core/persistence/providers/supabase.py +31 -0
  188. forma_core/persistence/repositories/__init__.py +9 -0
  189. forma_core/persistence/repositories/base.py +335 -0
  190. forma_core/persistence/repositories/sqlite.py +1571 -0
  191. forma_core/persistence/repositories/supabase.py +1576 -0
  192. forma_core/persistence/schema.py +176 -0
  193. forma_core/processes/__init__.py +5 -0
  194. forma_core/processes/models.py +338 -0
  195. forma_core/processes/validation.py +141 -0
  196. forma_core/project_list_cache.py +316 -0
  197. forma_core/prompt_continuity.py +387 -0
  198. forma_core/providers/__init__.py +39 -0
  199. forma_core/providers/base.py +28 -0
  200. forma_core/providers/models.py +138 -0
  201. forma_core/providers/openai.py +92 -0
  202. forma_core/providers/openai_compatible.py +190 -0
  203. forma_core/providers/registry.py +68 -0
  204. forma_core/providers/registry_utils.py +46 -0
  205. forma_core/py.typed +1 -0
  206. forma_core/runtime.py +3 -0
  207. forma_core/selectors.py +36 -0
  208. forma_core/signups/__init__.py +5 -0
  209. forma_core/signups/models.py +49 -0
  210. forma_core/terminal/__init__.py +1 -0
  211. forma_core/terminal/dashboard.py +475 -0
  212. forma_core/terminal/images.py +156 -0
  213. forma_core/thermal/__init__.py +5 -0
  214. forma_core/thermal/models.py +361 -0
  215. forma_core/thermal/validation.py +175 -0
  216. forma_core/user_integrations.py +2069 -0
  217. forma_core/utils.py +291 -0
  218. forma_core/validation.py +83 -0
  219. forma_core/vertex_auth.py +92 -0
  220. forma_core/video_prompts.py +193 -0
  221. forma_core/video_review.py +1006 -0
  222. forma_core/wiring.py +356 -0
  223. forma_core/workers/__init__.py +120 -0
  224. forma_core/workers/contracts.py +183 -0
  225. forma_core/workers/generation.py +753 -0
  226. forma_core/workers/orchestration.py +805 -0
  227. forma_core/workers/registry.py +222 -0
  228. forma_core/workers/reverse_engineering.py +272 -0
  229. forma_core/workers/validation.py +291 -0
  230. forma_core/workspaces/__init__.py +5 -0
  231. forma_core/workspaces/chats/__init__.py +11 -0
  232. forma_core/workspaces/chats/models.py +48 -0
  233. forma_core/workspaces/context/__init__.py +15 -0
  234. forma_core/workspaces/context/agent.py +260 -0
  235. forma_core/workspaces/context/models.py +117 -0
  236. forma_core/workspaces/context/pdf.py +418 -0
  237. forma_core/workspaces/design_briefs/__init__.py +25 -0
  238. forma_core/workspaces/design_briefs/models.py +85 -0
  239. forma_core/workspaces/design_briefs/references.py +56 -0
  240. forma_core/workspaces/models.py +41 -0
  241. forma_core/workspaces/projects/__init__.py +88 -0
  242. forma_core/workspaces/projects/cad_generation.py +1016 -0
  243. forma_core/workspaces/projects/context_governance.py +365 -0
  244. forma_core/workspaces/projects/design_lifecycle.py +668 -0
  245. forma_core/workspaces/projects/fabrication/__init__.py +54 -0
  246. forma_core/workspaces/projects/fabrication/demo_printers.py +236 -0
  247. forma_core/workspaces/projects/fabrication/models.py +120 -0
  248. forma_core/workspaces/projects/fabrication/printer_config.py +205 -0
  249. forma_core/workspaces/projects/fabrication/slicers/__init__.py +7 -0
  250. forma_core/workspaces/projects/fabrication/slicers/base.py +25 -0
  251. forma_core/workspaces/projects/fabrication/slicers/cura.py +125 -0
  252. forma_core/workspaces/projects/fabrication/slicers/orca.py +208 -0
  253. forma_core/workspaces/projects/fabrication/slicing.py +202 -0
  254. forma_core/workspaces/projects/fabrication/validation.py +103 -0
  255. forma_core/workspaces/projects/gear_benchmark.py +6 -0
  256. forma_core/workspaces/projects/generation_mode.py +70 -0
  257. forma_core/workspaces/projects/identity.py +28 -0
  258. forma_core/workspaces/projects/iteration.py +680 -0
  259. forma_core/workspaces/projects/manifest.py +362 -0
  260. forma_core/workspaces/projects/mechanism_benchmarks.py +12 -0
  261. forma_core/workspaces/projects/models.py +913 -0
  262. forma_core/workspaces/projects/objects.py +731 -0
  263. forma_core/workspaces/projects/outcomes.py +47 -0
  264. forma_core/workspaces/projects/output.py +735 -0
  265. forma_core/workspaces/projects/resolver.py +397 -0
  266. forma_core/workspaces/projects/solid_cad.py +8 -0
  267. forma_core/workspaces/projects/state.py +622 -0
  268. forma_core/workspaces/readiness/__init__.py +28 -0
  269. forma_core/workspaces/readiness/evaluator.py +103 -0
  270. forma_core/workspaces/readiness/models.py +97 -0
  271. forma_core/workspaces/readiness/service.py +225 -0
  272. forma_core/workspaces/reverse_engineering/__init__.py +37 -0
  273. forma_core/workspaces/reverse_engineering/analyzer.py +246 -0
  274. forma_core/workspaces/reverse_engineering/models.py +128 -0
  275. forma_core/workspaces/validation/__init__.py +37 -0
  276. forma_core/workspaces/validation/evaluator.py +327 -0
  277. forma_core/workspaces/validation/models.py +146 -0
  278. forma_core/workspaces/validation/service.py +212 -0
  279. forma_core/workspaces/workflow/__init__.py +29 -0
  280. forma_core/workspaces/workflow/guard.py +33 -0
  281. forma_core/workspaces/workflow/models.py +77 -0
  282. forma_core/workspaces/workflow/service.py +287 -0
  283. openforma-0.4.0.dist-info/METADATA +247 -0
  284. openforma-0.4.0.dist-info/RECORD +288 -0
  285. openforma-0.4.0.dist-info/WHEEL +5 -0
  286. openforma-0.4.0.dist-info/entry_points.txt +4 -0
  287. openforma-0.4.0.dist-info/licenses/LICENSE +373 -0
  288. openforma-0.4.0.dist-info/top_level.txt +2 -0
forma_cli/local.py ADDED
@@ -0,0 +1,562 @@
1
+ """Local project discovery and offline operations for ``forma-oss``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ from pathlib import Path
8
+ import shutil
9
+ import struct
10
+ from typing import Any
11
+ from uuid import uuid4
12
+
13
+ from forma_core.config import config
14
+ from forma_core.workspaces.projects.manifest import (
15
+ PROJECT_MANIFEST_FORMAT,
16
+ ProjectArtifactReference,
17
+ ProjectManifest,
18
+ load_project_manifest,
19
+ write_project_manifest,
20
+ )
21
+
22
+ from forma_cli.config import load_linkage, save_linkage
23
+ from forma_cli.credentials import CredentialStore, CredentialStoreError
24
+
25
+
26
+ PROJECT_FILENAME = "forma-project.json"
27
+ STRICT_GENERATION_ENVIRONMENT = {
28
+ "FORMA_DISABLE_GENERATION_FALLBACK": "true",
29
+ "FORMA_STRICT_GENERATION": "true",
30
+ "LLM_DISABLE_FALLBACK": "true",
31
+ }
32
+ SIMULATION_ENVIRONMENT = {
33
+ "FORMA_DEV_MODE": "true",
34
+ "FORMA_DISABLE_GENERATION_FALLBACK": "false",
35
+ "FORMA_STRICT_GENERATION": "false",
36
+ "LLM_DISABLE_FALLBACK": "false",
37
+ }
38
+ ASSEMBLY_STEP_FILENAMES = ("assembly.step", "assembled.step")
39
+ LOCAL_OWNER_USER_ID = "local-dev-user"
40
+ LOCAL_PROVIDER_ENVIRONMENT = {
41
+ "anthropic": "ANTHROPIC_API_KEY",
42
+ "baseten": "BASETEN_API_KEY",
43
+ "cloudflare": "CLOUDFLARE_API_TOKEN",
44
+ "firecrawl": "FIRECRAWL_API_KEY",
45
+ "gemini": "GEMINI_API_KEY",
46
+ "gmi": "GMI_API_KEY",
47
+ "huggingface": "HF_TOKEN",
48
+ "nvidia": "NVIDIA_API_KEY",
49
+ "openai": "OPENAI_API_KEY",
50
+ "runpod": "RUNPOD_API_KEY",
51
+ "tavily": "TAVILY_API_KEY",
52
+ "together": "TOGETHER_API_KEY",
53
+ "xai": "XAI_API_KEY",
54
+ }
55
+
56
+
57
+ class LocalProjectError(RuntimeError):
58
+ """Raised when a local project cannot be read or safely updated."""
59
+
60
+
61
+ def project_root(path: str | Path | None = None) -> Path:
62
+ start = Path(path or Path.cwd()).expanduser().resolve()
63
+ if start.is_file():
64
+ start = start.parent
65
+ for candidate in (start, *start.parents):
66
+ if (candidate / PROJECT_FILENAME).is_file():
67
+ return candidate
68
+ raise LocalProjectError(f"Could not find {PROJECT_FILENAME} from {start}.")
69
+
70
+
71
+ def project_path(path: str | Path | None = None) -> Path:
72
+ return project_root(path) / PROJECT_FILENAME
73
+
74
+
75
+ def read_project(path: str | Path | None = None) -> ProjectManifest:
76
+ return load_project_manifest(project_path(path))
77
+
78
+
79
+ def init_project(path: str | Path | None = None, *, title: str = "") -> ProjectManifest:
80
+ root = Path(path or Path.cwd()).expanduser().resolve()
81
+ root.mkdir(parents=True, exist_ok=True)
82
+ target = root / PROJECT_FILENAME
83
+ if target.exists():
84
+ raise LocalProjectError(f"A Forma project already exists at {target}.")
85
+ manifest = ProjectManifest(
86
+ format=PROJECT_MANIFEST_FORMAT,
87
+ version=1,
88
+ project_id=str(uuid4()),
89
+ title=title.strip(),
90
+ project_ir={},
91
+ )
92
+ write_project_manifest(target, manifest)
93
+ save_linkage(root, {"version": 1, "project_id": manifest.project_id})
94
+ return manifest
95
+
96
+
97
+ def _local_provider_environment(store: CredentialStore) -> dict[str, str]:
98
+ values: dict[str, str] = {}
99
+ for provider, environment_name in LOCAL_PROVIDER_ENVIRONMENT.items():
100
+ try:
101
+ value = store.get(f"provider:{provider}")
102
+ except CredentialStoreError:
103
+ # Local generation remains usable with environment-supplied keys.
104
+ value = None
105
+ if value:
106
+ values[environment_name] = value
107
+ return values
108
+
109
+
110
+ def _resolve_assembly_step_source(root: Path, requested: str | Path | None) -> Path | None:
111
+ source = Path(requested).expanduser() if requested else None
112
+ if source is None:
113
+ source = next((root / name for name in ASSEMBLY_STEP_FILENAMES if (root / name).is_file()), None)
114
+ if source is None:
115
+ return None
116
+ if not source.is_absolute():
117
+ source = root / source
118
+ source = source.resolve()
119
+ if not source.is_file():
120
+ raise LocalProjectError(f"Assembly STEP file does not exist: {source}")
121
+ return source
122
+
123
+
124
+ def _prepare_assembly_step(root: Path, source: Path | None) -> Path | None:
125
+ if source is None:
126
+ return None
127
+
128
+ destination = (root / "assembly.step").resolve()
129
+ if source != destination:
130
+ shutil.copy2(source, destination)
131
+ return destination
132
+
133
+
134
+ def _resolve_source_file(root: Path, value: str | Path | None) -> Path | None:
135
+ if not value:
136
+ return None
137
+ source = Path(value).expanduser()
138
+ if not source.is_absolute():
139
+ source = root / source
140
+ source = source.resolve()
141
+ if not source.is_file():
142
+ raise LocalProjectError(f"Project artifact does not exist: {source}")
143
+ return source
144
+
145
+
146
+ def _read_stl_mesh(path: Path) -> dict[str, Any]:
147
+ """Read a binary or ASCII STL into the mesh payload consumed by the web viewport."""
148
+ data = path.read_bytes()
149
+ vertices: list[float] = []
150
+ faces: list[int] = []
151
+ vertex_ids: dict[tuple[float, float, float], int] = {}
152
+
153
+ def add_triangle(points: list[tuple[float, float, float]]) -> None:
154
+ if len(points) != 3:
155
+ return
156
+ face: list[int] = []
157
+ for point in points:
158
+ if not all(math.isfinite(value) for value in point):
159
+ raise LocalProjectError(f"STL contains a non-finite vertex: {path}")
160
+ vertex_id = vertex_ids.get(point)
161
+ if vertex_id is None:
162
+ vertex_id = len(vertices) // 3
163
+ vertex_ids[point] = vertex_id
164
+ vertices.extend(point)
165
+ face.append(vertex_id)
166
+ faces.extend(face)
167
+
168
+ binary_count = int.from_bytes(data[80:84], "little") if len(data) >= 84 else -1
169
+ binary_size = 84 + max(binary_count, 0) * 50
170
+ if binary_count >= 0 and binary_size == len(data):
171
+ for index in range(binary_count):
172
+ offset = 84 + index * 50 + 12
173
+ points = [struct.unpack_from("<3f", data, offset + point * 12) for point in range(3)]
174
+ add_triangle(points)
175
+ else:
176
+ try:
177
+ text = data.decode("ascii")
178
+ except UnicodeDecodeError as exc:
179
+ raise LocalProjectError(f"Unsupported STL encoding: {path}") from exc
180
+ points: list[tuple[float, float, float]] = []
181
+ for line in text.splitlines():
182
+ fields = line.strip().split()
183
+ if len(fields) == 4 and fields[0].lower() == "vertex":
184
+ try:
185
+ points.append(tuple(float(value) for value in fields[1:4]))
186
+ except ValueError as exc:
187
+ raise LocalProjectError(f"Invalid STL vertex in {path}") from exc
188
+ if len(points) == 3:
189
+ add_triangle(points)
190
+ points = []
191
+
192
+ if not faces:
193
+ raise LocalProjectError(f"STL contains no triangles: {path}")
194
+ return {
195
+ "shapeId": f"imported-{path.stem}",
196
+ "name": path.stem,
197
+ "vertices": vertices,
198
+ "faces": faces,
199
+ }
200
+
201
+
202
+ def import_project(
203
+ source: str | Path,
204
+ *,
205
+ destination: str | Path | None = None,
206
+ assembly_step: str | Path | None = None,
207
+ preview_stl: str | Path | None = None,
208
+ ) -> ProjectManifest:
209
+ """Import a generated Hardware Intermediate Representation project and make its CAD renderable locally."""
210
+ source_path = Path(source).expanduser().resolve()
211
+ if source_path.is_dir():
212
+ source_path = source_path / PROJECT_FILENAME
213
+ if not source_path.is_file():
214
+ raise LocalProjectError(f"Project manifest does not exist: {source_path}")
215
+
216
+ source_root = source_path.parent.resolve()
217
+ imported = load_project_manifest(source_path)
218
+ from forma_core.workspaces.projects.models import HardwareIntermediateRepresentation
219
+
220
+ try:
221
+ ir = HardwareIntermediateRepresentation.model_validate(imported.project_ir)
222
+ except Exception as exc:
223
+ raise LocalProjectError(f"Project manifest contains invalid HardwareIntermediateRepresentation: {source_path}") from exc
224
+
225
+ target_root = Path(destination).expanduser().resolve() if destination else source_root
226
+ target_root.mkdir(parents=True, exist_ok=True)
227
+ cad_model = ir.cad_model if isinstance(ir.cad_model, dict) else {}
228
+ step_source = _resolve_source_file(source_root, assembly_step)
229
+ if step_source is None:
230
+ step_source = _resolve_source_file(source_root, cad_model.get("path"))
231
+ if step_source is None:
232
+ step_source = next(
233
+ (candidate for name in ASSEMBLY_STEP_FILENAMES if (candidate := source_root / name).is_file()),
234
+ None,
235
+ )
236
+ if step_source is None:
237
+ raise LocalProjectError("Imported project has no native STEP artifact.")
238
+
239
+ preview_source = _resolve_source_file(source_root, preview_stl)
240
+ if preview_source is None:
241
+ preview_source = _resolve_source_file(source_root, cad_model.get("preview_path"))
242
+ if preview_source is None:
243
+ raise LocalProjectError("Imported project has no STL preview artifact.")
244
+
245
+ from forma_core.workspaces.projects.output import attach_assembly_step, persist_project_output
246
+
247
+ assembly_path = _prepare_assembly_step(target_root, step_source)
248
+ preview_path = (target_root / "cad-preview.stl").resolve()
249
+ if preview_source != preview_path:
250
+ shutil.copy2(preview_source, preview_path)
251
+ ir.cad_model = {
252
+ **cad_model,
253
+ "preview_path": str(preview_path),
254
+ "preview_filename": preview_path.name,
255
+ "meshes": [_read_stl_mesh(preview_path)],
256
+ "source": "Imported native OpenCAD STEP/STL project",
257
+ }
258
+ metadata = dict(ir.assembly_metadata or {})
259
+ metadata["project_id"] = imported.project_id
260
+ metadata["import_source"] = str(source_path)
261
+ metadata["cad_preview_imported"] = True
262
+ ir.assembly_metadata = metadata
263
+ assembly_artifact = attach_assembly_step(ir, assembly_path)
264
+ persist_project_output(
265
+ ir,
266
+ prompt_text=imported.prompt or imported.title,
267
+ owner_user_id=LOCAL_OWNER_USER_ID,
268
+ )
269
+
270
+ artifacts = [
271
+ artifact
272
+ for artifact in imported.artifacts
273
+ if artifact.path not in {"assembly.step", "assembled.step", "cad-preview.stl"}
274
+ ]
275
+ artifacts.extend(
276
+ (
277
+ ProjectArtifactReference(
278
+ path="assembly.step",
279
+ sha256=assembly_artifact["sha256"],
280
+ media_type="model/step",
281
+ ),
282
+ ProjectArtifactReference(
283
+ path="cad-preview.stl",
284
+ sha256=hashlib.sha256(preview_path.read_bytes()).hexdigest(),
285
+ media_type="model/stl",
286
+ ),
287
+ )
288
+ )
289
+ updated = ProjectManifest(
290
+ format=PROJECT_MANIFEST_FORMAT,
291
+ version=1,
292
+ project_id=imported.project_id,
293
+ workspace_id=imported.workspace_id,
294
+ title=imported.title or (ir.overview.title if ir.overview else "Imported Forma Project"),
295
+ prompt=imported.prompt or imported.title,
296
+ project_ir=ir.model_dump(mode="json"),
297
+ artifacts=artifacts,
298
+ )
299
+ write_project_manifest(target_root / PROJECT_FILENAME, updated)
300
+ save_linkage(target_root, {"version": 1, "project_id": updated.project_id})
301
+ return updated
302
+
303
+
304
+ def build_project(
305
+ path: str | Path | None = None,
306
+ *,
307
+ prompt: str | None = None,
308
+ workflow: str = "default",
309
+ provider: str | None = None,
310
+ model: str | None = None,
311
+ simulation: bool = False,
312
+ assembly_step: str | Path | None = None,
313
+ credential_store: CredentialStore | None = None,
314
+ ) -> ProjectManifest:
315
+ root = project_root(path)
316
+ current = read_project(root)
317
+ assembly_source = _resolve_assembly_step_source(root, assembly_step)
318
+ from forma_core.generation import generate_project_with_workflow
319
+ from forma_core.agents.workflows import generate_legacy_project_with_workflow
320
+ from forma_core.domains.generation import EngineeringResult, EngineeringRequest
321
+ old_result = EngineeringResult.model_validate(current.project_ir) if current.project_ir.get("format") == "forma.engineering-result" else None
322
+ if simulation and old_result is not None:
323
+ raise LocalProjectError("A legacy simulation fixture cannot overwrite a domain project.")
324
+ legacy = bool(current.project_ir) and old_result is None
325
+
326
+ requested_prompt = (prompt or current.prompt or current.title).strip()
327
+ if not requested_prompt:
328
+ raise LocalProjectError("Build requires a prompt. Pass one or set prompt in forma-project.json.")
329
+ store = credential_store or CredentialStore()
330
+ generation_environment = SIMULATION_ENVIRONMENT if simulation else STRICT_GENERATION_ENVIRONMENT
331
+ environment = {**generation_environment, **_local_provider_environment(store)}
332
+ with config.override(environment):
333
+ generate = generate_legacy_project_with_workflow if simulation or legacy else generate_project_with_workflow
334
+ continuation = {"engineering_request": EngineeringRequest(
335
+ product_id=current.project_id, brief=requested_prompt, existing=old_result.product,
336
+ update_domains={r.domain for r in old_result.product.manifest.artifacts})} if old_result else {}
337
+ ir = generate(
338
+ workflow,
339
+ requested_prompt,
340
+ provider_name="simulation" if simulation else provider,
341
+ model_name=None if simulation else model,
342
+ generation_metadata={"project_id": current.project_id, "project_prompt": requested_prompt},
343
+ persist_project=False,
344
+ **continuation,
345
+ )
346
+ if isinstance(ir, EngineeringResult):
347
+ if assembly_source is not None:
348
+ ir.unresolved.append("A CAD file is present but no domain geometry binding was authored.")
349
+ ir.status = "partial"
350
+ updated = current.model_copy(update={"prompt": requested_prompt, "project_ir": ir.model_dump(mode="json")})
351
+ write_project_manifest(root / PROJECT_FILENAME, updated)
352
+ return updated
353
+ metadata = dict(ir.assembly_metadata or {})
354
+ metadata["project_id"] = current.project_id
355
+ metadata["project_prompt"] = requested_prompt
356
+ ir.assembly_metadata = metadata
357
+ from forma_core.workspaces.projects.output import attach_assembly_step, persist_project_output
358
+
359
+ assembly_path = _prepare_assembly_step(root, assembly_source)
360
+ assembly_artifact = attach_assembly_step(ir, assembly_path) if assembly_path is not None else None
361
+ persist_project_output(ir, prompt_text=requested_prompt, owner_user_id=LOCAL_OWNER_USER_ID)
362
+ artifacts = [
363
+ artifact
364
+ for artifact in current.artifacts
365
+ if artifact.path not in {"assembly.step", "assembled.step"}
366
+ ]
367
+ if assembly_artifact is not None:
368
+ artifacts.append(
369
+ ProjectArtifactReference(
370
+ path="assembly.step",
371
+ sha256=assembly_artifact["sha256"],
372
+ media_type="model/step",
373
+ )
374
+ )
375
+ updated = ProjectManifest(
376
+ format=PROJECT_MANIFEST_FORMAT,
377
+ version=1,
378
+ project_id=current.project_id,
379
+ workspace_id=current.workspace_id,
380
+ title=current.title or (ir.overview.title if ir.overview else requested_prompt),
381
+ prompt=requested_prompt,
382
+ project_ir=ir.model_dump(mode="json"),
383
+ artifacts=artifacts,
384
+ )
385
+ write_project_manifest(root / PROJECT_FILENAME, updated)
386
+ return updated
387
+
388
+
389
+ def status_project(path: str | Path | None = None) -> dict[str, Any]:
390
+ root = project_root(path)
391
+ manifest = read_project(root)
392
+ try:
393
+ from forma_core.validation import build_validation_summary, validate_circuit
394
+ from forma_core.workspaces.projects.models import HardwareIntermediateRepresentation
395
+
396
+ if manifest.project_ir.get("format") == "forma.engineering-result":
397
+ from forma_core.domains.generation import EngineeringResult
398
+ from forma_core.domains.composition import validate_product
399
+ result = EngineeringResult.model_validate(manifest.project_ir)
400
+ report = validate_product(result.product)
401
+ return {"project_id": manifest.project_id, "title": manifest.title, "path": str(root / PROJECT_FILENAME),
402
+ "valid": report.is_valid, "validation": report.model_dump(mode="json"), "status": result.status}
403
+ ir = HardwareIntermediateRepresentation.model_validate(manifest.project_ir)
404
+ summary = build_validation_summary(validate_circuit(ir.components, ir.nets, ir.requirements))
405
+ valid = not summary.critical
406
+ validation = summary.model_dump(mode="json")
407
+ except Exception as exc:
408
+ valid = False
409
+ validation = {"critical": [str(exc)], "warning": [], "info": []}
410
+ linkage = load_linkage(root)
411
+ return {
412
+ "project_id": manifest.project_id,
413
+ "title": manifest.title,
414
+ "path": str(root / PROJECT_FILENAME),
415
+ "valid": valid,
416
+ "validation": validation,
417
+ "remote": linkage.get("remote"),
418
+ "remote_project_id": linkage.get("remote_project_id") or linkage.get("project_id") if linkage.get("remote") else None,
419
+ "revision_id": linkage.get("revision_id"),
420
+ "parent_revision_id": linkage.get("parent_revision_id"),
421
+ }
422
+
423
+
424
+ def slice_local_project(
425
+ path: str | Path | None = None,
426
+ *,
427
+ printer_id: str | None = None,
428
+ backend: str | None = None,
429
+ profile: str | Path | None = None,
430
+ profile_name: str | None = None,
431
+ output_name: str | None = None,
432
+ ) -> ProjectManifest:
433
+ """Slice an existing local CAD mesh without regenerating the project."""
434
+ root = project_root(path)
435
+ manifest = read_project(root)
436
+ from forma_core.workspaces.projects.fabrication import (
437
+ SliceRequest,
438
+ load_printer_registry,
439
+ resolve_slice_profile,
440
+ slice_project as run_slice_project,
441
+ )
442
+ from forma_core.workspaces.projects.models import HardwareIntermediateRepresentation
443
+ from forma_core.workspaces.projects.state import ProjectArtifact
444
+
445
+ try:
446
+ ir = HardwareIntermediateRepresentation.model_validate(manifest.project_ir)
447
+ except Exception as exc:
448
+ raise LocalProjectError("Project manifest contains invalid HardwareIntermediateRepresentation.") from exc
449
+ cad = ir.cad_model if isinstance(ir.cad_model, dict) else {}
450
+ mesh_path = str(cad.get("preview_path") or "").strip()
451
+ if not mesh_path:
452
+ for artifact in manifest.artifacts:
453
+ if (artifact.media_type or "").lower() == "model/stl":
454
+ mesh_path = artifact.path
455
+ break
456
+ if not mesh_path:
457
+ raise LocalProjectError("Project has no printable STL mesh artifact. Generate or import CAD first.")
458
+ mesh = Path(mesh_path).expanduser()
459
+ if not mesh.is_absolute():
460
+ mesh = (root / mesh).resolve()
461
+ if not mesh.is_file():
462
+ raise LocalProjectError(f"Printable mesh artifact does not exist: {mesh}")
463
+ registry = load_printer_registry()
464
+ try:
465
+ resolved = resolve_slice_profile(
466
+ registry,
467
+ printer_id=printer_id,
468
+ backend=backend,
469
+ native_config=str(profile) if profile else None,
470
+ profile_name=profile_name,
471
+ )
472
+ except (ValueError, RuntimeError) as exc:
473
+ raise LocalProjectError(str(exc)) from exc
474
+ output = root / "fabrication" / (output_name or f"{mesh.stem}.gcode")
475
+ if output_name and Path(output_name).name != output_name:
476
+ raise LocalProjectError("Slice output name must be a filename, not a path.")
477
+ mesh_artifact = ProjectArtifact(
478
+ artifact_id="native-cad-mesh",
479
+ kind="mesh.stl",
480
+ uri=str(mesh),
481
+ media_type="model/stl",
482
+ checksum=f"sha256:{hashlib.sha256(mesh.read_bytes()).hexdigest()}",
483
+ metadata={"path": str(mesh)},
484
+ )
485
+ try:
486
+ result = run_slice_project(
487
+ SliceRequest(
488
+ mesh_artifact=mesh_artifact,
489
+ profile=resolved,
490
+ output_path=str(output),
491
+ project_id=manifest.project_id,
492
+ )
493
+ )
494
+ except Exception as exc:
495
+ raise LocalProjectError(str(exc)) from exc
496
+
497
+ metadata = dict(ir.assembly_metadata or {})
498
+ metadata["fabrication"] = {
499
+ "status": "succeeded",
500
+ "backend": result.backend,
501
+ "printer_name": result.printer_name,
502
+ "profile_name": result.profile_name,
503
+ "gcode_sha256": result.gcode_artifact.checksum,
504
+ "report_uri": result.report_artifact.uri if result.report_artifact else None,
505
+ }
506
+ ir.assembly_metadata = metadata
507
+ from forma_core.workspaces.projects.output import persist_project_output
508
+
509
+ persist_project_output(ir, prompt_text=manifest.prompt or manifest.title, owner_user_id=LOCAL_OWNER_USER_ID)
510
+ references = [
511
+ artifact
512
+ for artifact in manifest.artifacts
513
+ if artifact.path not in {"fabrication/" + output.name, "fabrication/" + output.with_suffix(".report.json").name}
514
+ ]
515
+ for artifact in (result.gcode_artifact, result.report_artifact):
516
+ if artifact is None:
517
+ continue
518
+ artifact_path = Path(artifact.uri).resolve().relative_to(root.resolve()).as_posix()
519
+ references.append(
520
+ ProjectArtifactReference(
521
+ path=artifact_path,
522
+ sha256=str(artifact.checksum or "").removeprefix("sha256:"),
523
+ media_type=artifact.media_type,
524
+ size_bytes=Path(artifact.uri).stat().st_size,
525
+ )
526
+ )
527
+ updated = ProjectManifest(
528
+ format=PROJECT_MANIFEST_FORMAT,
529
+ version=1,
530
+ project_id=manifest.project_id,
531
+ workspace_id=manifest.workspace_id,
532
+ title=manifest.title,
533
+ prompt=manifest.prompt,
534
+ visibility=manifest.visibility,
535
+ project_ir=ir.model_dump(mode="json"),
536
+ artifacts=references,
537
+ )
538
+ write_project_manifest(root / PROJECT_FILENAME, updated)
539
+ return updated
540
+
541
+
542
+ def update_linkage(path: str | Path, **values: Any) -> dict[str, Any]:
543
+ root = project_root(path)
544
+ linkage = {**load_linkage(root), **values}
545
+ save_linkage(root, linkage)
546
+ return linkage
547
+
548
+
549
+ __all__ = [
550
+ "LOCAL_PROVIDER_ENVIRONMENT",
551
+ "LocalProjectError",
552
+ "PROJECT_FILENAME",
553
+ "build_project",
554
+ "import_project",
555
+ "init_project",
556
+ "project_path",
557
+ "project_root",
558
+ "read_project",
559
+ "status_project",
560
+ "slice_local_project",
561
+ "update_linkage",
562
+ ]