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
+ """Plugin loader with background threading.
2
+
3
+ The PluginLoader discovers plugin manifests via entry points, loads plugin
4
+ classes in a background thread, and instantiates them. It uses Qt threading
5
+ integration for non-blocking operation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib
11
+ import time
12
+ from collections import deque
13
+ from collections.abc import Generator
14
+ from datetime import datetime
15
+ from importlib.metadata import entry_points
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ from loguru import logger
19
+ from PySide6.QtCore import QObject, Signal
20
+ from PySide6.QtWidgets import QApplication
21
+
22
+ from lightfall.plugins.errors import (
23
+ PluginInitError,
24
+ PluginLoadError,
25
+ PluginNotFoundError,
26
+ PluginStatus,
27
+ )
28
+ from lightfall.plugins.info import PluginInfo
29
+ from lightfall.plugins.manifest import PluginManifest
30
+ from lightfall.plugins.registry import PluginRegistry
31
+ from lightfall.plugins.types import PluginType
32
+ from lightfall.utils.threads import (
33
+ QThreadFutureIterator,
34
+ initialize_main_thread_invoker,
35
+ invoke_in_main_thread,
36
+ is_main_thread,
37
+ )
38
+
39
+ if TYPE_CHECKING:
40
+ pass
41
+
42
+
43
+ class PluginLoader(QObject):
44
+ """Loads plugins from manifests with background threading.
45
+
46
+ The loader discovers plugin manifests via entry points, loads plugin
47
+ classes in a background thread, and instantiates them. It addresses
48
+ common issues from Xi-CAM:
49
+
50
+ 1. Duplicate detection: Uses unique IDs (type:name) tracked in registry
51
+ 2. Graceful failure: Catches exceptions, marks plugins as failed
52
+ 3. Background loading: Non-blocking loading via QThreadFutureIterator
53
+ 4. Priority loading: get_plugin_by_name() loads immediately if needed
54
+
55
+ Signals:
56
+ plugin_loaded: Emitted when a plugin is ready (PluginInfo).
57
+ plugin_failed: Emitted when a plugin fails to load (PluginInfo).
58
+ loading_started: Emitted when background loading begins.
59
+ loading_complete: Emitted when loading finishes (successful, failed).
60
+
61
+ Example::
62
+
63
+ loader = PluginLoader(registry)
64
+ loader.register_plugin_type("plan", PlanPlugin)
65
+ loader.discover_manifests()
66
+ loader.start_loading()
67
+ loader.loading_complete.connect(on_plugins_ready)
68
+ """
69
+
70
+ ENTRY_POINT_GROUP = "lightfall.plugins"
71
+
72
+ # Signals
73
+ plugin_loaded = Signal(object) # PluginInfo
74
+ plugin_failed = Signal(object) # PluginInfo
75
+ loading_started = Signal()
76
+ loading_complete = Signal(int, int) # successful, failed
77
+
78
+ def __init__(
79
+ self,
80
+ registry: PluginRegistry | None = None,
81
+ parent: QObject | None = None,
82
+ ) -> None:
83
+ """Initialize the plugin loader.
84
+
85
+ Args:
86
+ registry: Plugin registry. Creates a new one if not provided.
87
+ parent: Qt parent object.
88
+ """
89
+ super().__init__(parent)
90
+ self._registry = registry or PluginRegistry()
91
+ self._plugin_types: dict[str, type[PluginType]] = {}
92
+
93
+ # Queues for two-phase loading
94
+ self._load_queue: deque[PluginInfo] = deque()
95
+ self._init_queue: deque[PluginInfo] = deque()
96
+
97
+ # Track what's being processed to detect cycles
98
+ self._loading: set[str] = set()
99
+ self._initializing: set[str] = set()
100
+
101
+ # Background loading state
102
+ self._worker: QThreadFutureIterator | None = None
103
+ self._is_loading = False
104
+
105
+ # Counters
106
+ self._successful = 0
107
+ self._failed = 0
108
+
109
+ @property
110
+ def registry(self) -> PluginRegistry:
111
+ """Get the plugin registry."""
112
+ return self._registry
113
+
114
+ @property
115
+ def is_loading(self) -> bool:
116
+ """Check if background loading is in progress."""
117
+ return self._is_loading
118
+
119
+ def register_plugin_type(
120
+ self,
121
+ type_name: str,
122
+ plugin_type_class: type[PluginType],
123
+ ) -> None:
124
+ """Register a plugin type.
125
+
126
+ Args:
127
+ type_name: Unique type identifier (e.g., "plan").
128
+ plugin_type_class: The PluginType subclass.
129
+ """
130
+ self._plugin_types[type_name] = plugin_type_class
131
+ logger.debug("Registered plugin type: {}", type_name)
132
+
133
+ def get_plugin_type(self, type_name: str) -> type[PluginType] | None:
134
+ """Get a registered plugin type class.
135
+
136
+ Args:
137
+ type_name: The type identifier.
138
+
139
+ Returns:
140
+ The PluginType subclass or None.
141
+ """
142
+ return self._plugin_types.get(type_name)
143
+
144
+ def discover_manifests(self) -> int:
145
+ """Discover plugin manifests via entry points.
146
+
147
+ Entry point format in pyproject.toml::
148
+
149
+ [project.entry-points."lightfall.plugins"]
150
+ my_beamline = "my_plugin.manifest:manifest"
151
+
152
+ Returns:
153
+ Number of manifests discovered.
154
+ """
155
+ count = 0
156
+
157
+ try:
158
+ eps = entry_points(group=self.ENTRY_POINT_GROUP)
159
+ except TypeError:
160
+ # Fallback for older Python
161
+ all_eps = entry_points()
162
+ eps = all_eps.get(self.ENTRY_POINT_GROUP, [])
163
+
164
+ for ep in eps:
165
+ try:
166
+ manifest = ep.load()
167
+ if isinstance(manifest, PluginManifest):
168
+ self._process_manifest(manifest)
169
+ count += 1
170
+ logger.info(
171
+ "Discovered manifest '{}' with {} plugins from {}",
172
+ manifest.name,
173
+ len(manifest.plugins),
174
+ ep.value,
175
+ )
176
+ else:
177
+ logger.warning(
178
+ "Entry point {} does not provide a PluginManifest, got {}",
179
+ ep.name,
180
+ type(manifest).__name__,
181
+ )
182
+ except Exception as e:
183
+ logger.error(
184
+ "Failed to load manifest from entry point {}: {}",
185
+ ep.name,
186
+ e,
187
+ )
188
+
189
+ logger.info("Discovered {} plugin manifest(s)", count)
190
+ return count
191
+
192
+ def load_manifest(self, manifest: PluginManifest) -> None:
193
+ """Load plugins from a manifest directly (not via entry point).
194
+
195
+ Args:
196
+ manifest: The manifest to load.
197
+ """
198
+ self._process_manifest(manifest)
199
+
200
+ def _get_disabled_plugin_ids(self) -> set[str]:
201
+ """Get the set of disabled plugin IDs from preferences.
202
+
203
+ Returns:
204
+ Set of unique_id strings for disabled plugins.
205
+ """
206
+ try:
207
+ from lightfall.ui.preferences.manager import PreferencesManager
208
+
209
+ prefs = PreferencesManager.get_instance()
210
+ disabled_list = prefs.get("disabled_plugins", [])
211
+ if isinstance(disabled_list, list):
212
+ return set(disabled_list)
213
+ except Exception as e:
214
+ logger.debug("Could not load disabled plugins preference: {}", e)
215
+ return set()
216
+
217
+ def _process_manifest(self, manifest: PluginManifest) -> None:
218
+ """Process a manifest and queue its plugins.
219
+
220
+ Args:
221
+ manifest: The manifest to process.
222
+ """
223
+ disabled_ids = self._get_disabled_plugin_ids()
224
+
225
+ for entry in manifest.plugins:
226
+ # Check if this type is known
227
+ if entry.type_name not in self._plugin_types:
228
+ logger.warning(
229
+ "Unknown plugin type '{}' for plugin '{}', skipping",
230
+ entry.type_name,
231
+ entry.name,
232
+ )
233
+ continue
234
+
235
+ # Create PluginInfo
236
+ plugin_info = PluginInfo(
237
+ type_name=entry.type_name,
238
+ name=entry.name,
239
+ import_path=entry.import_path,
240
+ manifest_name=manifest.name,
241
+ status=PluginStatus.DISCOVERED,
242
+ preload=entry.preload,
243
+ )
244
+
245
+ # Try to register (checks for duplicates)
246
+ if self._registry.register(plugin_info):
247
+ # Check if this plugin is disabled (but never disable settings:plugins)
248
+ if (
249
+ plugin_info.unique_id in disabled_ids
250
+ and plugin_info.unique_id != "settings:plugins"
251
+ ):
252
+ plugin_info.status = PluginStatus.DISABLED
253
+ logger.info(
254
+ "Plugin '{}' is disabled, not loading",
255
+ plugin_info.unique_id,
256
+ )
257
+ else:
258
+ self._load_queue.append(plugin_info)
259
+ plugin_info.status = PluginStatus.QUEUED_LOAD
260
+ logger.debug("Queued plugin for loading: {}", plugin_info.unique_id)
261
+
262
+ def load_preload_plugins(self) -> tuple[int, int]:
263
+ """Load all plugins marked with preload=True synchronously.
264
+
265
+ Call this BEFORE creating the main window to ensure preload plugins
266
+ (like appearance/theme) are ready before any UI is shown.
267
+
268
+ Returns:
269
+ Tuple of (successful_count, failed_count).
270
+
271
+ Example::
272
+
273
+ loader = PluginLoader(registry)
274
+ loader.register_plugin_type("settings", SettingsPlugin)
275
+ loader.load_manifest(builtin_manifest)
276
+ loader.discover_manifests()
277
+
278
+ # Load preload plugins before creating window
279
+ ok, failed = loader.load_preload_plugins()
280
+ logger.info("Preload plugins: {} ok, {} failed", ok, failed)
281
+
282
+ # NOW create main window (after theme is applied)
283
+ window = MainWindow()
284
+
285
+ # Start background loading for remaining plugins
286
+ loader.start_loading()
287
+ """
288
+ # Separate preload plugins from regular queue
289
+ preload_infos: list[PluginInfo] = []
290
+ remaining: deque[PluginInfo] = deque()
291
+
292
+ for info in self._load_queue:
293
+ if info.preload:
294
+ preload_infos.append(info)
295
+ else:
296
+ remaining.append(info)
297
+
298
+ self._load_queue = remaining
299
+
300
+ if not preload_infos:
301
+ logger.debug("No preload plugins to load")
302
+ return 0, 0
303
+
304
+ logger.info("Loading {} preload plugin(s) synchronously", len(preload_infos))
305
+
306
+ # Load preload plugins synchronously
307
+ successful = 0
308
+ failed = 0
309
+
310
+ for info in preload_infos:
311
+ if self._load_plugin_class(info):
312
+ if self._instantiate_plugin(info):
313
+ successful += 1
314
+ self._register_with_type_registry(info)
315
+ self.plugin_loaded.emit(info)
316
+
317
+ # Call on_loaded for immediate application (e.g., theme)
318
+ if hasattr(info.instance, "on_loaded"):
319
+ try:
320
+ info.instance.on_loaded()
321
+ logger.debug(
322
+ "Called on_loaded() for preload plugin: {}",
323
+ info.unique_id,
324
+ )
325
+ except Exception as e:
326
+ logger.error(
327
+ "Error in on_loaded() for {}: {}",
328
+ info.unique_id,
329
+ e,
330
+ )
331
+ else:
332
+ failed += 1
333
+ self.plugin_failed.emit(info)
334
+ else:
335
+ failed += 1
336
+ self.plugin_failed.emit(info)
337
+
338
+ logger.info(
339
+ "Preload plugin loading complete: {} successful, {} failed",
340
+ successful,
341
+ failed,
342
+ )
343
+ return successful, failed
344
+
345
+ def start_loading(self) -> None:
346
+ """Start background loading of queued plugins.
347
+
348
+ Emits loading_started and loading_complete signals.
349
+ """
350
+ if self._is_loading:
351
+ logger.warning("Plugin loading already in progress")
352
+ return
353
+
354
+ if not self._load_queue:
355
+ logger.info("No plugins to load")
356
+ self.loading_complete.emit(0, 0)
357
+ return
358
+
359
+ self._is_loading = True
360
+ self._successful = 0
361
+ self._failed = 0
362
+
363
+ self.loading_started.emit()
364
+ logger.info("Starting background plugin loading ({} plugins)", len(self._load_queue))
365
+
366
+ # Ensure threading invoker is initialized on main thread before
367
+ # background thread tries to use invoke_in_main_thread.
368
+ initialize_main_thread_invoker()
369
+
370
+ # Start background thread
371
+ self._worker = QThreadFutureIterator(
372
+ self._load_plugins_generator,
373
+ yield_slot=self._on_plugin_processed,
374
+ finished_slot=self._on_loading_finished,
375
+ except_slot=self._on_loading_error,
376
+ key="plugin_loader",
377
+ name="PluginLoader",
378
+ )
379
+ self._worker.start()
380
+
381
+ def _load_plugins_generator(self) -> Generator[PluginInfo, None, None]:
382
+ """Generator for background plugin loading.
383
+
384
+ Yields PluginInfo after each plugin is processed for progress updates.
385
+ """
386
+ # Phase 1: Load classes (import)
387
+ while self._load_queue:
388
+ plugin_info = self._load_queue.popleft()
389
+
390
+ success = self._load_plugin_class(plugin_info)
391
+ if success:
392
+ self._init_queue.append(plugin_info)
393
+ plugin_info.status = PluginStatus.QUEUED_INIT
394
+ else:
395
+ self._failed += 1
396
+
397
+ yield plugin_info
398
+
399
+ # Phase 2: Instantiate
400
+ while self._init_queue:
401
+ plugin_info = self._init_queue.popleft()
402
+
403
+ success = self._instantiate_plugin(plugin_info)
404
+ if success:
405
+ self._successful += 1
406
+ else:
407
+ self._failed += 1
408
+
409
+ yield plugin_info
410
+
411
+ def _on_plugin_processed(self, plugin_info: PluginInfo) -> None:
412
+ """Handle plugin processing completion (called in main thread).
413
+
414
+ Args:
415
+ plugin_info: The processed plugin.
416
+ """
417
+ if plugin_info.is_ready:
418
+ self.plugin_loaded.emit(plugin_info)
419
+ self._register_with_type_registry(plugin_info)
420
+ elif plugin_info.is_failed:
421
+ self.plugin_failed.emit(plugin_info)
422
+
423
+ def _on_loading_finished(self) -> None:
424
+ """Handle loading completion (called in main thread)."""
425
+ self._is_loading = False
426
+ self._worker = None
427
+ logger.info(
428
+ "Plugin loading complete: {} successful, {} failed",
429
+ self._successful,
430
+ self._failed,
431
+ )
432
+ self.loading_complete.emit(self._successful, self._failed)
433
+
434
+ def _on_loading_error(self, error: Exception) -> None:
435
+ """Handle loading error (called in main thread).
436
+
437
+ Args:
438
+ error: The exception that occurred.
439
+ """
440
+ self._is_loading = False
441
+ self._worker = None
442
+ logger.error("Plugin loading failed with error: {}", error)
443
+ self.loading_complete.emit(self._successful, self._failed)
444
+
445
+ def _load_plugin_class(self, plugin_info: PluginInfo) -> bool:
446
+ """Load a plugin class (import).
447
+
448
+ Args:
449
+ plugin_info: Plugin to load.
450
+
451
+ Returns:
452
+ True if successful.
453
+ """
454
+ unique_id = plugin_info.unique_id
455
+
456
+ # Check for circular dependency
457
+ if unique_id in self._loading:
458
+ logger.error(
459
+ "Circular dependency detected while loading {}",
460
+ unique_id,
461
+ )
462
+ plugin_info.status = PluginStatus.FAILED_LOAD
463
+ plugin_info.error = "Circular dependency"
464
+ return False
465
+
466
+ self._loading.add(unique_id)
467
+ plugin_info.status = PluginStatus.LOADING
468
+
469
+ try:
470
+ # Parse import path: "module.path:ClassName"
471
+ module_path, class_name = plugin_info.import_path.rsplit(":", 1)
472
+
473
+ logger.debug("Loading plugin class: {} from {}", class_name, module_path)
474
+
475
+ module = importlib.import_module(module_path)
476
+ plugin_class = getattr(module, class_name)
477
+
478
+ # Validate against plugin type
479
+ plugin_type_class = self._plugin_types[plugin_info.type_name]
480
+ if not plugin_type_class.validate_class(plugin_class):
481
+ raise TypeError(
482
+ f"{class_name} is not a valid {plugin_info.type_name} plugin"
483
+ )
484
+
485
+ plugin_info.plugin_class = plugin_class
486
+ plugin_info.load_time = datetime.now()
487
+
488
+ logger.debug("Loaded plugin class: {}", unique_id)
489
+ return True
490
+
491
+ except Exception as e:
492
+ logger.error("Failed to load plugin {}: {}", unique_id, e)
493
+ plugin_info.status = PluginStatus.FAILED_LOAD
494
+ plugin_info.error = str(e)
495
+ return False
496
+
497
+ finally:
498
+ self._loading.discard(unique_id)
499
+
500
+ def _instantiate_plugin(self, plugin_info: PluginInfo) -> bool:
501
+ """Instantiate a loaded plugin class.
502
+
503
+ Args:
504
+ plugin_info: Plugin to instantiate.
505
+
506
+ Returns:
507
+ True if successful.
508
+ """
509
+ unique_id = plugin_info.unique_id
510
+
511
+ # Check for circular instantiation
512
+ if unique_id in self._initializing:
513
+ logger.error(
514
+ "Circular dependency detected while instantiating {}",
515
+ unique_id,
516
+ )
517
+ plugin_info.status = PluginStatus.FAILED_INIT
518
+ plugin_info.error = "Circular instantiation"
519
+ return False
520
+
521
+ self._initializing.add(unique_id)
522
+ plugin_info.status = PluginStatus.INITIALIZING
523
+
524
+ try:
525
+ plugin_class = plugin_info.plugin_class
526
+ plugin_type_class = self._plugin_types[plugin_info.type_name]
527
+
528
+ # Instantiate if singleton, otherwise store class
529
+ if plugin_type_class.is_singleton:
530
+ logger.debug("Instantiating singleton plugin: {}", unique_id)
531
+ plugin_info.instance = plugin_class()
532
+ else:
533
+ # For non-singletons, store the class itself
534
+ plugin_info.instance = plugin_class
535
+
536
+ plugin_info.status = PluginStatus.READY
537
+
538
+ logger.info("Plugin ready: {}", unique_id)
539
+ return True
540
+
541
+ except Exception as e:
542
+ logger.error("Failed to instantiate plugin {}: {}", unique_id, e)
543
+ plugin_info.status = PluginStatus.FAILED_INIT
544
+ plugin_info.error = str(e)
545
+ return False
546
+
547
+ finally:
548
+ self._initializing.discard(unique_id)
549
+
550
+ def _register_with_type_registry(self, plugin_info: PluginInfo) -> None:
551
+ """Register plugin with type-specific registry.
552
+
553
+ For example, PlanPlugins get registered with PlanRegistry,
554
+ EnginePlugins get registered with EngineRegistry.
555
+
556
+ Args:
557
+ plugin_info: The ready plugin.
558
+ """
559
+ if plugin_info.type_name == "plan":
560
+ try:
561
+ from lightfall.acquire.plans.registry import PlanRegistry
562
+
563
+ plan_registry = PlanRegistry.get_instance()
564
+ plan_plugin = plugin_info.instance
565
+
566
+ if hasattr(plan_plugin, "get_plan_info"):
567
+ plan_info = plan_plugin.get_plan_info()
568
+ try:
569
+ plan_registry.register(
570
+ plan_info.name,
571
+ plan_info.func,
572
+ plan_info.category,
573
+ )
574
+ logger.debug(
575
+ "Registered plan '{}' with PlanRegistry",
576
+ plan_info.name,
577
+ )
578
+ except ValueError:
579
+ # Already registered
580
+ logger.warning(
581
+ "Plan '{}' already in PlanRegistry",
582
+ plan_info.name,
583
+ )
584
+ except ImportError:
585
+ logger.debug("PlanRegistry not available, skipping plan registration")
586
+
587
+ elif plugin_info.type_name == "engine":
588
+ try:
589
+ from lightfall.acquire.engine.registry import EngineRegistry
590
+
591
+ engine_registry = EngineRegistry.get_instance()
592
+ engine_plugin = plugin_info.instance
593
+
594
+ if hasattr(engine_plugin, "name"):
595
+ engine_registry.register(engine_plugin)
596
+ logger.debug(
597
+ "Registered engine '{}' with EngineRegistry",
598
+ engine_plugin.name,
599
+ )
600
+ except ImportError:
601
+ logger.debug("EngineRegistry not available, skipping engine registration")
602
+
603
+ elif plugin_info.type_name == "statusbar":
604
+ # Statusbar plugins don't need type-specific registration here.
605
+ # They are loaded by StatusBarManager when the main window is created.
606
+ logger.debug(
607
+ "Statusbar plugin '{}' registered, will be loaded by StatusBarManager",
608
+ plugin_info.name,
609
+ )
610
+
611
+ elif plugin_info.type_name == "controller":
612
+ try:
613
+ from lightfall.ui.widgets.controller_registry import ControllerPluginRegistry
614
+
615
+ controller_registry = ControllerPluginRegistry.get_instance()
616
+ controller_plugin = plugin_info.instance
617
+
618
+ controller_registry.register(controller_plugin)
619
+ logger.debug(
620
+ "Registered controller plugin '{}' with ControllerPluginRegistry",
621
+ controller_plugin.name,
622
+ )
623
+ except ImportError:
624
+ logger.debug(
625
+ "ControllerPluginRegistry not available, "
626
+ "skipping controller registration"
627
+ )
628
+
629
+ elif plugin_info.type_name == "agent":
630
+ try:
631
+ from lightfall.plugins.agent_plugin import AgentPlugin
632
+ from lightfall.ui.panels.claude.agent_registry import AgentRegistry
633
+
634
+ instance = plugin_info.instance
635
+ if not isinstance(instance, AgentPlugin):
636
+ logger.error(
637
+ "Agent plugin '{}' class {} is not an AgentPlugin subclass; skipping",
638
+ plugin_info.name, type(instance).__name__,
639
+ )
640
+ else:
641
+ AgentRegistry.get_instance().register(instance)
642
+ logger.debug("Registered agent plugin '{}' with AgentRegistry", instance.name)
643
+ except ImportError:
644
+ logger.debug("AgentRegistry not available, skipping agent registration")
645
+
646
+ elif plugin_info.type_name == "panel":
647
+ try:
648
+ from lightfall.ui.panels.registry import PanelRegistry
649
+
650
+ panel_registry = PanelRegistry.get_instance()
651
+ panel_plugin = plugin_info.instance
652
+ panel_class = panel_plugin.get_panel_class()
653
+
654
+ panel_registry.register(panel_class, replace=True)
655
+ logger.debug(
656
+ "Registered panel '{}' with PanelRegistry",
657
+ panel_class.panel_metadata.id,
658
+ )
659
+ except ImportError:
660
+ logger.debug(
661
+ "PanelRegistry not available, skipping panel registration"
662
+ )
663
+
664
+ elif plugin_info.type_name == "theme":
665
+ try:
666
+ from lightfall.ui.theme.registry import ThemeRegistry
667
+
668
+ theme_registry = ThemeRegistry.get_instance()
669
+ theme_plugin = plugin_info.instance
670
+
671
+ theme_registry.register(theme_plugin)
672
+ logger.debug(
673
+ "Registered theme '{}' with ThemeRegistry",
674
+ theme_plugin.name,
675
+ )
676
+ except ImportError:
677
+ logger.debug("ThemeRegistry not available, skipping theme registration")
678
+
679
+ elif plugin_info.type_name == "visualization":
680
+ try:
681
+ from lightfall.visualization.registry import VisualizationRegistry
682
+
683
+ viz_registry = VisualizationRegistry.get_instance()
684
+ viz_plugin = plugin_info.instance
685
+
686
+ viz_registry.register_visualization(viz_plugin, replace=True)
687
+ logger.debug(
688
+ "Registered visualization '{}' with VisualizationRegistry",
689
+ viz_plugin.name,
690
+ )
691
+ except ImportError:
692
+ logger.debug(
693
+ "VisualizationRegistry not available, skipping visualization registration"
694
+ )
695
+
696
+ def get_plugin_by_name(
697
+ self,
698
+ name: str,
699
+ type_name: str | None = None,
700
+ timeout: float = 10.0,
701
+ ) -> Any | None:
702
+ """Get a plugin by name, loading it immediately if necessary.
703
+
704
+ This implements the Xi-CAM pattern of priority loading - if a plugin
705
+ is not yet ready, it will be loaded synchronously.
706
+
707
+ Args:
708
+ name: Plugin name.
709
+ type_name: Plugin type (required if name is ambiguous).
710
+ timeout: Maximum seconds to wait for loading.
711
+
712
+ Returns:
713
+ Plugin instance or None if not found.
714
+
715
+ Raises:
716
+ PluginNotFoundError: If plugin is not registered.
717
+ PluginLoadError: If plugin failed to load.
718
+ PluginInitError: If plugin failed to initialize.
719
+ TimeoutError: If loading times out.
720
+ """
721
+ # Find the plugin info
722
+ plugin_info = None
723
+ if type_name:
724
+ plugin_info = self._registry.get(type_name, name)
725
+ else:
726
+ # Search all types
727
+ for t in self._registry.get_types():
728
+ info = self._registry.get(t, name)
729
+ if info:
730
+ if plugin_info is not None:
731
+ raise ValueError(
732
+ f"Multiple plugins named '{name}' exist. "
733
+ "Specify type_name to disambiguate."
734
+ )
735
+ plugin_info = info
736
+
737
+ if plugin_info is None:
738
+ raise PluginNotFoundError(type_name or "any", name)
739
+
740
+ if plugin_info.is_ready:
741
+ return plugin_info.instance
742
+
743
+ if plugin_info.is_failed:
744
+ if plugin_info.status == PluginStatus.FAILED_LOAD:
745
+ raise PluginLoadError(
746
+ plugin_info.unique_id,
747
+ plugin_info.error or "Unknown error",
748
+ )
749
+ else:
750
+ raise PluginInitError(
751
+ plugin_info.unique_id,
752
+ plugin_info.error or "Unknown error",
753
+ )
754
+
755
+ # Try to load it now (priority loading)
756
+ if plugin_info.status in (PluginStatus.QUEUED_LOAD, PluginStatus.DISCOVERED):
757
+ # Remove from queue if present
758
+ try:
759
+ self._load_queue.remove(plugin_info)
760
+ except ValueError:
761
+ pass
762
+
763
+ if not self._load_plugin_class(plugin_info):
764
+ raise PluginLoadError(
765
+ plugin_info.unique_id,
766
+ plugin_info.error or "Unknown error",
767
+ )
768
+
769
+ if plugin_info.status == PluginStatus.QUEUED_INIT:
770
+ # Remove from queue if present
771
+ try:
772
+ self._init_queue.remove(plugin_info)
773
+ except ValueError:
774
+ pass
775
+
776
+ if not self._instantiate_plugin(plugin_info):
777
+ raise PluginInitError(
778
+ plugin_info.unique_id,
779
+ plugin_info.error or "Unknown error",
780
+ )
781
+
782
+ # Register with type-specific registry
783
+ invoke_in_main_thread(self._register_with_type_registry, plugin_info)
784
+
785
+ # Wait for loading/initializing to complete
786
+ if plugin_info.is_loading:
787
+ start_time = time.monotonic()
788
+ while plugin_info.is_loading:
789
+ if is_main_thread():
790
+ app = QApplication.instance()
791
+ if app:
792
+ app.processEvents()
793
+ else:
794
+ time.sleep(0.01)
795
+
796
+ if time.monotonic() - start_time > timeout:
797
+ raise TimeoutError(
798
+ f"Plugin '{plugin_info.unique_id}' loading timed out"
799
+ )
800
+
801
+ if plugin_info.is_ready:
802
+ return plugin_info.instance
803
+
804
+ # Must have failed
805
+ if plugin_info.status == PluginStatus.FAILED_LOAD:
806
+ raise PluginLoadError(
807
+ plugin_info.unique_id,
808
+ plugin_info.error or "Unknown error",
809
+ )
810
+ else:
811
+ raise PluginInitError(
812
+ plugin_info.unique_id,
813
+ plugin_info.error or "Unknown error",
814
+ )
815
+
816
+ def load_all_sync(self) -> tuple[int, int]:
817
+ """Load all queued plugins synchronously.
818
+
819
+ Blocks until all plugins are loaded. Use for testing or when
820
+ background loading is not desired.
821
+
822
+ Returns:
823
+ Tuple of (successful_count, failed_count).
824
+ """
825
+ successful = 0
826
+ failed = 0
827
+
828
+ # Phase 1: Load classes
829
+ while self._load_queue:
830
+ plugin_info = self._load_queue.popleft()
831
+
832
+ if self._load_plugin_class(plugin_info):
833
+ self._init_queue.append(plugin_info)
834
+ plugin_info.status = PluginStatus.QUEUED_INIT
835
+ else:
836
+ failed += 1
837
+
838
+ # Phase 2: Instantiate
839
+ while self._init_queue:
840
+ plugin_info = self._init_queue.popleft()
841
+
842
+ if self._instantiate_plugin(plugin_info):
843
+ successful += 1
844
+ self._register_with_type_registry(plugin_info)
845
+ self.plugin_loaded.emit(plugin_info)
846
+ else:
847
+ failed += 1
848
+ self.plugin_failed.emit(plugin_info)
849
+
850
+ logger.info(
851
+ "Synchronous plugin loading complete: {} successful, {} failed",
852
+ successful,
853
+ failed,
854
+ )
855
+ return successful, failed
856
+
857
+ def cancel_loading(self) -> None:
858
+ """Cancel background loading if in progress."""
859
+ if self._worker and self._worker.isRunning():
860
+ self._worker.cancel()
861
+ self._is_loading = False
862
+ logger.info("Plugin loading cancelled")
863
+
864
+ def get_introspection_data(self) -> dict[str, Any]:
865
+ """Get introspection data for MCP tools.
866
+
867
+ Returns:
868
+ Dictionary with loader state and statistics.
869
+ """
870
+ return {
871
+ "is_loading": self._is_loading,
872
+ "registered_types": list(self._plugin_types.keys()),
873
+ "queued_for_load": len(self._load_queue),
874
+ "queued_for_init": len(self._init_queue),
875
+ "last_successful": self._successful,
876
+ "last_failed": self._failed,
877
+ "registry": self._registry.get_introspection_data(),
878
+ }