lightfall 0.1.1__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 (388) hide show
  1. lightfall/__init__.py +8 -0
  2. lightfall/__main__.py +10 -0
  3. lightfall/_version.py +24 -0
  4. lightfall/acquire/__init__.py +74 -0
  5. lightfall/acquire/buffer.py +363 -0
  6. lightfall/acquire/device_wrapper.py +416 -0
  7. lightfall/acquire/engine/__init__.py +155 -0
  8. lightfall/acquire/engine/base.py +587 -0
  9. lightfall/acquire/engine/bluesky.py +358 -0
  10. lightfall/acquire/engine/mock.py +165 -0
  11. lightfall/acquire/engine/plugins/__init__.py +9 -0
  12. lightfall/acquire/engine/plugins/bluesky_plugin.py +56 -0
  13. lightfall/acquire/engine/plugins/mock_plugin.py +55 -0
  14. lightfall/acquire/engine/protocol.py +145 -0
  15. lightfall/acquire/engine/registry.py +152 -0
  16. lightfall/acquire/engine/state.py +32 -0
  17. lightfall/acquire/engine/waiting_hook.py +225 -0
  18. lightfall/acquire/nats_bridge.py +62 -0
  19. lightfall/acquire/plan_ui.py +78 -0
  20. lightfall/acquire/plans/__init__.py +38 -0
  21. lightfall/acquire/plans/adaptive.py +288 -0
  22. lightfall/acquire/plans/example_plans.py +995 -0
  23. lightfall/acquire/plans/lightfall_plans.py +587 -0
  24. lightfall/acquire/plans/registry.py +543 -0
  25. lightfall/acquire/plans/standard_plans.py +186 -0
  26. lightfall/acquire/plans/user_plans.py +470 -0
  27. lightfall/acquire/runengine.py +36 -0
  28. lightfall/acquire/signals.py +452 -0
  29. lightfall/acquire/triggers/__init__.py +16 -0
  30. lightfall/acquire/triggers/base.py +25 -0
  31. lightfall/acquire/triggers/filter.py +37 -0
  32. lightfall/acquire/triggers/manager.py +73 -0
  33. lightfall/acquire/triggers/manual.py +36 -0
  34. lightfall/acquire/triggers/run_end.py +74 -0
  35. lightfall/acquire/triggers/run_start.py +52 -0
  36. lightfall/auth/__init__.py +38 -0
  37. lightfall/auth/policy.py +518 -0
  38. lightfall/auth/providers/__init__.py +30 -0
  39. lightfall/auth/providers/base.py +124 -0
  40. lightfall/auth/providers/keycloak.py +1017 -0
  41. lightfall/auth/providers/local.py +319 -0
  42. lightfall/auth/providers/pam.py +250 -0
  43. lightfall/auth/service_key.py +173 -0
  44. lightfall/auth/service_key_auth.py +79 -0
  45. lightfall/auth/session.py +656 -0
  46. lightfall/claude/__init__.py +52 -0
  47. lightfall/claude/_internal/__init__.py +1 -0
  48. lightfall/claude/_internal/serialization.py +195 -0
  49. lightfall/claude/_internal/threading.py +61 -0
  50. lightfall/claude/_internal/worker.py +757 -0
  51. lightfall/claude/_session_assembly.py +124 -0
  52. lightfall/claude/agent.py +596 -0
  53. lightfall/claude/lightfall_core_tools.py +410 -0
  54. lightfall/claude/markdown.py +103 -0
  55. lightfall/claude/permission_manager.py +588 -0
  56. lightfall/claude/tools/__init__.py +45 -0
  57. lightfall/claude/tools/controller.py +143 -0
  58. lightfall/claude/tools/interaction.py +177 -0
  59. lightfall/claude/tools/introspection.py +127 -0
  60. lightfall/claude/tools/logs.py +155 -0
  61. lightfall/claude/tools/screenshot.py +87 -0
  62. lightfall/claude/widget.py +851 -0
  63. lightfall/claude/widgets/__init__.py +5 -0
  64. lightfall/claude/widgets/permission_request.py +282 -0
  65. lightfall/claude/widgets/question_request.py +227 -0
  66. lightfall/claude/widgets/task_card.py +223 -0
  67. lightfall/config/__init__.py +23 -0
  68. lightfall/config/layers.py +317 -0
  69. lightfall/config/manager.py +244 -0
  70. lightfall/config/schema.py +154 -0
  71. lightfall/core/__init__.py +23 -0
  72. lightfall/core/application.py +727 -0
  73. lightfall/core/services.py +235 -0
  74. lightfall/devices/__init__.py +53 -0
  75. lightfall/devices/backends/__init__.py +17 -0
  76. lightfall/devices/backends/bcs.py +448 -0
  77. lightfall/devices/backends/happi.py +986 -0
  78. lightfall/devices/backends/mock.py +646 -0
  79. lightfall/devices/base.py +338 -0
  80. lightfall/devices/catalog.py +1039 -0
  81. lightfall/devices/connection_manager.py +676 -0
  82. lightfall/devices/model.py +290 -0
  83. lightfall/devices/monitoring.py +442 -0
  84. lightfall/devices/sim/__init__.py +26 -0
  85. lightfall/devices/sim/areadetector.py +436 -0
  86. lightfall/devices/sim/generators.py +223 -0
  87. lightfall/devices/sim/plugins.py +116 -0
  88. lightfall/epics/__init__.py +28 -0
  89. lightfall/epics/ca/__init__.py +10 -0
  90. lightfall/epics/ca/context.py +100 -0
  91. lightfall/epics/ca/pv.py +303 -0
  92. lightfall/epics/widgets/__init__.py +49 -0
  93. lightfall/epics/widgets/areadetector/__init__.py +16 -0
  94. lightfall/epics/widgets/areadetector/areadetector.py +281 -0
  95. lightfall/epics/widgets/areadetector/controls.py +478 -0
  96. lightfall/epics/widgets/areadetector/image_view.py +447 -0
  97. lightfall/epics/widgets/auto.py +319 -0
  98. lightfall/epics/widgets/base.py +404 -0
  99. lightfall/epics/widgets/checkbox.py +239 -0
  100. lightfall/epics/widgets/combobox.py +202 -0
  101. lightfall/epics/widgets/label.py +176 -0
  102. lightfall/epics/widgets/lineedit.py +253 -0
  103. lightfall/epics/widgets/motor.py +694 -0
  104. lightfall/epics/widgets/ophyd_base.py +469 -0
  105. lightfall/epics/widgets/ophyd_combobox.py +86 -0
  106. lightfall/epics/widgets/ophyd_label.py +54 -0
  107. lightfall/epics/widgets/ophyd_lineedit.py +170 -0
  108. lightfall/epics/widgets/ophyd_spinbox.py +79 -0
  109. lightfall/epics/widgets/slider.py +272 -0
  110. lightfall/epics/widgets/status_indicator.py +98 -0
  111. lightfall/epics/widgets/style.py +188 -0
  112. lightfall/exporter/__init__.py +1 -0
  113. lightfall/exporter/cli.py +67 -0
  114. lightfall/exporter/converters/__init__.py +26 -0
  115. lightfall/exporter/converters/base.py +39 -0
  116. lightfall/exporter/converters/noop.py +39 -0
  117. lightfall/exporter/converters/nxsas.py +73 -0
  118. lightfall/exporter/service.py +200 -0
  119. lightfall/exporter/tiled_utils.py +92 -0
  120. lightfall/ipc/__init__.py +6 -0
  121. lightfall/ipc/service.py +701 -0
  122. lightfall/ipc/trust.py +144 -0
  123. lightfall/logbook/__init__.py +46 -0
  124. lightfall/logbook/action_dialog.py +207 -0
  125. lightfall/logbook/action_logger.py +432 -0
  126. lightfall/logbook/block_mapper.py +562 -0
  127. lightfall/logbook/client.py +799 -0
  128. lightfall/logbook/converter.py +273 -0
  129. lightfall/logbook/editors/__init__.py +19 -0
  130. lightfall/logbook/editors/highlighter.py +305 -0
  131. lightfall/logbook/editors/markdown_editor.py +319 -0
  132. lightfall/logbook/editors/richtext_editor.py +1397 -0
  133. lightfall/logbook/entry_widget.py +1065 -0
  134. lightfall/logbook/event_listener.py +221 -0
  135. lightfall/logbook/fragment_widgets.py +925 -0
  136. lightfall/logbook/position_mapper.py +320 -0
  137. lightfall/logbook/protection.py +402 -0
  138. lightfall/logbook/style.py +394 -0
  139. lightfall/logbook/url.py +29 -0
  140. lightfall/logbook/visual_protection.py +330 -0
  141. lightfall/logbook/widget.py +680 -0
  142. lightfall/main.py +1091 -0
  143. lightfall/pipelines/__init__.py +4 -0
  144. lightfall/pipelines/client.py +148 -0
  145. lightfall/plugins/__init__.py +119 -0
  146. lightfall/plugins/agent_plugin.py +106 -0
  147. lightfall/plugins/agents/__init__.py +10 -0
  148. lightfall/plugins/agents/_mcp_helpers.py +52 -0
  149. lightfall/plugins/agents/alignment.py +94 -0
  150. lightfall/plugins/agents/autonomous_experiment/__init__.py +12 -0
  151. lightfall/plugins/agents/autonomous_experiment/nats_tools.py +210 -0
  152. lightfall/plugins/agents/autonomous_experiment/plugin.py +60 -0
  153. lightfall/plugins/agents/autonomous_experiment/prompts.py +164 -0
  154. lightfall/plugins/agents/current_esaf.py +435 -0
  155. lightfall/plugins/agents/device_tools.py +1043 -0
  156. lightfall/plugins/agents/engine_tools.py +720 -0
  157. lightfall/plugins/agents/ipython_tools.py +444 -0
  158. lightfall/plugins/agents/panel_builder.py +637 -0
  159. lightfall/plugins/agents/panel_design/references/cross_panel_patterns.md +95 -0
  160. lightfall/plugins/agents/panel_design/references/panel_design.md +680 -0
  161. lightfall/plugins/agents/panel_design.py +94 -0
  162. lightfall/plugins/agents/plan_design/references/plan_design.md +398 -0
  163. lightfall/plugins/agents/plan_design.py +90 -0
  164. lightfall/plugins/agents/plan_tools.py +878 -0
  165. lightfall/plugins/agents/scan_planning.py +101 -0
  166. lightfall/plugins/builtin_manifest.py +348 -0
  167. lightfall/plugins/controller_plugin.py +162 -0
  168. lightfall/plugins/engine_plugin.py +124 -0
  169. lightfall/plugins/errors.py +104 -0
  170. lightfall/plugins/info.py +112 -0
  171. lightfall/plugins/loader.py +878 -0
  172. lightfall/plugins/manifest.py +150 -0
  173. lightfall/plugins/panel_plugin.py +119 -0
  174. lightfall/plugins/plan_plugin.py +163 -0
  175. lightfall/plugins/registry.py +309 -0
  176. lightfall/plugins/settings_plugin.py +226 -0
  177. lightfall/plugins/statusbar_plugin.py +289 -0
  178. lightfall/plugins/theme_plugin.py +165 -0
  179. lightfall/plugins/types.py +136 -0
  180. lightfall/plugins/user_plugins.py +764 -0
  181. lightfall/project/__init__.py +37 -0
  182. lightfall/project/model.py +375 -0
  183. lightfall/project/service.py +427 -0
  184. lightfall/project/welcome.py +106 -0
  185. lightfall/resources/__init__.py +126 -0
  186. lightfall/resources/images/__init__.py +1 -0
  187. lightfall/resources/images/icon.ico +0 -0
  188. lightfall/resources/images/icon.png +0 -0
  189. lightfall/resources/images/logo.png +0 -0
  190. lightfall/services/__init__.py +33 -0
  191. lightfall/services/_alshub_client.py +73 -0
  192. lightfall/services/access_stamper.py +240 -0
  193. lightfall/services/als_beam_status.py +347 -0
  194. lightfall/services/ca_tunnel.py +325 -0
  195. lightfall/services/threaded_tiled_writer.py +174 -0
  196. lightfall/services/tiled_auth.py +21 -0
  197. lightfall/services/tiled_service.py +971 -0
  198. lightfall/services/tiled_writer_patch.py +301 -0
  199. lightfall/settings/__init__.py +1 -0
  200. lightfall/settings/image_helpers.py +30 -0
  201. lightfall/settings/user_settings_client.py +232 -0
  202. lightfall/ui/__init__.py +28 -0
  203. lightfall/ui/annotations.py +208 -0
  204. lightfall/ui/common/__init__.py +7 -0
  205. lightfall/ui/dialogs/__init__.py +26 -0
  206. lightfall/ui/dialogs/about_dialog.py +131 -0
  207. lightfall/ui/dialogs/add_trigger_dialog.py +152 -0
  208. lightfall/ui/dialogs/base.py +44 -0
  209. lightfall/ui/dialogs/bug_report_dialog.py +353 -0
  210. lightfall/ui/dialogs/create_plan_dialog.py +189 -0
  211. lightfall/ui/dialogs/device_edit_dialog.py +183 -0
  212. lightfall/ui/dialogs/export_dialog.py +565 -0
  213. lightfall/ui/dialogs/go_to_position_dialog.py +192 -0
  214. lightfall/ui/dialogs/login_dialog.py +756 -0
  215. lightfall/ui/dialogs/oauth_browser_dialog.py +305 -0
  216. lightfall/ui/dialogs/run_pipeline_dialog.py +131 -0
  217. lightfall/ui/dialogs/sample_metadata_dialog.py +316 -0
  218. lightfall/ui/docking/__init__.py +22 -0
  219. lightfall/ui/docking/icon_sidebar.py +806 -0
  220. lightfall/ui/docking/manager.py +682 -0
  221. lightfall/ui/docking/state.py +113 -0
  222. lightfall/ui/docking/theme.py +399 -0
  223. lightfall/ui/docking/widget.py +214 -0
  224. lightfall/ui/events.py +75 -0
  225. lightfall/ui/mainwindow.py +1006 -0
  226. lightfall/ui/models/__init__.py +49 -0
  227. lightfall/ui/models/device_selection.py +389 -0
  228. lightfall/ui/models/device_tree.py +1095 -0
  229. lightfall/ui/models/thread_model.py +667 -0
  230. lightfall/ui/models/tiled_model.py +384 -0
  231. lightfall/ui/panels/__init__.py +28 -0
  232. lightfall/ui/panels/base.py +525 -0
  233. lightfall/ui/panels/bluesky_panel.py +619 -0
  234. lightfall/ui/panels/claude/__init__.py +9 -0
  235. lightfall/ui/panels/claude/agent_registry.py +168 -0
  236. lightfall/ui/panels/claude_panel.py +887 -0
  237. lightfall/ui/panels/device_panel.py +370 -0
  238. lightfall/ui/panels/documents_panel.py +166 -0
  239. lightfall/ui/panels/ipython_panel.py +580 -0
  240. lightfall/ui/panels/logbook_entries_panel.py +84 -0
  241. lightfall/ui/panels/logbook_panel.py +627 -0
  242. lightfall/ui/panels/logging_panel.py +587 -0
  243. lightfall/ui/panels/pipeline_jobs_panel.py +160 -0
  244. lightfall/ui/panels/pipeline_triggers_panel.py +170 -0
  245. lightfall/ui/panels/plugins/__init__.py +34 -0
  246. lightfall/ui/panels/plugins/bluesky_plugin.py +27 -0
  247. lightfall/ui/panels/plugins/claude_plugin.py +29 -0
  248. lightfall/ui/panels/plugins/device_plugin.py +27 -0
  249. lightfall/ui/panels/plugins/documents_plugin.py +26 -0
  250. lightfall/ui/panels/plugins/ipython_plugin.py +27 -0
  251. lightfall/ui/panels/plugins/logbook_entries_plugin.py +23 -0
  252. lightfall/ui/panels/plugins/logbook_plugin.py +27 -0
  253. lightfall/ui/panels/plugins/logging_plugin.py +27 -0
  254. lightfall/ui/panels/plugins/pipeline_jobs_plugin.py +23 -0
  255. lightfall/ui/panels/plugins/pipeline_triggers_plugin.py +25 -0
  256. lightfall/ui/panels/plugins/queue_plugin.py +29 -0
  257. lightfall/ui/panels/plugins/synoptic_plugin.py +38 -0
  258. lightfall/ui/panels/plugins/threads_plugin.py +27 -0
  259. lightfall/ui/panels/plugins/tiled_browser_plugin.py +27 -0
  260. lightfall/ui/panels/plugins/visualization_plugin.py +27 -0
  261. lightfall/ui/panels/queue.py +754 -0
  262. lightfall/ui/panels/registry.py +483 -0
  263. lightfall/ui/panels/synoptic/__init__.py +27 -0
  264. lightfall/ui/panels/synoptic/editors.py +481 -0
  265. lightfall/ui/panels/synoptic/items.py +556 -0
  266. lightfall/ui/panels/synoptic/models.py +336 -0
  267. lightfall/ui/panels/synoptic/panel.py +889 -0
  268. lightfall/ui/panels/synoptic/serialization.py +300 -0
  269. lightfall/ui/panels/synoptic/view.py +504 -0
  270. lightfall/ui/panels/threads_panel.py +621 -0
  271. lightfall/ui/panels/tiled_browser_panel.py +854 -0
  272. lightfall/ui/panels/visualization_panel.py +508 -0
  273. lightfall/ui/preferences/__init__.py +24 -0
  274. lightfall/ui/preferences/backend.py +148 -0
  275. lightfall/ui/preferences/builtin.py +220 -0
  276. lightfall/ui/preferences/claude_settings.py +762 -0
  277. lightfall/ui/preferences/device_settings.py +461 -0
  278. lightfall/ui/preferences/dialog.py +234 -0
  279. lightfall/ui/preferences/editor_settings.py +227 -0
  280. lightfall/ui/preferences/ipc_settings.py +226 -0
  281. lightfall/ui/preferences/logbook_settings.py +232 -0
  282. lightfall/ui/preferences/login_settings.py +183 -0
  283. lightfall/ui/preferences/manager.py +562 -0
  284. lightfall/ui/preferences/plugin_settings.py +392 -0
  285. lightfall/ui/preferences/proxy_settings.py +561 -0
  286. lightfall/ui/preferences/skill_settings.py +28 -0
  287. lightfall/ui/preferences/tiled_settings.py +469 -0
  288. lightfall/ui/preferences/tool_settings.py +393 -0
  289. lightfall/ui/preferences/user_portable_backend.py +131 -0
  290. lightfall/ui/preferences/user_profile_settings.py +316 -0
  291. lightfall/ui/preferences/visualization_settings.py +159 -0
  292. lightfall/ui/resources/__init__.py +1 -0
  293. lightfall/ui/resources/logo.png +0 -0
  294. lightfall/ui/statusbar/__init__.py +11 -0
  295. lightfall/ui/statusbar/manager.py +379 -0
  296. lightfall/ui/statusbar/plugins/__init__.py +28 -0
  297. lightfall/ui/statusbar/plugins/als_beam_status.py +218 -0
  298. lightfall/ui/statusbar/plugins/auth_status.py +116 -0
  299. lightfall/ui/statusbar/plugins/connection_status.py +100 -0
  300. lightfall/ui/statusbar/plugins/thread_status.py +556 -0
  301. lightfall/ui/statusbar/plugins/tiled_status.py +179 -0
  302. lightfall/ui/statusbar/plugins/user_status.py +84 -0
  303. lightfall/ui/theater/__init__.py +28 -0
  304. lightfall/ui/theater/manager.py +124 -0
  305. lightfall/ui/theater/overlay.py +279 -0
  306. lightfall/ui/theater/proxy.py +111 -0
  307. lightfall/ui/theme/__init__.py +18 -0
  308. lightfall/ui/theme/builtin.py +1015 -0
  309. lightfall/ui/theme/manager.py +875 -0
  310. lightfall/ui/theme/registry.py +195 -0
  311. lightfall/ui/toast.py +221 -0
  312. lightfall/ui/tutorial.py +1100 -0
  313. lightfall/ui/widgets/__init__.py +110 -0
  314. lightfall/ui/widgets/base_control.py +259 -0
  315. lightfall/ui/widgets/camera/__init__.py +36 -0
  316. lightfall/ui/widgets/camera/base.py +815 -0
  317. lightfall/ui/widgets/camera/dark_frames.py +213 -0
  318. lightfall/ui/widgets/camera/image_view.py +649 -0
  319. lightfall/ui/widgets/camera/panels/__init__.py +14 -0
  320. lightfall/ui/widgets/camera/panels/cooler.py +320 -0
  321. lightfall/ui/widgets/camera/panels/temperature.py +192 -0
  322. lightfall/ui/widgets/camera/plan_based.py +202 -0
  323. lightfall/ui/widgets/compact_motor.py +522 -0
  324. lightfall/ui/widgets/controller_matcher.py +278 -0
  325. lightfall/ui/widgets/controller_registry.py +144 -0
  326. lightfall/ui/widgets/device_control.py +411 -0
  327. lightfall/ui/widgets/device_selector.py +438 -0
  328. lightfall/ui/widgets/device_tree_tab.py +461 -0
  329. lightfall/ui/widgets/document_stream.py +1028 -0
  330. lightfall/ui/widgets/favorites_tab.py +191 -0
  331. lightfall/ui/widgets/motor_control.py +1120 -0
  332. lightfall/ui/widgets/observers/__init__.py +8 -0
  333. lightfall/ui/widgets/observers/camera.py +48 -0
  334. lightfall/ui/widgets/observers/image_view.py +130 -0
  335. lightfall/ui/widgets/plan_config.py +954 -0
  336. lightfall/ui/widgets/plan_edit_dialog.py +294 -0
  337. lightfall/ui/widgets/plan_selector.py +452 -0
  338. lightfall/ui/widgets/profile_avatar.py +128 -0
  339. lightfall/ui/widgets/queue_view.py +647 -0
  340. lightfall/ui/widgets/runengine_control.py +549 -0
  341. lightfall/ui/widgets/signal_control.py +793 -0
  342. lightfall/ui/widgets/skill_trigger_button.py +183 -0
  343. lightfall/ui/widgets/tiled_filter_widget.py +314 -0
  344. lightfall/ui/widgets/tiled_status.py +149 -0
  345. lightfall/ui/widgets/warning_banner.py +185 -0
  346. lightfall/utils/__init__.py +53 -0
  347. lightfall/utils/crash_diagnostics.py +454 -0
  348. lightfall/utils/data_migration.py +22 -0
  349. lightfall/utils/editor_launcher.py +594 -0
  350. lightfall/utils/error_collector.py +245 -0
  351. lightfall/utils/git_tracker.py +197 -0
  352. lightfall/utils/log_buffer.py +233 -0
  353. lightfall/utils/logging.py +229 -0
  354. lightfall/utils/module_resolver.py +70 -0
  355. lightfall/utils/sentry.py +722 -0
  356. lightfall/utils/threads.py +991 -0
  357. lightfall/utils/tiled_helpers.py +96 -0
  358. lightfall/visualization/__init__.py +50 -0
  359. lightfall/visualization/base.py +5 -0
  360. lightfall/visualization/base_visualization.py +74 -0
  361. lightfall/visualization/fitting/__init__.py +24 -0
  362. lightfall/visualization/fitting/base.py +267 -0
  363. lightfall/visualization/fitting/fitters.py +325 -0
  364. lightfall/visualization/fitting/panel.py +265 -0
  365. lightfall/visualization/memory.py +392 -0
  366. lightfall/visualization/motor_mixin.py +524 -0
  367. lightfall/visualization/pg.py +156 -0
  368. lightfall/visualization/registry.py +144 -0
  369. lightfall/visualization/spec.py +79 -0
  370. lightfall/visualization/theme.py +266 -0
  371. lightfall/visualization/widgets/__init__.py +28 -0
  372. lightfall/visualization/widgets/adaptive/__init__.py +1 -0
  373. lightfall/visualization/widgets/adaptive/heatmap.py +655 -0
  374. lightfall/visualization/widgets/adaptive/plot.py +233 -0
  375. lightfall/visualization/widgets/heatmap.py +264 -0
  376. lightfall/visualization/widgets/image_stack.py +316 -0
  377. lightfall/visualization/widgets/image_view_toolbar.py +227 -0
  378. lightfall/visualization/widgets/lazy_image_view.py +590 -0
  379. lightfall/visualization/widgets/plot_1d.py +262 -0
  380. lightfall/visualization/widgets/scatter.py +247 -0
  381. lightfall/visualization/widgets/table.py +221 -0
  382. lightfall/visualization/widgets/time_axis.py +93 -0
  383. lightfall-0.1.1.dist-info/METADATA +223 -0
  384. lightfall-0.1.1.dist-info/RECORD +388 -0
  385. lightfall-0.1.1.dist-info/WHEEL +4 -0
  386. lightfall-0.1.1.dist-info/entry_points.txt +6 -0
  387. lightfall-0.1.1.dist-info/licenses/LEGAL.md +13 -0
  388. lightfall-0.1.1.dist-info/licenses/LICENSE.md +33 -0
@@ -0,0 +1,878 @@
1
+ """MCP tools for user plan management.
2
+
3
+ Provides tools for Claude to create and manage user-defined Bluesky plans.
4
+ Plans are saved to ~/lightfall/plans/ and automatically loaded by the UserPlanService.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import inspect
10
+ import re
11
+ from typing import Any, Union
12
+
13
+ from lightfall.plugins.agent_plugin import AgentPlugin
14
+ from lightfall.utils.git_tracker import GitTracker
15
+ from lightfall.utils.logging import logger
16
+
17
+
18
+ class PlanToolsAgent(AgentPlugin):
19
+ """MCP tools for creating and managing user plans.
20
+
21
+ This plugin provides tools for Claude to:
22
+ - Create new user plans from Python code
23
+ - (Future) List, get, and delete user plans
24
+ """
25
+
26
+ @property
27
+ def name(self) -> str:
28
+ """Plugin name."""
29
+ return "plan_tools"
30
+
31
+ @property
32
+ def description(self) -> str:
33
+ """Human-readable description of what this plugin provides."""
34
+ return "Tools for creating and managing user plans"
35
+
36
+ @property
37
+ def category(self) -> str:
38
+ """Category for grouping in settings UI."""
39
+ return "acquisition"
40
+
41
+ def _get_catalog(self):
42
+ """Get the device catalog instance."""
43
+ from lightfall.devices import DeviceCatalog
44
+
45
+ return DeviceCatalog.get_instance()
46
+
47
+ @staticmethod
48
+ def _is_str_annotation(annotation: Any) -> bool:
49
+ """Check if a parameter annotation indicates a plain string type.
50
+
51
+ Handles both real type objects (``str``) and stringified
52
+ annotations produced by ``from __future__ import annotations``
53
+ (``"str"``). Returns True for ``str``, ``Optional[str]``,
54
+ ``str | None``, etc. Returns False for device-related
55
+ annotations (Annotated types with DeviceFilter, Motor,
56
+ Detector, Any, etc.) so those get resolved.
57
+ """
58
+ if annotation is str:
59
+ return True
60
+ # Stringified annotations (from __future__ import annotations)
61
+ if isinstance(annotation, str):
62
+ stripped = annotation.strip()
63
+ if stripped == "str":
64
+ return True
65
+ # Optional[str], str | None, Union[str, None]
66
+ if stripped in ("Optional[str]", "str | None", "Union[str, None]"):
67
+ return True
68
+ return False
69
+ # Real type objects — handle Optional[str], str | None, Union[str, None]
70
+ origin = getattr(annotation, "__origin__", None)
71
+ if origin is Union:
72
+ args = getattr(annotation, "__args__", ())
73
+ non_none = [a for a in args if a is not type(None)]
74
+ return len(non_none) == 1 and non_none[0] is str
75
+ return False
76
+
77
+ @staticmethod
78
+ def _numeric_target_type(annotation: Any) -> type | None:
79
+ """Return ``float`` or ``int`` if the annotation declares one of those
80
+ as the underlying scalar type, else ``None``.
81
+
82
+ Unwraps ``Annotated[T, ...]``, ``Optional[T]`` / ``T | None``, and
83
+ ``Union[T, None]``. Stringified annotations (``"float"``,
84
+ ``"Optional[float]"``, ``"Annotated[int, ...]"``) are matched by
85
+ substring on the head token, since we don't have access to the
86
+ original namespace to actually evaluate them.
87
+
88
+ Used to coerce JSON ints to Python floats for plan parameters
89
+ annotated as ``float`` — without coercion, ``mv(motor, -5)``
90
+ leaves the motor's setpoint sim_state as a Python int, which
91
+ propagates through ``describe()`` as ``dtype="integer"`` for
92
+ ophyd-fakes devices and bakes the Tiled SQL column as int64.
93
+ First fractional position written to that column then raises
94
+ ``ArrowInvalid``.
95
+ """
96
+ # Stringified path: "float", "Annotated[float, ...]", "float | None", etc.
97
+ if isinstance(annotation, str):
98
+ head = annotation.strip()
99
+ # Strip Annotated[T, ...] -> T
100
+ if head.startswith("Annotated[") and "," in head:
101
+ head = head[len("Annotated["):].split(",", 1)[0].strip()
102
+ # Strip Optional[T] / Union[T, None] / T | None
103
+ if head.startswith("Optional["):
104
+ head = head[len("Optional["):-1].strip()
105
+ elif head.startswith("Union[") and "None" in head:
106
+ args = [a.strip() for a in head[len("Union["):-1].split(",")]
107
+ non_none = [a for a in args if a not in ("None", "type(None)")]
108
+ head = non_none[0] if len(non_none) == 1 else head
109
+ elif "| None" in head:
110
+ head = head.split("|", 1)[0].strip()
111
+ if head == "float":
112
+ return float
113
+ if head == "int":
114
+ return int
115
+ return None
116
+
117
+ # Real type objects.
118
+ # Annotated[T, ...] - the underlying type is in __origin__'s arg list,
119
+ # but typing.get_args() works for both real Annotated and Union too.
120
+ try:
121
+ from typing import Annotated, get_args, get_origin
122
+ origin = get_origin(annotation)
123
+ if origin is Annotated:
124
+ # First arg is the underlying type; rest are metadata.
125
+ args = get_args(annotation)
126
+ if args:
127
+ return PlanToolsAgent._numeric_target_type(args[0])
128
+ except Exception:
129
+ origin = getattr(annotation, "__origin__", None)
130
+
131
+ # Optional[T] / Union[T, None]
132
+ if origin is Union:
133
+ args = getattr(annotation, "__args__", ())
134
+ non_none = [a for a in args if a is not type(None)]
135
+ if len(non_none) == 1:
136
+ return PlanToolsAgent._numeric_target_type(non_none[0])
137
+
138
+ if annotation is float:
139
+ return float
140
+ if annotation is int:
141
+ return int
142
+ return None
143
+
144
+ def _resolve_plan_params(
145
+ self, plan_info: Any, params: dict[str, Any]
146
+ ) -> dict[str, Any]:
147
+ """Resolve string device names to actual ophyd device objects.
148
+
149
+ Inspects plan parameters and resolves string device names
150
+ via the DeviceCatalog. Parameters whose type annotation is
151
+ ``str`` are left untouched — they are data-field names, not
152
+ device references (e.g. ``target_field`` in adaptive / tune
153
+ plans).
154
+
155
+ Args:
156
+ plan_info: PlanInfo with parameter metadata.
157
+ params: Raw parameters dict (device names as strings).
158
+
159
+ Returns:
160
+ Dict with device strings replaced by ophyd device objects.
161
+ """
162
+ resolved = dict(params)
163
+
164
+ try:
165
+ catalog = self._get_catalog()
166
+ except Exception:
167
+ return resolved
168
+
169
+ for p_info in plan_info.parameters:
170
+ if p_info.name not in resolved:
171
+ continue
172
+
173
+ # Skip parameters annotated as plain str — they are field
174
+ # names, not device names (e.g. target_field for tune/adaptive).
175
+ if self._is_str_annotation(p_info.annotation):
176
+ continue
177
+
178
+ val = resolved[p_info.name]
179
+
180
+ # Coerce JSON ints to Python floats for parameters annotated as
181
+ # float. The MCP wire format encodes JSON numbers without a
182
+ # type tag, so ``{"start": -5}`` decodes as ``int``. Passing an
183
+ # int through ``mv(motor, -5)`` leaves the ophyd-fakes
184
+ # setpoint sim_state as a Python int, ``describe()`` reports
185
+ # ``dtype="integer"``, the Tiled SQL column is baked as
186
+ # int64, and the first fractional scan position raises
187
+ # ``ArrowInvalid: Float value … was truncated converting to
188
+ # int64`` mid-run.
189
+ if (
190
+ isinstance(val, (int, float))
191
+ and not isinstance(val, bool)
192
+ and self._numeric_target_type(p_info.annotation) is float
193
+ and not isinstance(val, float)
194
+ ):
195
+ resolved[p_info.name] = float(val)
196
+ continue
197
+
198
+ # List of strings → resolve each as a device
199
+ if isinstance(val, list) and all(isinstance(v, str) for v in val):
200
+ devices = []
201
+ for dev_name in val:
202
+ dev = catalog.get_ophyd_device(dev_name)
203
+ if dev is None:
204
+ raise ValueError(f"Device '{dev_name}' not found in catalog")
205
+ devices.append(dev)
206
+ resolved[p_info.name] = devices
207
+ elif isinstance(val, str):
208
+ # Try to resolve as a device; if not found, leave as string
209
+ dev = catalog.get_ophyd_device(val)
210
+ if dev is not None:
211
+ resolved[p_info.name] = dev
212
+
213
+ return resolved
214
+
215
+ def _validate_plan_code(self, code: str, name: str) -> tuple[bool, str | None]:
216
+ """Validate plan code without writing to disk.
217
+
218
+ Performs in-memory validation:
219
+ 1. Syntax check via compile()
220
+ 2. Execution in isolated namespace to check imports
221
+ 3. Verify 'plan' callable exists
222
+ 4. Verify 'plan' is a generator function
223
+
224
+ Args:
225
+ code: Python source code for the plan.
226
+ name: Plan name (for error messages).
227
+
228
+ Returns:
229
+ Tuple of (is_valid, error_message). error_message is None if valid.
230
+ """
231
+ # 1. Syntax check
232
+ try:
233
+ compile(code, f"{name}.py", "exec")
234
+ except SyntaxError as e:
235
+ return False, f"Syntax error at line {e.lineno}: {e.msg}"
236
+
237
+ # 2. Execute in isolated namespace to check for import errors
238
+ namespace: dict[str, Any] = {}
239
+ try:
240
+ exec(code, namespace)
241
+ except Exception as e:
242
+ return False, f"Execution error: {type(e).__name__}: {e}"
243
+
244
+ # 3. Check for 'plan' callable
245
+ if "plan" not in namespace:
246
+ return False, "Missing required 'plan' function"
247
+
248
+ if not callable(namespace["plan"]):
249
+ return False, "'plan' must be a callable (function)"
250
+
251
+ # 4. Check it's a generator function
252
+ if not inspect.isgeneratorfunction(namespace["plan"]):
253
+ return False, "'plan' must be a generator function (use 'yield from')"
254
+
255
+ return True, None
256
+
257
+ def create_tools(self) -> list[Any]:
258
+ """Create plan management MCP tools.
259
+
260
+ Returns:
261
+ List of tool functions.
262
+ """
263
+ try:
264
+ from claude_agent_sdk import tool
265
+ except ImportError:
266
+ logger.warning("claude_agent_sdk not available, plan tools disabled")
267
+ return []
268
+
269
+ @tool(
270
+ name="lightfall_create_user_plan",
271
+ description="""Create a Lightfall user plan from Python code.
272
+
273
+ A valid Lightfall plan file must:
274
+ - Be valid Python syntax
275
+ - Export a callable named `plan` (generator function)
276
+ - Include a module docstring describing the plan
277
+ - Use proper type hints for UI widget generation (see below)
278
+
279
+ ## Type Hints for UI Generation
280
+
281
+ Lightfall auto-generates parameter UI from type hints. Use `typing.Annotated` with
282
+ annotations from `lightfall.ui.annotations` for proper device selection widgets.
283
+
284
+ ### Required imports:
285
+ ```python
286
+ from __future__ import annotations
287
+ from typing import Annotated, Any, Generator
288
+ import bluesky.plans as bp
289
+ from lightfall.ui.annotations import DeviceFilter, DeviceDefault, Unit, Decimals, Range
290
+ ```
291
+
292
+ ### Device Parameters (IMPORTANT for device selection UI):
293
+
294
+ Single device (motor/positioner) - use parameter name OR DeviceFilter:
295
+ ```python
296
+ motor: Annotated[Any, DeviceFilter(category="motor")]
297
+ # Or with pre-selection:
298
+ motor: Annotated[Any, DeviceFilter(category="motor"), DeviceDefault("sample_x")]
299
+ ```
300
+
301
+ Multiple devices (detectors) - use list type:
302
+ ```python
303
+ detectors: Annotated[list[Any], DeviceFilter(category="detector")]
304
+ # Or filter by device class:
305
+ detectors: Annotated[list[Any], DeviceFilter(device_class="AreaDetector")]
306
+ ```
307
+
308
+ DeviceFilter options:
309
+ - category: "motor", "detector", "sensor", "positioner", etc.
310
+ - device_class: specific class like "EpicsMotor", "AreaDetector"
311
+ - group: tag group like "areadetectors"
312
+ - name_pattern: regex pattern for device names
313
+
314
+ ### Numeric Parameters (for formatted input):
315
+ ```python
316
+ energy: Annotated[float, Unit("eV")]
317
+ position: Annotated[float, Unit("mm"), Decimals(3)]
318
+ num_points: Annotated[int, Range(min=1, max=1000)]
319
+ exposure: Annotated[float, Unit("s"), Range(min=0.001, max=60.0)] = 1.0
320
+ ```
321
+
322
+ ### Complete Example:
323
+ ```python
324
+ \"\"\"grid_scan - 2D grid scan with detector.\"\"\"
325
+ from __future__ import annotations
326
+ from typing import Annotated, Any, Generator
327
+ import bluesky.plans as bp
328
+ from lightfall.ui.annotations import DeviceFilter, DeviceDefault, Unit, Range
329
+
330
+ def plan(
331
+ detectors: Annotated[list[Any], DeviceFilter(category="detector")],
332
+ motor_x: Annotated[Any, DeviceFilter(category="motor")],
333
+ motor_y: Annotated[Any, DeviceFilter(category="motor")],
334
+ x_start: Annotated[float, Unit("mm")] = -5.0,
335
+ x_stop: Annotated[float, Unit("mm")] = 5.0,
336
+ y_start: Annotated[float, Unit("mm")] = -5.0,
337
+ y_stop: Annotated[float, Unit("mm")] = 5.0,
338
+ num_x: Annotated[int, Range(min=1, max=100)] = 10,
339
+ num_y: Annotated[int, Range(min=1, max=100)] = 10,
340
+ ) -> Generator[Any, Any, Any]:
341
+ \"\"\"Perform a 2D grid scan.
342
+
343
+ Args:
344
+ detectors: Detectors to read at each point.
345
+ motor_x: Motor for X axis.
346
+ motor_y: Motor for Y axis.
347
+ x_start: X axis start position.
348
+ x_stop: X axis end position.
349
+ y_start: Y axis start position.
350
+ y_stop: Y axis end position.
351
+ num_x: Number of X points.
352
+ num_y: Number of Y points.
353
+ \"\"\"
354
+ yield from bp.grid_scan(detectors, motor_y, y_start, y_stop, num_y,
355
+ motor_x, x_start, x_stop, num_x)
356
+ ```
357
+
358
+ Plans are saved to ~/lightfall/plans/ and immediately available in the Plan Runner.""",
359
+ input_schema={
360
+ "type": "object",
361
+ "properties": {
362
+ "name": {
363
+ "type": "string",
364
+ "description": "Plan name (becomes filename, e.g., 'my_scan' -> my_scan.py). Must be a valid Python identifier.",
365
+ },
366
+ "code": {
367
+ "type": "string",
368
+ "description": "Complete Python source code for the plan file",
369
+ },
370
+ "description": {
371
+ "type": "string",
372
+ "description": "Brief description of what the plan does (for logging/confirmation)",
373
+ },
374
+ "overwrite": {
375
+ "type": "boolean",
376
+ "description": "If true, overwrite existing plan with same name. Default: false",
377
+ "default": False,
378
+ },
379
+ },
380
+ "required": ["name", "code", "description"],
381
+ },
382
+ )
383
+ async def create_user_plan(args: dict) -> dict[str, Any]:
384
+ """Create a user plan from Python code."""
385
+ from lightfall.acquire.plans.user_plans import UserPlanService
386
+
387
+ name = args["name"]
388
+ code = args["code"]
389
+ description = args["description"]
390
+ overwrite = args.get("overwrite", False)
391
+
392
+ # Validate name is a valid Python identifier
393
+ if not re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", name):
394
+ return {
395
+ "success": False,
396
+ "error": "Invalid plan name. Must be a valid Python identifier "
397
+ "(letters, numbers, underscore; must start with letter or underscore).",
398
+ }
399
+
400
+ # Validate code in-memory before writing
401
+ is_valid, error = self._validate_plan_code(code, name)
402
+ if not is_valid:
403
+ return {
404
+ "success": False,
405
+ "error": error,
406
+ }
407
+
408
+ # Get plans directory from UserPlanService
409
+ try:
410
+ service = UserPlanService.get_instance()
411
+ plans_dir = service.get_plans_directory()
412
+ except Exception as e:
413
+ logger.error("Failed to get UserPlanService: {}", e)
414
+ return {
415
+ "success": False,
416
+ "error": f"Failed to access user plans service: {e}",
417
+ }
418
+
419
+ file_path = plans_dir / f"{name}.py"
420
+
421
+ # Check for existing file
422
+ if file_path.exists() and not overwrite:
423
+ return {
424
+ "success": False,
425
+ "error": f"Plan '{name}' already exists. Set overwrite=true to replace it.",
426
+ }
427
+
428
+ # Write the file
429
+ try:
430
+ file_path.write_text(code, encoding="utf-8")
431
+ except Exception as e:
432
+ logger.error("Failed to write plan file {}: {}", file_path, e)
433
+ return {
434
+ "success": False,
435
+ "error": f"Failed to write plan file: {e}",
436
+ }
437
+
438
+ # The UserPlanService's file watcher will auto-detect and load the plan.
439
+ # We can also explicitly trigger a load to ensure it's available immediately.
440
+ try:
441
+ # description is required by input_schema, but the guard handles
442
+ # direct calls (e.g., from unit tests) that may pass ""
443
+ commit_msg = f"agent: {description}" if description else None
444
+ service.load_plan_from_file(file_path, commit_msg=commit_msg)
445
+ except Exception as e:
446
+ logger.warning("Plan file written but failed to load: {}", e)
447
+ # File was written successfully, so we return success
448
+ # The file watcher should pick it up eventually
449
+
450
+ logger.info(
451
+ "Created user plan '{}': {} (overwrite={})",
452
+ name,
453
+ description,
454
+ overwrite,
455
+ )
456
+
457
+ return {
458
+ "success": True,
459
+ "message": f"Plan '{name}' created successfully",
460
+ "path": str(file_path),
461
+ "description": description,
462
+ }
463
+
464
+ @tool(
465
+ name="lightfall_list_plans",
466
+ description="""List all registered plans available in the Lightfall plan registry.
467
+
468
+ Returns plan names, categories, descriptions, and parameter signatures.
469
+ Use this to discover what plans are available before running one with lightfall_run_plan.
470
+
471
+ Optionally filter by category (e.g., "scan", "count", "alignment", "user").""",
472
+ input_schema={
473
+ "type": "object",
474
+ "properties": {
475
+ "category": {
476
+ "type": "string",
477
+ "description": "Optional category filter (e.g., 'scan', 'count', 'alignment', 'user', 'general')",
478
+ },
479
+ },
480
+ },
481
+ )
482
+ async def list_plans(args: dict) -> dict[str, Any]:
483
+ """List all registered plans."""
484
+ import json
485
+
486
+ from lightfall.acquire.plans.registry import get_registry
487
+
488
+ registry = get_registry()
489
+ category = args.get("category")
490
+ plans = registry.list_plans(category=category)
491
+
492
+ result = []
493
+ for plan_info in plans:
494
+ params = []
495
+ for p in plan_info.parameters:
496
+ param = {
497
+ "name": p.name,
498
+ "type": p.type_name,
499
+ "required": p.required,
500
+ }
501
+ if p.description:
502
+ param["description"] = p.description
503
+ if not p.required and p.default is not inspect.Parameter.empty:
504
+ param["default"] = repr(p.default)
505
+ params.append(param)
506
+
507
+ result.append({
508
+ "name": plan_info.name,
509
+ "display_name": plan_info.get_display_name(),
510
+ "category": plan_info.category,
511
+ "description": plan_info.description,
512
+ "parameters": params,
513
+ })
514
+
515
+ return {
516
+ "content": [{
517
+ "type": "text",
518
+ "text": json.dumps({"plans": result, "total": len(result)}, indent=2),
519
+ }]
520
+ }
521
+
522
+ @tool(
523
+ name="lightfall_run_plan",
524
+ description="""Run a registered plan from the Lightfall plan registry by name.
525
+
526
+ Use lightfall_list_plans first to see available plans and their parameters.
527
+ The plan is submitted to the RunEngine queue and executed asynchronously.
528
+
529
+ Parameters are passed as a JSON object. Device parameters should use device
530
+ names as strings — they will be resolved from the device registry automatically.
531
+
532
+ Example:
533
+ lightfall_run_plan(plan_name="scan", params={"detectors": ["det1"], "motor": "motor1", "start": -5, "stop": 5, "num": 21})
534
+ lightfall_run_plan(plan_name="count", params={"detectors": ["det1"], "num": 5, "delay": 1.0})""",
535
+ input_schema={
536
+ "type": "object",
537
+ "properties": {
538
+ "plan_name": {
539
+ "type": "string",
540
+ "description": "Name of the registered plan to run (e.g., 'scan', 'count', 'rel_scan')",
541
+ },
542
+ "params": {
543
+ "type": "object",
544
+ "description": "Parameters to pass to the plan function. Device names (strings) are resolved automatically.",
545
+ },
546
+ },
547
+ "required": ["plan_name"],
548
+ },
549
+ )
550
+ async def run_plan(args: dict) -> dict[str, Any]:
551
+ """Run a registered plan by name."""
552
+ import json
553
+
554
+ from lightfall.acquire.engine import get_engine
555
+ from lightfall.acquire.plans.registry import get_registry
556
+
557
+ plan_name = args["plan_name"]
558
+ params = args.get("params", {})
559
+
560
+ # Look up the plan
561
+ registry = get_registry()
562
+ plan_info = registry.get_plan(plan_name)
563
+ if plan_info is None:
564
+ available = registry.plan_names
565
+ return {
566
+ "content": [{
567
+ "type": "text",
568
+ "text": json.dumps({
569
+ "success": False,
570
+ "error": f"Plan '{plan_name}' not found",
571
+ "available_plans": available,
572
+ }),
573
+ }],
574
+ "is_error": True,
575
+ }
576
+
577
+ # Resolve device names to device objects
578
+ resolved_params = {}
579
+ try:
580
+ resolved_params = self._resolve_plan_params(plan_info, params)
581
+ except Exception as e:
582
+ return {
583
+ "content": [{
584
+ "type": "text",
585
+ "text": json.dumps({
586
+ "success": False,
587
+ "error": f"Parameter resolution error: {e}",
588
+ }),
589
+ }],
590
+ "is_error": True,
591
+ }
592
+
593
+ # Create the plan generator and submit
594
+ try:
595
+ engine = get_engine()
596
+ plan_generator = plan_info.func(**resolved_params)
597
+ proc_id = engine.submit(plan_generator, name=plan_name, skip_pre_submit=True)
598
+ return {
599
+ "content": [{
600
+ "type": "text",
601
+ "text": json.dumps({
602
+ "success": True,
603
+ "message": f"Plan '{plan_name}' submitted to RunEngine",
604
+ "procedure_id": proc_id,
605
+ "engine_state": engine.state_name,
606
+ }),
607
+ }]
608
+ }
609
+ except Exception as e:
610
+ logger.error("Failed to submit plan '{}': {}", plan_name, e)
611
+ return {
612
+ "content": [{
613
+ "type": "text",
614
+ "text": json.dumps({
615
+ "success": False,
616
+ "error": f"Failed to submit plan: {e}",
617
+ }),
618
+ }],
619
+ "is_error": True,
620
+ }
621
+
622
+ @tool(
623
+ name="lightfall_run_plan_code",
624
+ description="""Run arbitrary Python code as a Bluesky plan in the Lightfall RunEngine.
625
+
626
+ The code string is executed in an isolated namespace with common imports available.
627
+ The code MUST define a generator (using yield from) that produces Bluesky messages.
628
+
629
+ The code is wrapped in a function and executed — you write the body of a generator function.
630
+
631
+ Pre-imported in the execution namespace:
632
+ - bluesky.plans as bp
633
+ - bluesky.plan_stubs as bps
634
+ - All devices from the device registry (by name)
635
+ - numpy as np
636
+
637
+ Example code strings:
638
+ "yield from bp.scan([det], motor1, -5, 5, 21)"
639
+ "yield from bp.count([det], num=5, delay=1.0)"
640
+ "for i in range(3):\\n yield from bp.scan([det], motor1, -i, i, 11)"
641
+
642
+ WARNING: This executes arbitrary code in the RunEngine context. Use with caution.""",
643
+ input_schema={
644
+ "type": "object",
645
+ "properties": {
646
+ "code": {
647
+ "type": "string",
648
+ "description": "Python code string that yields Bluesky plan messages. Written as the body of a generator function.",
649
+ },
650
+ "description": {
651
+ "type": "string",
652
+ "description": "Brief description of what this plan does (for logging and queue display)",
653
+ },
654
+ },
655
+ "required": ["code"],
656
+ },
657
+ )
658
+ async def run_plan_code(args: dict) -> dict[str, Any]:
659
+ """Run arbitrary code as a Bluesky plan."""
660
+ import json
661
+ import textwrap
662
+
663
+ from lightfall.acquire.engine import get_engine
664
+
665
+ code = args["code"]
666
+ description = args.get("description", "ad-hoc plan")
667
+
668
+ # Build the execution namespace with common imports
669
+ namespace: dict[str, Any] = {}
670
+ try:
671
+ import numpy as np
672
+ namespace["np"] = np
673
+ namespace["numpy"] = np
674
+ except ImportError:
675
+ pass
676
+
677
+ try:
678
+ import bluesky.plan_stubs as bps
679
+ import bluesky.plans as bp
680
+ namespace["bp"] = bp
681
+ namespace["bps"] = bps
682
+ except ImportError:
683
+ return {
684
+ "content": [{
685
+ "type": "text",
686
+ "text": json.dumps({
687
+ "success": False,
688
+ "error": "bluesky is not installed",
689
+ }),
690
+ }],
691
+ "is_error": True,
692
+ }
693
+
694
+ # Inject all ophyd devices from the device catalog
695
+ try:
696
+ catalog = self._get_catalog()
697
+ for dev_name, dev_obj in catalog.get_all_ophyd_devices().items():
698
+ namespace[dev_name] = dev_obj
699
+ except Exception as e:
700
+ logger.debug("Could not inject devices into namespace: {}", e)
701
+
702
+ # Wrap user code in a generator function
703
+ indented_code = textwrap.indent(code, " ")
704
+ wrapper = f"def _plan():\n{indented_code}\n"
705
+
706
+ # Compile and execute to define the function
707
+ try:
708
+ compiled = compile(wrapper, "<plan_code>", "exec")
709
+ exec(compiled, namespace)
710
+ except SyntaxError as e:
711
+ return {
712
+ "content": [{
713
+ "type": "text",
714
+ "text": json.dumps({
715
+ "success": False,
716
+ "error": f"Syntax error at line {e.lineno}: {e.msg}",
717
+ }),
718
+ }],
719
+ "is_error": True,
720
+ }
721
+ except Exception as e:
722
+ return {
723
+ "content": [{
724
+ "type": "text",
725
+ "text": json.dumps({
726
+ "success": False,
727
+ "error": f"Code execution error: {type(e).__name__}: {e}",
728
+ }),
729
+ }],
730
+ "is_error": True,
731
+ }
732
+
733
+ # Get the plan generator
734
+ plan_func = namespace.get("_plan")
735
+ if plan_func is None:
736
+ return {
737
+ "content": [{
738
+ "type": "text",
739
+ "text": json.dumps({
740
+ "success": False,
741
+ "error": "Internal error: plan function not created",
742
+ }),
743
+ }],
744
+ "is_error": True,
745
+ }
746
+
747
+ # Submit to engine
748
+ try:
749
+ engine = get_engine()
750
+ plan_generator = plan_func()
751
+ proc_id = engine.submit(plan_generator, name=description, skip_pre_submit=True)
752
+ return {
753
+ "content": [{
754
+ "type": "text",
755
+ "text": json.dumps({
756
+ "success": True,
757
+ "message": f"Plan '{description}' submitted to RunEngine",
758
+ "procedure_id": proc_id,
759
+ "engine_state": engine.state_name,
760
+ }),
761
+ }]
762
+ }
763
+ except Exception as e:
764
+ logger.error("Failed to submit plan code: {}", e)
765
+ return {
766
+ "content": [{
767
+ "type": "text",
768
+ "text": json.dumps({
769
+ "success": False,
770
+ "error": f"Failed to submit plan: {e}",
771
+ }),
772
+ }],
773
+ "is_error": True,
774
+ }
775
+
776
+ @tool(
777
+ name="lightfall_get_user_plan",
778
+ description="Read the source code of a user plan by name.",
779
+ input_schema={
780
+ "type": "object",
781
+ "properties": {
782
+ "name": {
783
+ "type": "string",
784
+ "description": "Plan name (without .py extension)",
785
+ },
786
+ },
787
+ "required": ["name"],
788
+ },
789
+ )
790
+ async def get_user_plan(args: dict) -> dict[str, Any]:
791
+ """Read source code of a user plan."""
792
+ from lightfall.acquire.plans.user_plans import UserPlanService
793
+ from lightfall.plugins.agents._mcp_helpers import mcp_result
794
+
795
+ name = args["name"]
796
+
797
+ try:
798
+ service = UserPlanService.get_instance()
799
+ plans_dir = service.get_plans_directory()
800
+ except Exception as e:
801
+ return mcp_result({"success": False, "error": f"Failed to access user plans service: {e}"}, is_error=True)
802
+
803
+ file_path = plans_dir / f"{name}.py"
804
+ if not file_path.exists():
805
+ return mcp_result({"success": False, "error": f"Plan '{name}' not found at {file_path}"}, is_error=True)
806
+
807
+ try:
808
+ code = file_path.read_text(encoding="utf-8")
809
+ return mcp_result({
810
+ "success": True,
811
+ "name": name,
812
+ "path": str(file_path),
813
+ "code": code,
814
+ })
815
+ except Exception as e:
816
+ return mcp_result({"success": False, "error": f"Failed to read plan: {e}"}, is_error=True)
817
+
818
+ @tool(
819
+ name="lightfall_delete_user_plan",
820
+ description="Delete a user plan by name. Requires confirm=true.",
821
+ input_schema={
822
+ "type": "object",
823
+ "properties": {
824
+ "name": {
825
+ "type": "string",
826
+ "description": "Plan name (without .py extension)",
827
+ },
828
+ "confirm": {
829
+ "type": "boolean",
830
+ "description": "Must be true to confirm deletion",
831
+ },
832
+ },
833
+ "required": ["name", "confirm"],
834
+ },
835
+ )
836
+ async def delete_user_plan(args: dict) -> dict[str, Any]:
837
+ """Delete a user plan."""
838
+ from lightfall.acquire.plans.user_plans import UserPlanService
839
+ from lightfall.plugins.agents._mcp_helpers import mcp_result
840
+
841
+ name = args["name"]
842
+ confirm = args.get("confirm", False)
843
+
844
+ if not confirm:
845
+ return mcp_result({"success": False, "error": "Deletion not confirmed. Set confirm=true to delete."}, is_error=True)
846
+
847
+ try:
848
+ service = UserPlanService.get_instance()
849
+ plans_dir = service.get_plans_directory()
850
+ except Exception as e:
851
+ return mcp_result({"success": False, "error": f"Failed to access user plans service: {e}"}, is_error=True)
852
+
853
+ file_path = plans_dir / f"{name}.py"
854
+ if not file_path.exists():
855
+ return mcp_result({"success": False, "error": f"Plan '{name}' not found at {file_path}"}, is_error=True)
856
+
857
+ try:
858
+ # Unload from the registry BEFORE removing the file so that
859
+ # lightfall_list_plans / lightfall_run_plan don't briefly see a stale
860
+ # entry in the window between unlink() and the watcher's
861
+ # _on_file_changed callback. The watcher will fire later as
862
+ # a no-op (plan already unloaded; commit_removal is a no-op
863
+ # via `git diff --cached --quiet`).
864
+ service._unload_plan(name)
865
+ file_path.unlink()
866
+ GitTracker.get_instance().commit_removal(
867
+ [file_path], f"agent: delete plan {name}"
868
+ )
869
+ logger.info("Deleted user plan '{}'", name)
870
+ return mcp_result({
871
+ "success": True,
872
+ "message": f"Plan '{name}' deleted",
873
+ "path": str(file_path),
874
+ })
875
+ except Exception as e:
876
+ return mcp_result({"success": False, "error": f"Failed to delete plan: {e}"}, is_error=True)
877
+
878
+ return [create_user_plan, list_plans, run_plan, run_plan_code, get_user_plan, delete_user_plan]