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
@@ -0,0 +1,194 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import List
5
+
6
+ from forma_core.jobs.source_usage import normalize_generation_workflow_id
7
+ from forma_core.workspaces.projects.models import (
8
+ ClarifyingQuestion,
9
+ ClarifyingQuestionsRequest,
10
+ ClarifyingQuestionsResponse,
11
+ )
12
+
13
+
14
+ class ContextClarifierAgent:
15
+ """Asks focused pre-generation questions so hardware context is explicit."""
16
+
17
+ agent_name = "Context Clarifier Agent"
18
+
19
+ def ask(self, request: ClarifyingQuestionsRequest) -> ClarifyingQuestionsResponse:
20
+ prompt = (request.prompt or "").strip()
21
+ workflow = normalize_generation_workflow_id(request.workflow, strict=False)
22
+ if request.max_questions <= 0:
23
+ return self._response(False, "Question limit is zero.", [], workflow)
24
+ if self._already_has_context(prompt):
25
+ return self._response(False, "Human context has already been supplied.", [], workflow)
26
+ if self._user_requested_no_questions(prompt):
27
+ return self._response(False, "User asked to skip clarification.", [], workflow)
28
+
29
+ questions = self._questions_for_prompt(prompt, request.has_image)
30
+ limited = questions[: request.max_questions]
31
+ should_ask = bool(limited and (request.force or self._looks_under_specified(prompt, request.has_image)))
32
+ reason = "Ask for missing build context before generation." if should_ask else "Prompt has enough context to generate."
33
+ return self._response(should_ask, reason, limited if should_ask else [], workflow)
34
+
35
+ def _response(
36
+ self,
37
+ should_ask: bool,
38
+ reason: str,
39
+ questions: List[ClarifyingQuestion],
40
+ workflow: str,
41
+ ) -> ClarifyingQuestionsResponse:
42
+ return ClarifyingQuestionsResponse(
43
+ agent=self.agent_name,
44
+ should_ask=should_ask,
45
+ reason=reason,
46
+ questions=questions,
47
+ workflow=workflow,
48
+ )
49
+
50
+ def _already_has_context(self, prompt: str) -> bool:
51
+ return "human-in-the-loop context:" in prompt.lower()
52
+
53
+ def _user_requested_no_questions(self, prompt: str) -> bool:
54
+ lowered = prompt.lower()
55
+ return any(
56
+ marker in lowered
57
+ for marker in (
58
+ "don't ask questions",
59
+ "do not ask questions",
60
+ "no questions",
61
+ "skip questions",
62
+ "generate immediately",
63
+ "build immediately",
64
+ )
65
+ )
66
+
67
+ def _looks_under_specified(self, prompt: str, has_image: bool) -> bool:
68
+ if has_image and len(prompt.split()) < 12:
69
+ return True
70
+ signals = (
71
+ "voltage",
72
+ "battery",
73
+ "usb",
74
+ "esp32",
75
+ "arduino",
76
+ "sensor",
77
+ "display",
78
+ "enclosure",
79
+ "weather",
80
+ "budget",
81
+ "cost",
82
+ "validate",
83
+ "success",
84
+ )
85
+ signal_count = sum(1 for signal in signals if signal in prompt.lower())
86
+ return len(prompt.split()) < 18 or signal_count < 2
87
+
88
+ def _questions_for_prompt(self, prompt: str, has_image: bool) -> List[ClarifyingQuestion]:
89
+ lower = prompt.lower()
90
+ physical_form = self._physical_form_question(has_image)
91
+ if re.search(r"(lab[-\s]?on[-\s]?a[-\s]?chip|microfluid|assay|cartridge|diagnostic|reagent|sample)", lower):
92
+ return [
93
+ ClarifyingQuestion(
94
+ id="sample_assay",
95
+ label="Sample / Assay",
96
+ question="What sample, analyte, or assay workflow should this support?",
97
+ placeholder="Example: water sample, colorimetric nitrate assay, 3 reagent chambers...",
98
+ suggestions=["Water quality", "Colorimetric assay", "Fluorescence readout"],
99
+ ),
100
+ physical_form,
101
+ ClarifyingQuestion(
102
+ id="instrumentation",
103
+ label="Reader / Detection",
104
+ question="What detection and control method should the reader use?",
105
+ placeholder="Example: LED + photodiode absorbance, heater, pressure sensor, peristaltic pump...",
106
+ suggestions=["Optical absorbance", "Fluorescence", "Pressure-driven flow"],
107
+ ),
108
+ ]
109
+
110
+ if re.search(r"(tent|deploy|self[-\s]?assembl|fold|frame|shelter|weatherproof|structure)", lower):
111
+ return [
112
+ ClarifyingQuestion(
113
+ id="environment",
114
+ label="Environment",
115
+ question="Where will this operate, and what weather or load should it survive?",
116
+ placeholder="Example: camping rain/wind, sandy soil, one-person field setup, 35 mph gust target...",
117
+ suggestions=["Rain and wind", "Field work", "Portable camping"],
118
+ ),
119
+ physical_form,
120
+ ClarifyingQuestion(
121
+ id="motion_power",
122
+ label="Motion / Power",
123
+ question="How should deployment be powered and limited for safety?",
124
+ placeholder="Example: 12V battery, low-force servos, clutch release, manual crank fallback...",
125
+ suggestions=["12V battery", "Low-force actuators", "Manual release"],
126
+ ),
127
+ ]
128
+
129
+ if re.search(r"(wire|wiring|schematic|pcb|sensor|relay|motor|driver|esp32|arduino|pin|gpio)", lower):
130
+ return [
131
+ ClarifyingQuestion(
132
+ id="controller_modules",
133
+ label="Controller / Modules",
134
+ question="Which controller and major modules should be treated as fixed?",
135
+ placeholder="Example: ESP32-S3, SSD1306 OLED, SHT41, 5V relay module...",
136
+ suggestions=["ESP32", "Arduino", "Use generated choice"],
137
+ ),
138
+ physical_form,
139
+ ClarifyingQuestion(
140
+ id="power",
141
+ label="Power",
142
+ question="What power rails, battery, or adapter constraints matter?",
143
+ placeholder="Example: USB-C 5V only, 3S LiPo, no mains, separate motor rail...",
144
+ suggestions=["USB-C 5V", "Battery powered", "No mains"],
145
+ ),
146
+ ]
147
+
148
+ first_label = "Reference Image" if has_image and not prompt else "Use Case"
149
+ first_question = (
150
+ "What should Forma infer from the attached reference image?"
151
+ if has_image and not prompt
152
+ else "Who uses it, and where does it operate?"
153
+ )
154
+ first_placeholder = (
155
+ "Example: copy the layout, preserve the enclosure shape, identify visible modules..."
156
+ if has_image and not prompt
157
+ else "Example: bench prototype, outdoor field tool, wearable, classroom demo..."
158
+ )
159
+ return [
160
+ ClarifyingQuestion(
161
+ id="use_case",
162
+ label=first_label,
163
+ question=first_question,
164
+ placeholder=first_placeholder,
165
+ suggestions=["Bench prototype", "Field tool", "Consumer device"],
166
+ ),
167
+ physical_form,
168
+ ClarifyingQuestion(
169
+ id="constraints",
170
+ label="Constraints",
171
+ question="What hard constraints should the design preserve?",
172
+ placeholder="Example: USB-C only, under $100, waterproof, no enclosure, safe low voltage...",
173
+ suggestions=["Low voltage", "Low cost", "Weatherproof"],
174
+ ),
175
+ ]
176
+
177
+ def _physical_form_question(self, has_image: bool) -> ClarifyingQuestion:
178
+ question = "What overall shape, silhouette, or form factor should the system have?"
179
+ placeholder = (
180
+ "Example: preserve the reference silhouette, but make it handheld with a curved grip..."
181
+ if has_image
182
+ else "Example: curved handheld pod, cylindrical wearable, folded frame, or exposed open assembly..."
183
+ )
184
+ return ClarifyingQuestion(
185
+ id="physical_form",
186
+ label="Shape / Form Factor",
187
+ question=question,
188
+ placeholder=placeholder,
189
+ suggestions=["Curved handheld", "Cylindrical / radial", "Open frame"],
190
+ )
191
+
192
+
193
+ def ask_clarifying_questions(request: ClarifyingQuestionsRequest) -> ClarifyingQuestionsResponse:
194
+ return ContextClarifierAgent().ask(request)
@@ -0,0 +1,99 @@
1
+ """Deterministic reconciliation for catalog parts explicitly named by a user."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Iterable, Mapping
7
+
8
+ from forma_core.workspaces.projects.models import ComponentInstance
9
+
10
+
11
+ _PREFIX_BY_CATEGORY = {
12
+ "microcontroller": "U",
13
+ "sensor": "SEN",
14
+ "actuator": "ACT",
15
+ "display": "DISP",
16
+ "power": "PWR",
17
+ "communication": "COM",
18
+ }
19
+ _IGNORED_PART_TOKENS = {"generic", "plug"}
20
+ _NAMED_COMPONENT_TOKENS = {"display", "led", "relay", "sensor", "servo"}
21
+
22
+
23
+ def _tokens(value: str) -> tuple[str, ...]:
24
+ tokens: list[str] = []
25
+ for token in re.findall(r"[a-z0-9]+", value.lower()):
26
+ resistance = re.fullmatch(r"(\d+)r", token)
27
+ if resistance:
28
+ tokens.extend((resistance.group(1), "ohm"))
29
+ else:
30
+ tokens.append(token)
31
+ return tuple(tokens)
32
+
33
+
34
+ def _part_is_explicitly_requested(prompt: str, part_number: str) -> bool:
35
+ prompt_tokens = set(_tokens(prompt))
36
+ part_tokens = tuple(token for token in _tokens(part_number) if token not in _IGNORED_PART_TOKENS)
37
+ if not part_tokens:
38
+ return False
39
+ normalized_prompt = "".join(_tokens(prompt))
40
+ normalized_part = "".join(part_tokens)
41
+ if normalized_part and normalized_part in normalized_prompt:
42
+ return True
43
+ distinctive = any(any(character.isdigit() for character in token) for token in part_tokens) or any(
44
+ token in _NAMED_COMPONENT_TOKENS for token in part_tokens
45
+ )
46
+ return set(part_tokens).issubset(prompt_tokens) and distinctive
47
+
48
+
49
+ def _ref_des_prefix(template: Mapping[str, Any]) -> str:
50
+ category = str(template.get("category") or "").strip().lower()
51
+ if category == "passives":
52
+ text = f"{template.get('part_number') or ''} {template.get('name') or ''}".lower()
53
+ return "LED" if "led" in text else "R" if "resistor" in text else "P"
54
+ return _PREFIX_BY_CATEGORY.get(category, "C")
55
+
56
+
57
+ def _next_ref_des(prefix: str, used: set[str]) -> str:
58
+ index = 1
59
+ while f"{prefix}{index}" in used:
60
+ index += 1
61
+ return f"{prefix}{index}"
62
+
63
+
64
+ def reconcile_explicit_catalog_components(
65
+ prompt: str,
66
+ components: Iterable[ComponentInstance],
67
+ catalog: Iterable[Mapping[str, Any]],
68
+ ) -> tuple[list[ComponentInstance], list[str]]:
69
+ """Add exact catalog parts named in the prompt when the model omitted them."""
70
+ reconciled = list(components)
71
+ selected_parts = {component.part_number for component in reconciled}
72
+ used_refs = {component.ref_des for component in reconciled}
73
+ added: list[str] = []
74
+ for template in catalog:
75
+ part_number = str(template.get("part_number") or "").strip()
76
+ if not part_number or part_number in selected_parts:
77
+ continue
78
+ if not _part_is_explicitly_requested(prompt, part_number):
79
+ continue
80
+ prefix = _ref_des_prefix(template)
81
+ ref_des = _next_ref_des(prefix, used_refs)
82
+ component = ComponentInstance(
83
+ ref_des=ref_des,
84
+ part_number=part_number,
85
+ name=str(template.get("name") or part_number),
86
+ category=str(template.get("category") or "Component"),
87
+ unit_price=float(template.get("price") or template.get("unit_price") or 0.0),
88
+ sourcing_url=template.get("sourcing_url"),
89
+ rationale="Explicitly requested catalog part; restored by deterministic component reconciliation.",
90
+ pins=template.get("pins") or [],
91
+ )
92
+ reconciled.append(component)
93
+ selected_parts.add(part_number)
94
+ used_refs.add(ref_des)
95
+ added.append(part_number)
96
+ return reconciled, added
97
+
98
+
99
+ __all__ = ["reconcile_explicit_catalog_components"]
@@ -0,0 +1,115 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from typing import Any
6
+
7
+ from forma_core.llm import StructuredLLMProvider
8
+ from forma_core.workspaces.context.agent import ContextBriefUpdater, _assistant_reply
9
+ from forma_core.workspaces.context.models import ContextGatheringRequest, ContextTurnDecision
10
+ from forma_core.workspaces.design_briefs import DesignBrief
11
+
12
+
13
+ class ContextGatheringAgent(ContextBriefUpdater):
14
+ """Routes natural conversation and updates context only when appropriate."""
15
+
16
+ def __init__(self, llm_provider: StructuredLLMProvider | None = None) -> None:
17
+ self.llm_provider = llm_provider
18
+
19
+ def route_turn(
20
+ self,
21
+ request: ContextGatheringRequest,
22
+ previous: DesignBrief | None,
23
+ *,
24
+ workflow_state: str | None,
25
+ messages: list[dict[str, Any]],
26
+ ) -> ContextTurnDecision:
27
+ if request.requested_tool is not None:
28
+ return ContextTurnDecision(
29
+ turn_kind="proceed",
30
+ tool_name=request.requested_tool,
31
+ assistant_message="I’ll start from the current project context.",
32
+ )
33
+ if self.llm_provider is not None and self.llm_provider.is_configured:
34
+ return self.llm_provider.generate_structured(
35
+ self._routing_prompt(request, previous, workflow_state=workflow_state, messages=messages),
36
+ ContextTurnDecision,
37
+ )
38
+ return self._fallback_decision(request, previous)
39
+
40
+ @staticmethod
41
+ def _routing_prompt(
42
+ request: ContextGatheringRequest,
43
+ previous: DesignBrief | None,
44
+ *,
45
+ workflow_state: str | None,
46
+ messages: list[dict[str, Any]],
47
+ ) -> str:
48
+ recent_messages = [
49
+ {
50
+ "role": str(item.get("role") or ""),
51
+ "content": str(item.get("content") or "")[:1200],
52
+ }
53
+ for item in messages[-12:]
54
+ if isinstance(item, dict)
55
+ ]
56
+ brief = None if previous is None else {
57
+ "summary": previous.summary,
58
+ "requirements": previous.requirements,
59
+ "constraints": previous.constraints,
60
+ "requested_outputs": previous.requested_outputs,
61
+ "unresolved_questions": previous.unresolved_questions,
62
+ }
63
+ return "\n".join([
64
+ "You are Forma's conversational hardware-design intake agent.",
65
+ "Choose exactly one tool by meaning, not keywords or UI mode:",
66
+ "- ask_question: talk with the user, answer questions, or ask at most one useful design question. Set save_context=true only when the newest message contains an actual project requirement or preference.",
67
+ "- build_project: the user asks to start, build, proceed, or skip remaining questions.",
68
+ "- render_project: a completed project exists and the user asks to show or open it.",
69
+ "- iterate_project: a completed project exists and the user requests a change to it.",
70
+ "Set turn_kind only as compatibility metadata: ask_question uses chat, clarification, or context; all other tools use proceed.",
71
+ "Never mention internal fields, unresolved-context bookkeeping, routing, or context collection. Never repeat a question the user just answered or asked you to explain.",
72
+ "When ask_question offers a finite choice, populate suggestions with 2 to 4 concise, self-contained answers that the user can submit verbatim. Never add Custom, Other, Something else, or an equivalent catch-all; free text is always available.",
73
+ "If the user asks what they can build, offer a few relevant ideas and invite them to choose or describe a direction.",
74
+ "If the user says they do not know, guide them using outcomes and tradeoffs rather than repeating a technical question.",
75
+ f"Workflow state: {workflow_state or 'not_started'}",
76
+ f"Current DesignBrief: {json.dumps(brief, ensure_ascii=False)}",
77
+ f"Recent conversation: {json.dumps(recent_messages, ensure_ascii=False)}",
78
+ f"Newest user text: {request.text}",
79
+ f"Attachment kinds: {json.dumps([item.kind for item in request.attachments])}",
80
+ ])
81
+
82
+ @staticmethod
83
+ def _fallback_decision(
84
+ request: ContextGatheringRequest,
85
+ previous: DesignBrief | None,
86
+ ) -> ContextTurnDecision:
87
+ text = request.text.strip()
88
+ normalized = re.sub(r"[^a-z0-9]+", " ", text.casefold()).strip()
89
+ if re.search(r"\b(?:go|go ahead|continue|start|build it|do it|do it now|proceed|ready)\b", normalized):
90
+ return ContextTurnDecision(
91
+ turn_kind="proceed",
92
+ tool_name="build_project",
93
+ assistant_message="Understood—I’ll hand the current brief to the next agent stage.",
94
+ )
95
+ if re.search(r"\b(?:what do you mean|can you explain|could you explain|why do you ask)\b", normalized):
96
+ return ContextTurnDecision(
97
+ turn_kind="clarification",
98
+ tool_name="ask_question",
99
+ assistant_message=_assistant_reply(text, list(previous.unresolved_questions) if previous else [], previous),
100
+ )
101
+ if normalized in {"hi", "hello", "hey"} or "what can i build" in normalized:
102
+ return ContextTurnDecision(
103
+ turn_kind="chat",
104
+ tool_name="ask_question",
105
+ assistant_message=(
106
+ "I can help you explore a hardware idea, from a handheld instrument or environmental monitor to a small robot. "
107
+ "Tell me what you want it to accomplish, or name a direction you’re curious about."
108
+ ),
109
+ )
110
+ return ContextTurnDecision(
111
+ turn_kind="context",
112
+ tool_name="ask_question",
113
+ save_context=True,
114
+ assistant_message=_assistant_reply(text, list(previous.unresolved_questions) if previous else [], previous),
115
+ )