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.
- lightfall/__init__.py +8 -0
- lightfall/__main__.py +10 -0
- lightfall/_version.py +24 -0
- lightfall/acquire/__init__.py +74 -0
- lightfall/acquire/buffer.py +363 -0
- lightfall/acquire/device_wrapper.py +416 -0
- lightfall/acquire/engine/__init__.py +155 -0
- lightfall/acquire/engine/base.py +587 -0
- lightfall/acquire/engine/bluesky.py +358 -0
- lightfall/acquire/engine/mock.py +165 -0
- lightfall/acquire/engine/plugins/__init__.py +9 -0
- lightfall/acquire/engine/plugins/bluesky_plugin.py +56 -0
- lightfall/acquire/engine/plugins/mock_plugin.py +55 -0
- lightfall/acquire/engine/protocol.py +145 -0
- lightfall/acquire/engine/registry.py +152 -0
- lightfall/acquire/engine/state.py +32 -0
- lightfall/acquire/engine/waiting_hook.py +225 -0
- lightfall/acquire/nats_bridge.py +62 -0
- lightfall/acquire/plan_ui.py +78 -0
- lightfall/acquire/plans/__init__.py +38 -0
- lightfall/acquire/plans/adaptive.py +288 -0
- lightfall/acquire/plans/example_plans.py +995 -0
- lightfall/acquire/plans/lightfall_plans.py +587 -0
- lightfall/acquire/plans/registry.py +543 -0
- lightfall/acquire/plans/standard_plans.py +186 -0
- lightfall/acquire/plans/user_plans.py +470 -0
- lightfall/acquire/runengine.py +36 -0
- lightfall/acquire/signals.py +452 -0
- lightfall/acquire/triggers/__init__.py +16 -0
- lightfall/acquire/triggers/base.py +25 -0
- lightfall/acquire/triggers/filter.py +37 -0
- lightfall/acquire/triggers/manager.py +73 -0
- lightfall/acquire/triggers/manual.py +36 -0
- lightfall/acquire/triggers/run_end.py +74 -0
- lightfall/acquire/triggers/run_start.py +52 -0
- lightfall/auth/__init__.py +38 -0
- lightfall/auth/policy.py +518 -0
- lightfall/auth/providers/__init__.py +30 -0
- lightfall/auth/providers/base.py +124 -0
- lightfall/auth/providers/keycloak.py +1017 -0
- lightfall/auth/providers/local.py +319 -0
- lightfall/auth/providers/pam.py +250 -0
- lightfall/auth/service_key.py +173 -0
- lightfall/auth/service_key_auth.py +79 -0
- lightfall/auth/session.py +656 -0
- lightfall/claude/__init__.py +52 -0
- lightfall/claude/_internal/__init__.py +1 -0
- lightfall/claude/_internal/serialization.py +195 -0
- lightfall/claude/_internal/threading.py +61 -0
- lightfall/claude/_internal/worker.py +757 -0
- lightfall/claude/_session_assembly.py +124 -0
- lightfall/claude/agent.py +596 -0
- lightfall/claude/lightfall_core_tools.py +410 -0
- lightfall/claude/markdown.py +103 -0
- lightfall/claude/permission_manager.py +588 -0
- lightfall/claude/tools/__init__.py +45 -0
- lightfall/claude/tools/controller.py +143 -0
- lightfall/claude/tools/interaction.py +177 -0
- lightfall/claude/tools/introspection.py +127 -0
- lightfall/claude/tools/logs.py +155 -0
- lightfall/claude/tools/screenshot.py +87 -0
- lightfall/claude/widget.py +851 -0
- lightfall/claude/widgets/__init__.py +5 -0
- lightfall/claude/widgets/permission_request.py +282 -0
- lightfall/claude/widgets/question_request.py +227 -0
- lightfall/claude/widgets/task_card.py +223 -0
- lightfall/config/__init__.py +23 -0
- lightfall/config/layers.py +317 -0
- lightfall/config/manager.py +244 -0
- lightfall/config/schema.py +154 -0
- lightfall/core/__init__.py +23 -0
- lightfall/core/application.py +727 -0
- lightfall/core/services.py +235 -0
- lightfall/devices/__init__.py +53 -0
- lightfall/devices/backends/__init__.py +17 -0
- lightfall/devices/backends/bcs.py +448 -0
- lightfall/devices/backends/happi.py +986 -0
- lightfall/devices/backends/mock.py +646 -0
- lightfall/devices/base.py +338 -0
- lightfall/devices/catalog.py +1039 -0
- lightfall/devices/connection_manager.py +676 -0
- lightfall/devices/model.py +290 -0
- lightfall/devices/monitoring.py +442 -0
- lightfall/devices/sim/__init__.py +26 -0
- lightfall/devices/sim/areadetector.py +436 -0
- lightfall/devices/sim/generators.py +223 -0
- lightfall/devices/sim/plugins.py +116 -0
- lightfall/epics/__init__.py +28 -0
- lightfall/epics/ca/__init__.py +10 -0
- lightfall/epics/ca/context.py +100 -0
- lightfall/epics/ca/pv.py +303 -0
- lightfall/epics/widgets/__init__.py +49 -0
- lightfall/epics/widgets/areadetector/__init__.py +16 -0
- lightfall/epics/widgets/areadetector/areadetector.py +281 -0
- lightfall/epics/widgets/areadetector/controls.py +478 -0
- lightfall/epics/widgets/areadetector/image_view.py +447 -0
- lightfall/epics/widgets/auto.py +319 -0
- lightfall/epics/widgets/base.py +404 -0
- lightfall/epics/widgets/checkbox.py +239 -0
- lightfall/epics/widgets/combobox.py +202 -0
- lightfall/epics/widgets/label.py +176 -0
- lightfall/epics/widgets/lineedit.py +253 -0
- lightfall/epics/widgets/motor.py +694 -0
- lightfall/epics/widgets/ophyd_base.py +469 -0
- lightfall/epics/widgets/ophyd_combobox.py +86 -0
- lightfall/epics/widgets/ophyd_label.py +54 -0
- lightfall/epics/widgets/ophyd_lineedit.py +170 -0
- lightfall/epics/widgets/ophyd_spinbox.py +79 -0
- lightfall/epics/widgets/slider.py +272 -0
- lightfall/epics/widgets/status_indicator.py +98 -0
- lightfall/epics/widgets/style.py +188 -0
- lightfall/exporter/__init__.py +1 -0
- lightfall/exporter/cli.py +67 -0
- lightfall/exporter/converters/__init__.py +26 -0
- lightfall/exporter/converters/base.py +39 -0
- lightfall/exporter/converters/noop.py +39 -0
- lightfall/exporter/converters/nxsas.py +73 -0
- lightfall/exporter/service.py +200 -0
- lightfall/exporter/tiled_utils.py +92 -0
- lightfall/ipc/__init__.py +6 -0
- lightfall/ipc/service.py +701 -0
- lightfall/ipc/trust.py +144 -0
- lightfall/logbook/__init__.py +46 -0
- lightfall/logbook/action_dialog.py +207 -0
- lightfall/logbook/action_logger.py +432 -0
- lightfall/logbook/block_mapper.py +562 -0
- lightfall/logbook/client.py +799 -0
- lightfall/logbook/converter.py +273 -0
- lightfall/logbook/editors/__init__.py +19 -0
- lightfall/logbook/editors/highlighter.py +305 -0
- lightfall/logbook/editors/markdown_editor.py +319 -0
- lightfall/logbook/editors/richtext_editor.py +1397 -0
- lightfall/logbook/entry_widget.py +1065 -0
- lightfall/logbook/event_listener.py +221 -0
- lightfall/logbook/fragment_widgets.py +925 -0
- lightfall/logbook/position_mapper.py +320 -0
- lightfall/logbook/protection.py +402 -0
- lightfall/logbook/style.py +394 -0
- lightfall/logbook/url.py +29 -0
- lightfall/logbook/visual_protection.py +330 -0
- lightfall/logbook/widget.py +680 -0
- lightfall/main.py +1091 -0
- lightfall/pipelines/__init__.py +4 -0
- lightfall/pipelines/client.py +148 -0
- lightfall/plugins/__init__.py +119 -0
- lightfall/plugins/agent_plugin.py +106 -0
- lightfall/plugins/agents/__init__.py +10 -0
- lightfall/plugins/agents/_mcp_helpers.py +52 -0
- lightfall/plugins/agents/alignment.py +94 -0
- lightfall/plugins/agents/autonomous_experiment/__init__.py +12 -0
- lightfall/plugins/agents/autonomous_experiment/nats_tools.py +210 -0
- lightfall/plugins/agents/autonomous_experiment/plugin.py +60 -0
- lightfall/plugins/agents/autonomous_experiment/prompts.py +164 -0
- lightfall/plugins/agents/current_esaf.py +435 -0
- lightfall/plugins/agents/device_tools.py +1043 -0
- lightfall/plugins/agents/engine_tools.py +720 -0
- lightfall/plugins/agents/ipython_tools.py +444 -0
- lightfall/plugins/agents/panel_builder.py +637 -0
- lightfall/plugins/agents/panel_design/references/cross_panel_patterns.md +95 -0
- lightfall/plugins/agents/panel_design/references/panel_design.md +680 -0
- lightfall/plugins/agents/panel_design.py +94 -0
- lightfall/plugins/agents/plan_design/references/plan_design.md +398 -0
- lightfall/plugins/agents/plan_design.py +90 -0
- lightfall/plugins/agents/plan_tools.py +878 -0
- lightfall/plugins/agents/scan_planning.py +101 -0
- lightfall/plugins/builtin_manifest.py +348 -0
- lightfall/plugins/controller_plugin.py +162 -0
- lightfall/plugins/engine_plugin.py +124 -0
- lightfall/plugins/errors.py +104 -0
- lightfall/plugins/info.py +112 -0
- lightfall/plugins/loader.py +878 -0
- lightfall/plugins/manifest.py +150 -0
- lightfall/plugins/panel_plugin.py +119 -0
- lightfall/plugins/plan_plugin.py +163 -0
- lightfall/plugins/registry.py +309 -0
- lightfall/plugins/settings_plugin.py +226 -0
- lightfall/plugins/statusbar_plugin.py +289 -0
- lightfall/plugins/theme_plugin.py +165 -0
- lightfall/plugins/types.py +136 -0
- lightfall/plugins/user_plugins.py +764 -0
- lightfall/project/__init__.py +37 -0
- lightfall/project/model.py +375 -0
- lightfall/project/service.py +427 -0
- lightfall/project/welcome.py +106 -0
- lightfall/resources/__init__.py +126 -0
- lightfall/resources/images/__init__.py +1 -0
- lightfall/resources/images/icon.ico +0 -0
- lightfall/resources/images/icon.png +0 -0
- lightfall/resources/images/logo.png +0 -0
- lightfall/services/__init__.py +33 -0
- lightfall/services/_alshub_client.py +73 -0
- lightfall/services/access_stamper.py +240 -0
- lightfall/services/als_beam_status.py +347 -0
- lightfall/services/ca_tunnel.py +325 -0
- lightfall/services/threaded_tiled_writer.py +174 -0
- lightfall/services/tiled_auth.py +21 -0
- lightfall/services/tiled_service.py +971 -0
- lightfall/services/tiled_writer_patch.py +301 -0
- lightfall/settings/__init__.py +1 -0
- lightfall/settings/image_helpers.py +30 -0
- lightfall/settings/user_settings_client.py +232 -0
- lightfall/ui/__init__.py +28 -0
- lightfall/ui/annotations.py +208 -0
- lightfall/ui/common/__init__.py +7 -0
- lightfall/ui/dialogs/__init__.py +26 -0
- lightfall/ui/dialogs/about_dialog.py +131 -0
- lightfall/ui/dialogs/add_trigger_dialog.py +152 -0
- lightfall/ui/dialogs/base.py +44 -0
- lightfall/ui/dialogs/bug_report_dialog.py +353 -0
- lightfall/ui/dialogs/create_plan_dialog.py +189 -0
- lightfall/ui/dialogs/device_edit_dialog.py +183 -0
- lightfall/ui/dialogs/export_dialog.py +565 -0
- lightfall/ui/dialogs/go_to_position_dialog.py +192 -0
- lightfall/ui/dialogs/login_dialog.py +756 -0
- lightfall/ui/dialogs/oauth_browser_dialog.py +305 -0
- lightfall/ui/dialogs/run_pipeline_dialog.py +131 -0
- lightfall/ui/dialogs/sample_metadata_dialog.py +316 -0
- lightfall/ui/docking/__init__.py +22 -0
- lightfall/ui/docking/icon_sidebar.py +806 -0
- lightfall/ui/docking/manager.py +682 -0
- lightfall/ui/docking/state.py +113 -0
- lightfall/ui/docking/theme.py +399 -0
- lightfall/ui/docking/widget.py +214 -0
- lightfall/ui/events.py +75 -0
- lightfall/ui/mainwindow.py +1006 -0
- lightfall/ui/models/__init__.py +49 -0
- lightfall/ui/models/device_selection.py +389 -0
- lightfall/ui/models/device_tree.py +1095 -0
- lightfall/ui/models/thread_model.py +667 -0
- lightfall/ui/models/tiled_model.py +384 -0
- lightfall/ui/panels/__init__.py +28 -0
- lightfall/ui/panels/base.py +525 -0
- lightfall/ui/panels/bluesky_panel.py +619 -0
- lightfall/ui/panels/claude/__init__.py +9 -0
- lightfall/ui/panels/claude/agent_registry.py +168 -0
- lightfall/ui/panels/claude_panel.py +887 -0
- lightfall/ui/panels/device_panel.py +370 -0
- lightfall/ui/panels/documents_panel.py +166 -0
- lightfall/ui/panels/ipython_panel.py +580 -0
- lightfall/ui/panels/logbook_entries_panel.py +84 -0
- lightfall/ui/panels/logbook_panel.py +627 -0
- lightfall/ui/panels/logging_panel.py +587 -0
- lightfall/ui/panels/pipeline_jobs_panel.py +160 -0
- lightfall/ui/panels/pipeline_triggers_panel.py +170 -0
- lightfall/ui/panels/plugins/__init__.py +34 -0
- lightfall/ui/panels/plugins/bluesky_plugin.py +27 -0
- lightfall/ui/panels/plugins/claude_plugin.py +29 -0
- lightfall/ui/panels/plugins/device_plugin.py +27 -0
- lightfall/ui/panels/plugins/documents_plugin.py +26 -0
- lightfall/ui/panels/plugins/ipython_plugin.py +27 -0
- lightfall/ui/panels/plugins/logbook_entries_plugin.py +23 -0
- lightfall/ui/panels/plugins/logbook_plugin.py +27 -0
- lightfall/ui/panels/plugins/logging_plugin.py +27 -0
- lightfall/ui/panels/plugins/pipeline_jobs_plugin.py +23 -0
- lightfall/ui/panels/plugins/pipeline_triggers_plugin.py +25 -0
- lightfall/ui/panels/plugins/queue_plugin.py +29 -0
- lightfall/ui/panels/plugins/synoptic_plugin.py +38 -0
- lightfall/ui/panels/plugins/threads_plugin.py +27 -0
- lightfall/ui/panels/plugins/tiled_browser_plugin.py +27 -0
- lightfall/ui/panels/plugins/visualization_plugin.py +27 -0
- lightfall/ui/panels/queue.py +754 -0
- lightfall/ui/panels/registry.py +483 -0
- lightfall/ui/panels/synoptic/__init__.py +27 -0
- lightfall/ui/panels/synoptic/editors.py +481 -0
- lightfall/ui/panels/synoptic/items.py +556 -0
- lightfall/ui/panels/synoptic/models.py +336 -0
- lightfall/ui/panels/synoptic/panel.py +889 -0
- lightfall/ui/panels/synoptic/serialization.py +300 -0
- lightfall/ui/panels/synoptic/view.py +504 -0
- lightfall/ui/panels/threads_panel.py +621 -0
- lightfall/ui/panels/tiled_browser_panel.py +854 -0
- lightfall/ui/panels/visualization_panel.py +508 -0
- lightfall/ui/preferences/__init__.py +24 -0
- lightfall/ui/preferences/backend.py +148 -0
- lightfall/ui/preferences/builtin.py +220 -0
- lightfall/ui/preferences/claude_settings.py +762 -0
- lightfall/ui/preferences/device_settings.py +461 -0
- lightfall/ui/preferences/dialog.py +234 -0
- lightfall/ui/preferences/editor_settings.py +227 -0
- lightfall/ui/preferences/ipc_settings.py +226 -0
- lightfall/ui/preferences/logbook_settings.py +232 -0
- lightfall/ui/preferences/login_settings.py +183 -0
- lightfall/ui/preferences/manager.py +562 -0
- lightfall/ui/preferences/plugin_settings.py +392 -0
- lightfall/ui/preferences/proxy_settings.py +561 -0
- lightfall/ui/preferences/skill_settings.py +28 -0
- lightfall/ui/preferences/tiled_settings.py +469 -0
- lightfall/ui/preferences/tool_settings.py +393 -0
- lightfall/ui/preferences/user_portable_backend.py +131 -0
- lightfall/ui/preferences/user_profile_settings.py +316 -0
- lightfall/ui/preferences/visualization_settings.py +159 -0
- lightfall/ui/resources/__init__.py +1 -0
- lightfall/ui/resources/logo.png +0 -0
- lightfall/ui/statusbar/__init__.py +11 -0
- lightfall/ui/statusbar/manager.py +379 -0
- lightfall/ui/statusbar/plugins/__init__.py +28 -0
- lightfall/ui/statusbar/plugins/als_beam_status.py +218 -0
- lightfall/ui/statusbar/plugins/auth_status.py +116 -0
- lightfall/ui/statusbar/plugins/connection_status.py +100 -0
- lightfall/ui/statusbar/plugins/thread_status.py +556 -0
- lightfall/ui/statusbar/plugins/tiled_status.py +179 -0
- lightfall/ui/statusbar/plugins/user_status.py +84 -0
- lightfall/ui/theater/__init__.py +28 -0
- lightfall/ui/theater/manager.py +124 -0
- lightfall/ui/theater/overlay.py +279 -0
- lightfall/ui/theater/proxy.py +111 -0
- lightfall/ui/theme/__init__.py +18 -0
- lightfall/ui/theme/builtin.py +1015 -0
- lightfall/ui/theme/manager.py +875 -0
- lightfall/ui/theme/registry.py +195 -0
- lightfall/ui/toast.py +221 -0
- lightfall/ui/tutorial.py +1100 -0
- lightfall/ui/widgets/__init__.py +110 -0
- lightfall/ui/widgets/base_control.py +259 -0
- lightfall/ui/widgets/camera/__init__.py +36 -0
- lightfall/ui/widgets/camera/base.py +815 -0
- lightfall/ui/widgets/camera/dark_frames.py +213 -0
- lightfall/ui/widgets/camera/image_view.py +649 -0
- lightfall/ui/widgets/camera/panels/__init__.py +14 -0
- lightfall/ui/widgets/camera/panels/cooler.py +320 -0
- lightfall/ui/widgets/camera/panels/temperature.py +192 -0
- lightfall/ui/widgets/camera/plan_based.py +202 -0
- lightfall/ui/widgets/compact_motor.py +522 -0
- lightfall/ui/widgets/controller_matcher.py +278 -0
- lightfall/ui/widgets/controller_registry.py +144 -0
- lightfall/ui/widgets/device_control.py +411 -0
- lightfall/ui/widgets/device_selector.py +438 -0
- lightfall/ui/widgets/device_tree_tab.py +461 -0
- lightfall/ui/widgets/document_stream.py +1028 -0
- lightfall/ui/widgets/favorites_tab.py +191 -0
- lightfall/ui/widgets/motor_control.py +1120 -0
- lightfall/ui/widgets/observers/__init__.py +8 -0
- lightfall/ui/widgets/observers/camera.py +48 -0
- lightfall/ui/widgets/observers/image_view.py +130 -0
- lightfall/ui/widgets/plan_config.py +954 -0
- lightfall/ui/widgets/plan_edit_dialog.py +294 -0
- lightfall/ui/widgets/plan_selector.py +452 -0
- lightfall/ui/widgets/profile_avatar.py +128 -0
- lightfall/ui/widgets/queue_view.py +647 -0
- lightfall/ui/widgets/runengine_control.py +549 -0
- lightfall/ui/widgets/signal_control.py +793 -0
- lightfall/ui/widgets/skill_trigger_button.py +183 -0
- lightfall/ui/widgets/tiled_filter_widget.py +314 -0
- lightfall/ui/widgets/tiled_status.py +149 -0
- lightfall/ui/widgets/warning_banner.py +185 -0
- lightfall/utils/__init__.py +53 -0
- lightfall/utils/crash_diagnostics.py +454 -0
- lightfall/utils/data_migration.py +22 -0
- lightfall/utils/editor_launcher.py +594 -0
- lightfall/utils/error_collector.py +245 -0
- lightfall/utils/git_tracker.py +197 -0
- lightfall/utils/log_buffer.py +233 -0
- lightfall/utils/logging.py +229 -0
- lightfall/utils/module_resolver.py +70 -0
- lightfall/utils/sentry.py +722 -0
- lightfall/utils/threads.py +991 -0
- lightfall/utils/tiled_helpers.py +96 -0
- lightfall/visualization/__init__.py +50 -0
- lightfall/visualization/base.py +5 -0
- lightfall/visualization/base_visualization.py +74 -0
- lightfall/visualization/fitting/__init__.py +24 -0
- lightfall/visualization/fitting/base.py +267 -0
- lightfall/visualization/fitting/fitters.py +325 -0
- lightfall/visualization/fitting/panel.py +265 -0
- lightfall/visualization/memory.py +392 -0
- lightfall/visualization/motor_mixin.py +524 -0
- lightfall/visualization/pg.py +156 -0
- lightfall/visualization/registry.py +144 -0
- lightfall/visualization/spec.py +79 -0
- lightfall/visualization/theme.py +266 -0
- lightfall/visualization/widgets/__init__.py +28 -0
- lightfall/visualization/widgets/adaptive/__init__.py +1 -0
- lightfall/visualization/widgets/adaptive/heatmap.py +655 -0
- lightfall/visualization/widgets/adaptive/plot.py +233 -0
- lightfall/visualization/widgets/heatmap.py +264 -0
- lightfall/visualization/widgets/image_stack.py +316 -0
- lightfall/visualization/widgets/image_view_toolbar.py +227 -0
- lightfall/visualization/widgets/lazy_image_view.py +590 -0
- lightfall/visualization/widgets/plot_1d.py +262 -0
- lightfall/visualization/widgets/scatter.py +247 -0
- lightfall/visualization/widgets/table.py +221 -0
- lightfall/visualization/widgets/time_axis.py +93 -0
- lightfall-0.1.1.dist-info/METADATA +223 -0
- lightfall-0.1.1.dist-info/RECORD +388 -0
- lightfall-0.1.1.dist-info/WHEEL +4 -0
- lightfall-0.1.1.dist-info/entry_points.txt +6 -0
- lightfall-0.1.1.dist-info/licenses/LEGAL.md +13 -0
- lightfall-0.1.1.dist-info/licenses/LICENSE.md +33 -0
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
"""QtClaudeAgent - Low-level API for Claude integration with Qt."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import platform
|
|
5
|
+
import shutil
|
|
6
|
+
import tempfile
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient
|
|
11
|
+
from PySide6.QtCore import QObject, Signal
|
|
12
|
+
from PySide6.QtWidgets import QWidget
|
|
13
|
+
|
|
14
|
+
from lightfall.claude._internal.worker import PersistentClaudeWorker
|
|
15
|
+
from lightfall.claude.permission_manager import (
|
|
16
|
+
PermissionManager,
|
|
17
|
+
create_can_use_tool_callback,
|
|
18
|
+
create_pre_tool_use_hook,
|
|
19
|
+
)
|
|
20
|
+
from lightfall.claude.tools import create_qt_tools_server
|
|
21
|
+
from lightfall.utils.logging import logger
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _patch_sdk_for_windows_cmdline_limit():
|
|
25
|
+
"""
|
|
26
|
+
Monkey-patch the Claude Agent SDK to handle Windows command line length limits.
|
|
27
|
+
|
|
28
|
+
Windows has an 8191 character command line limit. The SDK handles --agents by
|
|
29
|
+
writing to a temp file when too long, but not other large arguments like
|
|
30
|
+
--system-prompt or --mcp-config. This patch extends that handling.
|
|
31
|
+
"""
|
|
32
|
+
if platform.system() != "Windows":
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
from claude_agent_sdk._internal.transport import subprocess_cli
|
|
37
|
+
except ImportError:
|
|
38
|
+
return # SDK structure changed, skip patching
|
|
39
|
+
|
|
40
|
+
if getattr(subprocess_cli, '_cmdline_patched', False):
|
|
41
|
+
return
|
|
42
|
+
|
|
43
|
+
original_build_command = subprocess_cli.SubprocessCLITransport._build_command
|
|
44
|
+
|
|
45
|
+
def patched_build_command(self):
|
|
46
|
+
"""Patched _build_command that writes large arguments to temp files."""
|
|
47
|
+
cmd = original_build_command(self)
|
|
48
|
+
cmd_str = " ".join(cmd)
|
|
49
|
+
cmd_limit = 8000
|
|
50
|
+
|
|
51
|
+
if len(cmd_str) > cmd_limit:
|
|
52
|
+
# Args the CLI reads natively as a file path (no @ prefix needed)
|
|
53
|
+
file_path_args = {"--mcp-config", "--settings"}
|
|
54
|
+
# Args the CLI reads via @file convention
|
|
55
|
+
atfile_args = {"--system-prompt", "--agents"}
|
|
56
|
+
|
|
57
|
+
for arg_name in file_path_args | atfile_args:
|
|
58
|
+
try:
|
|
59
|
+
arg_idx = cmd.index(arg_name)
|
|
60
|
+
arg_value = cmd[arg_idx + 1]
|
|
61
|
+
|
|
62
|
+
if arg_value.startswith("@") or len(arg_value) < 500:
|
|
63
|
+
continue
|
|
64
|
+
|
|
65
|
+
suffix = ".json" if arg_value.startswith("{") else ".txt"
|
|
66
|
+
temp_file = tempfile.NamedTemporaryFile(
|
|
67
|
+
mode="w", suffix=suffix, delete=False, encoding="utf-8"
|
|
68
|
+
)
|
|
69
|
+
temp_file.write(arg_value)
|
|
70
|
+
temp_file.close()
|
|
71
|
+
|
|
72
|
+
if not hasattr(self, '_temp_files'):
|
|
73
|
+
self._temp_files = []
|
|
74
|
+
self._temp_files.append(temp_file.name)
|
|
75
|
+
|
|
76
|
+
if arg_name in file_path_args:
|
|
77
|
+
cmd[arg_idx + 1] = temp_file.name
|
|
78
|
+
else:
|
|
79
|
+
cmd[arg_idx + 1] = f"@{temp_file.name}"
|
|
80
|
+
|
|
81
|
+
except (ValueError, IndexError):
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
return cmd
|
|
85
|
+
|
|
86
|
+
subprocess_cli.SubprocessCLITransport._build_command = patched_build_command
|
|
87
|
+
subprocess_cli._cmdline_patched = True
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# Apply the patch on module load
|
|
91
|
+
_patch_sdk_for_windows_cmdline_limit()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# System prompt for Qt understanding
|
|
95
|
+
QT_SYSTEM_PROMPT = """You are a synchrotron beamline AI assistant integrated with a Qt/PySide6 application named
|
|
96
|
+
Lightfall
|
|
97
|
+
|
|
98
|
+
## Your Capabilities
|
|
99
|
+
|
|
100
|
+
You have domain-specific tools provided by the application - use these FIRST when they match the task. These tools understand the application's structure and can perform actions directly.
|
|
101
|
+
|
|
102
|
+
You also have general Qt inspection and interaction tools as a fallback:
|
|
103
|
+
- screenshot: Capture the window's current visual state
|
|
104
|
+
- get_widget_tree: View the widget hierarchy and structure
|
|
105
|
+
- find_widget: Locate widgets by object name
|
|
106
|
+
- click_widget: Click buttons and interactive widgets
|
|
107
|
+
- type_text: Enter text into input fields
|
|
108
|
+
- get_recent_logs: Read recent log records from the running Lightfall process. Use this when something unexpected happened outside your own tool calls (e.g., a panel didn't update as expected, a plan failed, a device went offline). Defaults to WARNING+ in the last two minutes; widen the filter (e.g., level="DEBUG", since_seconds=600) only when narrower scopes don't surface the issue.
|
|
109
|
+
|
|
110
|
+
## Tool Selection Guidelines
|
|
111
|
+
|
|
112
|
+
1. **Prefer domain-specific tools** - If a tool exists for your specific task (e.g., opening a panel, running a scan, controlling a device), use it directly instead of navigating the UI manually.
|
|
113
|
+
|
|
114
|
+
2. **Use Qt tools when needed for:**
|
|
115
|
+
- Understanding unfamiliar parts of the UI
|
|
116
|
+
- Interacting with widgets that lack domain-specific tools
|
|
117
|
+
- Debugging or explaining the current UI state to the user
|
|
118
|
+
- Situations where the user explicitly asks you to inspect the interface
|
|
119
|
+
|
|
120
|
+
3. **Avoid unnecessary exploration** - Don't take screenshots or inspect widget trees unless you need that information. If you know what tool to use, use it.
|
|
121
|
+
|
|
122
|
+
## Plan Execution Tools
|
|
123
|
+
|
|
124
|
+
You have tools for running Bluesky plans in the Lightfall RunEngine:
|
|
125
|
+
|
|
126
|
+
- **lightfall_list_plans**: List all registered plans (built-in + user plans). Use this FIRST to discover what's available and see parameter signatures. Optionally filter by category.
|
|
127
|
+
- **lightfall_run_plan**: Run a registered plan by name with parameters. Use this when the user wants to run a known plan (e.g., "run a scan", "do a count"). Resolves device names automatically.
|
|
128
|
+
- **lightfall_run_plan_code**: Run arbitrary Python code as a plan. Use this when the user needs a custom/ad-hoc plan that isn't in the registry, or wants to compose multiple plans together. The code should use `yield from` with bluesky plans. Common imports (bp, bps, np, all devices) are pre-loaded.
|
|
129
|
+
- **lightfall_create_user_plan**: Create a persistent user plan file (saved to ~/lightfall/plans/). Use this when the user wants to save a reusable plan for future use, not for one-off execution.
|
|
130
|
+
|
|
131
|
+
### When to use which:
|
|
132
|
+
- "Run a scan" → lightfall_list_plans to check params, then lightfall_run_plan
|
|
133
|
+
- "Scan motor1 from -5 to 5" → lightfall_run_plan(plan_name="scan", params={...})
|
|
134
|
+
- "Do 3 scans with increasing range" → lightfall_run_plan_code with a loop
|
|
135
|
+
- "Create a plan I can reuse" → lightfall_create_user_plan
|
|
136
|
+
|
|
137
|
+
### Waiting for a scan to finish
|
|
138
|
+
|
|
139
|
+
Use **lightfall_wait_for_idle** whenever you need the engine to settle before doing
|
|
140
|
+
follow-up work (fitting, summarising, kicking off a dependent plan). It blocks
|
|
141
|
+
the tool call until the engine returns to IDLE, then optionally returns the
|
|
142
|
+
most recent run's metadata in the same response (`include_last_run=True` by
|
|
143
|
+
default), so you can pipe straight into `lightfall_get_scan_data(uid=...)` without
|
|
144
|
+
another round-trip. Prefer this over polling `lightfall_get_run_status` in a loop,
|
|
145
|
+
and **do not use `ScheduleWakeup` for this** — `ScheduleWakeup` currently does
|
|
146
|
+
not fire in Lightfall's embedded Claude session, so any wakeup you schedule will
|
|
147
|
+
silently drop and the conversation will stall waiting for the user to nudge
|
|
148
|
+
you. `lightfall_wait_for_idle` keeps the model suspended inside the tool call,
|
|
149
|
+
which is the right pattern here.
|
|
150
|
+
|
|
151
|
+
## Qt Tool Notes
|
|
152
|
+
- Widget object names (setObjectName) identify elements in the widget tree
|
|
153
|
+
- Verify widgets exist and are enabled before interacting
|
|
154
|
+
- Some widgets have auto-generated names like "<unnamed_QPushButton>"
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class QtClaudeAgent(QObject):
|
|
159
|
+
"""
|
|
160
|
+
Low-level Claude Agent for Qt applications.
|
|
161
|
+
|
|
162
|
+
This class provides programmatic access to Claude with Qt widget interaction
|
|
163
|
+
capabilities. It manages the Claude Agent SDK client and provides signals for
|
|
164
|
+
receiving responses.
|
|
165
|
+
|
|
166
|
+
Signals:
|
|
167
|
+
message_received(str): Emitted when Claude sends a text message
|
|
168
|
+
thinking_received(str): Emitted when Claude's thinking is available
|
|
169
|
+
tool_called(str, dict): Emitted when a tool is called (tool_name, tool_input)
|
|
170
|
+
tool_result(str, dict): Emitted when a tool returns a result
|
|
171
|
+
error_occurred(str): Emitted when an error occurs
|
|
172
|
+
query_completed(): Emitted when a query finishes successfully
|
|
173
|
+
result_received(dict): Emitted with usage/cost information
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
# Signals
|
|
177
|
+
message_received = Signal(str)
|
|
178
|
+
thinking_received = Signal(str)
|
|
179
|
+
tool_called = Signal(str, dict)
|
|
180
|
+
tool_result = Signal(str, dict)
|
|
181
|
+
error_occurred = Signal(str)
|
|
182
|
+
query_completed = Signal()
|
|
183
|
+
query_cancelled = Signal() # Emitted when a query is cancelled
|
|
184
|
+
result_received = Signal(dict)
|
|
185
|
+
permission_requested = Signal(str, str, dict) # request_id, tool_name, tool_input
|
|
186
|
+
question_requested = Signal(str, list) # request_id, questions
|
|
187
|
+
# Partial streaming
|
|
188
|
+
partial_block_started = Signal(str, str)
|
|
189
|
+
partial_text = Signal(str, str)
|
|
190
|
+
partial_thinking = Signal(str, str)
|
|
191
|
+
partial_block_finished = Signal(str)
|
|
192
|
+
# Task tool subagent lifecycle
|
|
193
|
+
task_started = Signal(str, str, str)
|
|
194
|
+
task_progress = Signal(str, str, dict, str)
|
|
195
|
+
task_finished = Signal(str, str, str, str, dict)
|
|
196
|
+
|
|
197
|
+
def __init__(
|
|
198
|
+
self,
|
|
199
|
+
target_window: QWidget,
|
|
200
|
+
api_key: str | None = None,
|
|
201
|
+
api_url: str | None = None,
|
|
202
|
+
cli_path: str | None = None,
|
|
203
|
+
permission_mode: str = "default",
|
|
204
|
+
max_turns: int = 20,
|
|
205
|
+
additional_system_prompt: str | None = None,
|
|
206
|
+
require_approval: bool = True,
|
|
207
|
+
parent: QObject | None = None
|
|
208
|
+
):
|
|
209
|
+
"""
|
|
210
|
+
Initialize the Qt Claude Agent.
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
target_window: The Qt widget to interact with
|
|
214
|
+
api_key: Anthropic API key. Optional if you have authenticated via `claude login`
|
|
215
|
+
(Claude Pro/Max subscription). Can also be set via ANTHROPIC_API_KEY
|
|
216
|
+
or ANTHROPIC_AUTH_TOKEN environment variables.
|
|
217
|
+
api_url: Not used - set ANTHROPIC_BASE_URL environment variable instead
|
|
218
|
+
(kept for backward compatibility)
|
|
219
|
+
cli_path: Path to Claude Code CLI executable (auto-detected if not provided)
|
|
220
|
+
permission_mode: Permission mode for tools ('default', 'acceptEdits', 'bypassPermissions')
|
|
221
|
+
max_turns: Maximum conversation turns
|
|
222
|
+
additional_system_prompt: Optional additional text to append to the system prompt.
|
|
223
|
+
require_approval: If True, show UI approval for tool calls (default True).
|
|
224
|
+
Read-only tools (screenshot, get_widget_tree, find_widget) are
|
|
225
|
+
auto-approved. Interactive tools require user confirmation.
|
|
226
|
+
parent: Parent QObject
|
|
227
|
+
|
|
228
|
+
Note:
|
|
229
|
+
Authentication can be provided in two ways:
|
|
230
|
+
1. API Key: Pass api_key or set ANTHROPIC_API_KEY environment variable
|
|
231
|
+
2. OAuth (subscription): Run `claude login` in terminal to authenticate with your
|
|
232
|
+
Claude Pro/Max subscription. The CLI will use stored OAuth credentials.
|
|
233
|
+
"""
|
|
234
|
+
super().__init__(parent)
|
|
235
|
+
|
|
236
|
+
self.target_window = target_window
|
|
237
|
+
|
|
238
|
+
# Try multiple environment variables for API key (optional - CLI can use OAuth)
|
|
239
|
+
self.api_key = (
|
|
240
|
+
api_key
|
|
241
|
+
or os.getenv("ANTHROPIC_API_KEY")
|
|
242
|
+
or os.getenv("ANTHROPIC_AUTH_TOKEN")
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
# Try multiple environment variables for API URL
|
|
246
|
+
self.api_url = (
|
|
247
|
+
api_url
|
|
248
|
+
or os.getenv("ANTHROPIC_BASE_URL")
|
|
249
|
+
or os.getenv("ANTHROPIC_API_URL")
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
# API key is now optional - CLI can authenticate via OAuth from `claude login`
|
|
253
|
+
|
|
254
|
+
# Setup permission manager. ALWAYS created — even with
|
|
255
|
+
# ``permission_mode="bypassPermissions"`` we still need it for
|
|
256
|
+
# ``AskUserQuestion`` routing (which is an interactive tool, not
|
|
257
|
+
# a permission ask, and must always reach the user).
|
|
258
|
+
self._require_approval = require_approval
|
|
259
|
+
self._permission_manager = PermissionManager(
|
|
260
|
+
parent=self, permission_mode=permission_mode
|
|
261
|
+
)
|
|
262
|
+
# Question requests must work regardless of approval mode — AskUserQuestion
|
|
263
|
+
# is an interactive tool, not a permission gate.
|
|
264
|
+
self._permission_manager.question_requested.connect(
|
|
265
|
+
self.question_requested.emit
|
|
266
|
+
)
|
|
267
|
+
if require_approval:
|
|
268
|
+
# Forward standard permission requests to our signal
|
|
269
|
+
self._permission_manager.permission_requested.connect(
|
|
270
|
+
self.permission_requested.emit
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
# Create MCP tools server with Qt tools
|
|
274
|
+
self.qt_tools = create_qt_tools_server(target_window)
|
|
275
|
+
|
|
276
|
+
# Build allowed tools list - start with Qt tools
|
|
277
|
+
allowed_tools = [
|
|
278
|
+
"mcp__qt__screenshot",
|
|
279
|
+
"mcp__qt__get_widget_tree",
|
|
280
|
+
"mcp__qt__find_widget",
|
|
281
|
+
"mcp__qt__click_widget",
|
|
282
|
+
"mcp__qt__type_text",
|
|
283
|
+
"mcp__qt__show_controller",
|
|
284
|
+
"mcp__qt__get_recent_logs",
|
|
285
|
+
]
|
|
286
|
+
|
|
287
|
+
mcp_servers: dict[str, Any] = {"qt": self.qt_tools}
|
|
288
|
+
|
|
289
|
+
# Per-plugin server assembly from AgentRegistry
|
|
290
|
+
from lightfall.claude._session_assembly import (
|
|
291
|
+
assemble_mcp_servers,
|
|
292
|
+
init_session_plugin_dir,
|
|
293
|
+
materialize_skill,
|
|
294
|
+
)
|
|
295
|
+
from lightfall.ui.panels.claude.agent_registry import AgentRegistry
|
|
296
|
+
|
|
297
|
+
enabled = AgentRegistry.get_instance().enabled_plugins()
|
|
298
|
+
agent_servers, agent_allowed = assemble_mcp_servers(enabled)
|
|
299
|
+
mcp_servers.update(agent_servers)
|
|
300
|
+
allowed_tools.extend(agent_allowed)
|
|
301
|
+
|
|
302
|
+
# Synthesize per-session SDK plugin dir
|
|
303
|
+
self._session_plugin_dir = Path(tempfile.mkdtemp(prefix="lightfall_claude_"))
|
|
304
|
+
init_session_plugin_dir(self._session_plugin_dir)
|
|
305
|
+
for plugin in enabled:
|
|
306
|
+
materialize_skill(plugin, self._session_plugin_dir)
|
|
307
|
+
|
|
308
|
+
# Build system prompt
|
|
309
|
+
system_prompt = QT_SYSTEM_PROMPT
|
|
310
|
+
if additional_system_prompt:
|
|
311
|
+
system_prompt = f"{system_prompt}\n\n{additional_system_prompt}"
|
|
312
|
+
|
|
313
|
+
# Configure Claude options
|
|
314
|
+
options_dict = {
|
|
315
|
+
"plugins": [{"type": "local", "path": str(self._session_plugin_dir)}],
|
|
316
|
+
"mcp_servers": mcp_servers,
|
|
317
|
+
"allowed_tools": allowed_tools,
|
|
318
|
+
"system_prompt": system_prompt,
|
|
319
|
+
"permission_mode": permission_mode,
|
|
320
|
+
"max_turns": max_turns,
|
|
321
|
+
# Opus 4.7's CLI default is --thinking-display omitted, which makes
|
|
322
|
+
# ThinkingBlock.thinking arrive empty. Opt in to summarized text so
|
|
323
|
+
# the agent panel's thinking boxes have content.
|
|
324
|
+
"thinking": {"type": "adaptive", "display": "summarized"},
|
|
325
|
+
# Stream per-token deltas so the chat bubble grows live instead of
|
|
326
|
+
# waiting for the whole block. The worker translates these into
|
|
327
|
+
# partial_* signals and the widget appends as they arrive.
|
|
328
|
+
"include_partial_messages": True,
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
# Add CLI path if provided
|
|
332
|
+
if cli_path:
|
|
333
|
+
options_dict["cli_path"] = cli_path
|
|
334
|
+
|
|
335
|
+
# Set API key and URL directly in os.environ rather than passing via options.
|
|
336
|
+
# This avoids Windows command line length limits (8191 chars) that occur when
|
|
337
|
+
# the entire environment is serialized to command line arguments.
|
|
338
|
+
if self.api_key:
|
|
339
|
+
os.environ["ANTHROPIC_API_KEY"] = self.api_key
|
|
340
|
+
if self.api_url:
|
|
341
|
+
os.environ["ANTHROPIC_BASE_URL"] = self.api_url
|
|
342
|
+
# Note: subprocess will inherit os.environ automatically, no need to pass env
|
|
343
|
+
|
|
344
|
+
# Register can_use_tool + PreToolUse hook ALWAYS. They serve two
|
|
345
|
+
# purposes:
|
|
346
|
+
# 1. Route ``AskUserQuestion`` to our question UI. This must work
|
|
347
|
+
# regardless of ``permission_mode`` — even with
|
|
348
|
+
# ``bypassPermissions`` the user wants to see the question.
|
|
349
|
+
# 2. Gate normal tools through the approval UI when require_approval.
|
|
350
|
+
# With require_approval=False (the bypassPermissions path), the
|
|
351
|
+
# hook returns ``{}`` for non-AskUserQuestion tools so the CLI's
|
|
352
|
+
# auto-allow takes effect.
|
|
353
|
+
options_dict["can_use_tool"] = create_can_use_tool_callback(
|
|
354
|
+
self._permission_manager, require_approval=require_approval,
|
|
355
|
+
)
|
|
356
|
+
try:
|
|
357
|
+
from claude_agent_sdk import HookMatcher
|
|
358
|
+
options_dict["hooks"] = {
|
|
359
|
+
"PreToolUse": [
|
|
360
|
+
HookMatcher(
|
|
361
|
+
matcher=None, # match all tools
|
|
362
|
+
hooks=[create_pre_tool_use_hook(
|
|
363
|
+
self._permission_manager,
|
|
364
|
+
require_approval=require_approval,
|
|
365
|
+
)],
|
|
366
|
+
)
|
|
367
|
+
],
|
|
368
|
+
}
|
|
369
|
+
except ImportError:
|
|
370
|
+
logger.debug("HookMatcher not available, using can_use_tool only")
|
|
371
|
+
|
|
372
|
+
self.options = ClaudeAgentOptions(**options_dict)
|
|
373
|
+
|
|
374
|
+
# Create Claude SDK client
|
|
375
|
+
self.client = ClaudeSDKClient(options=self.options)
|
|
376
|
+
|
|
377
|
+
# Persistent worker reference
|
|
378
|
+
self._worker: PersistentClaudeWorker | None = None
|
|
379
|
+
self._is_connected = False
|
|
380
|
+
|
|
381
|
+
def _ensure_connected(self) -> bool:
|
|
382
|
+
"""
|
|
383
|
+
Ensure the persistent worker is connected.
|
|
384
|
+
|
|
385
|
+
Returns:
|
|
386
|
+
True if connected, False otherwise
|
|
387
|
+
"""
|
|
388
|
+
if self._is_connected and self._worker and self._worker.isRunning():
|
|
389
|
+
return True
|
|
390
|
+
|
|
391
|
+
# Create and start persistent worker
|
|
392
|
+
self._worker = PersistentClaudeWorker(
|
|
393
|
+
self.client,
|
|
394
|
+
permission_manager=self._permission_manager,
|
|
395
|
+
parent=self,
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
# Connect signals
|
|
399
|
+
self._worker.message_received.connect(self.message_received)
|
|
400
|
+
self._worker.thinking_received.connect(self.thinking_received)
|
|
401
|
+
self._worker.tool_called.connect(self.tool_called)
|
|
402
|
+
self._worker.tool_result.connect(self.tool_result)
|
|
403
|
+
self._worker.error_occurred.connect(self.error_occurred)
|
|
404
|
+
self._worker.query_completed.connect(self.query_completed)
|
|
405
|
+
self._worker.query_cancelled.connect(self.query_cancelled)
|
|
406
|
+
self._worker.result_received.connect(self.result_received)
|
|
407
|
+
|
|
408
|
+
# Partial streaming forwards
|
|
409
|
+
self._worker.partial_block_started.connect(self.partial_block_started)
|
|
410
|
+
self._worker.partial_text.connect(self.partial_text)
|
|
411
|
+
self._worker.partial_thinking.connect(self.partial_thinking)
|
|
412
|
+
self._worker.partial_block_finished.connect(self.partial_block_finished)
|
|
413
|
+
|
|
414
|
+
# Task tool subagent forwards
|
|
415
|
+
self._worker.task_started.connect(self.task_started)
|
|
416
|
+
self._worker.task_progress.connect(self.task_progress)
|
|
417
|
+
self._worker.task_finished.connect(self.task_finished)
|
|
418
|
+
|
|
419
|
+
# Track connection result
|
|
420
|
+
result = {"success": False, "error": None}
|
|
421
|
+
|
|
422
|
+
def on_connected():
|
|
423
|
+
self._is_connected = True
|
|
424
|
+
result["success"] = True
|
|
425
|
+
|
|
426
|
+
def on_error(error):
|
|
427
|
+
result["error"] = error
|
|
428
|
+
result["success"] = False
|
|
429
|
+
|
|
430
|
+
self._worker.connected.connect(on_connected)
|
|
431
|
+
self._worker.error_occurred.connect(on_error)
|
|
432
|
+
|
|
433
|
+
# Start worker (will connect in background)
|
|
434
|
+
self._worker.start()
|
|
435
|
+
|
|
436
|
+
# Wait for connection - process Qt events while waiting
|
|
437
|
+
import time
|
|
438
|
+
|
|
439
|
+
from PySide6.QtWidgets import QApplication
|
|
440
|
+
timeout = 30 # seconds
|
|
441
|
+
start_time = time.time()
|
|
442
|
+
while not result["success"] and time.time() - start_time < timeout:
|
|
443
|
+
QApplication.processEvents() # Process Qt events including signals
|
|
444
|
+
time.sleep(0.01)
|
|
445
|
+
if result.get("success") or not self._worker.isRunning():
|
|
446
|
+
break
|
|
447
|
+
|
|
448
|
+
# If connection failed, emit the detailed error
|
|
449
|
+
if not result["success"] and result.get("error"):
|
|
450
|
+
self.error_occurred.emit(result["error"])
|
|
451
|
+
|
|
452
|
+
return result["success"]
|
|
453
|
+
|
|
454
|
+
def query_sync(self, prompt: str) -> None:
|
|
455
|
+
"""
|
|
456
|
+
Send a query to Claude (non-blocking).
|
|
457
|
+
|
|
458
|
+
This method sends a query to the persistent worker. The worker processes
|
|
459
|
+
the query asynchronously and emits signals as responses are received.
|
|
460
|
+
|
|
461
|
+
Args:
|
|
462
|
+
prompt: The prompt/question to send to Claude
|
|
463
|
+
"""
|
|
464
|
+
# Ensure connected
|
|
465
|
+
if not self._ensure_connected():
|
|
466
|
+
self.error_occurred.emit("Failed to connect to Claude")
|
|
467
|
+
return
|
|
468
|
+
|
|
469
|
+
# Send query to worker (non-blocking)
|
|
470
|
+
self._worker.send_query(prompt)
|
|
471
|
+
|
|
472
|
+
async def query(self, prompt: str) -> None:
|
|
473
|
+
"""
|
|
474
|
+
Send a query to Claude (async version).
|
|
475
|
+
|
|
476
|
+
This is an async wrapper that runs query_sync in a thread pool.
|
|
477
|
+
Prefer query_sync for simplicity in Qt applications.
|
|
478
|
+
|
|
479
|
+
Args:
|
|
480
|
+
prompt: The prompt/question to send to Claude
|
|
481
|
+
"""
|
|
482
|
+
import asyncio
|
|
483
|
+
loop = asyncio.get_event_loop()
|
|
484
|
+
await loop.run_in_executor(None, self.query_sync, prompt)
|
|
485
|
+
|
|
486
|
+
def stop(self) -> None:
|
|
487
|
+
"""
|
|
488
|
+
Stop the worker and disconnect.
|
|
489
|
+
"""
|
|
490
|
+
if self._worker and self._worker.isRunning():
|
|
491
|
+
self._worker.stop()
|
|
492
|
+
if not self._worker.wait(5000): # 5s timeout
|
|
493
|
+
logger.warning("Claude worker did not stop in time, terminating")
|
|
494
|
+
self._worker.terminate()
|
|
495
|
+
self._worker.wait(1000)
|
|
496
|
+
self._is_connected = False
|
|
497
|
+
|
|
498
|
+
# Clean up the per-session SDK plugin dir
|
|
499
|
+
if hasattr(self, "_session_plugin_dir") and self._session_plugin_dir.exists():
|
|
500
|
+
shutil.rmtree(self._session_plugin_dir, ignore_errors=True)
|
|
501
|
+
|
|
502
|
+
def is_busy(self) -> bool:
|
|
503
|
+
"""
|
|
504
|
+
Check if a query is currently running.
|
|
505
|
+
|
|
506
|
+
Returns:
|
|
507
|
+
True if a query is in progress, False otherwise
|
|
508
|
+
"""
|
|
509
|
+
if self._worker and self._worker.isRunning():
|
|
510
|
+
# Check both: items in queue OR actively processing
|
|
511
|
+
return self._worker.is_processing or not self._worker._query_queue.empty()
|
|
512
|
+
return False
|
|
513
|
+
|
|
514
|
+
def cancel(self) -> bool:
|
|
515
|
+
"""
|
|
516
|
+
Cancel the current query if one is running.
|
|
517
|
+
|
|
518
|
+
This requests cancellation of the current query. The cancellation
|
|
519
|
+
happens at the next check point during response processing. The
|
|
520
|
+
query_cancelled signal will be emitted when cancellation completes.
|
|
521
|
+
|
|
522
|
+
Returns:
|
|
523
|
+
True if a cancellation was requested, False if no query was running.
|
|
524
|
+
"""
|
|
525
|
+
if self._worker and self._worker.isRunning():
|
|
526
|
+
return self._worker.cancel_current_query()
|
|
527
|
+
return False
|
|
528
|
+
|
|
529
|
+
# --- Permission API ---
|
|
530
|
+
|
|
531
|
+
@property
|
|
532
|
+
def permission_manager(self) -> PermissionManager | None:
|
|
533
|
+
"""
|
|
534
|
+
Get the permission manager.
|
|
535
|
+
|
|
536
|
+
Returns:
|
|
537
|
+
PermissionManager if require_approval=True, else None
|
|
538
|
+
"""
|
|
539
|
+
return self._permission_manager
|
|
540
|
+
|
|
541
|
+
def respond_to_permission(
|
|
542
|
+
self,
|
|
543
|
+
request_id: str,
|
|
544
|
+
allowed: bool,
|
|
545
|
+
always: bool = False,
|
|
546
|
+
message: str = ""
|
|
547
|
+
) -> None:
|
|
548
|
+
"""
|
|
549
|
+
Respond to a permission request.
|
|
550
|
+
|
|
551
|
+
Args:
|
|
552
|
+
request_id: The request ID from permission_requested signal
|
|
553
|
+
allowed: Whether to allow the tool use
|
|
554
|
+
always: If True and allowed, auto-approve this tool in future
|
|
555
|
+
message: Optional message (used as deny reason)
|
|
556
|
+
"""
|
|
557
|
+
if self._permission_manager:
|
|
558
|
+
self._permission_manager.respond(request_id, allowed, always, message)
|
|
559
|
+
|
|
560
|
+
def respond_to_question(
|
|
561
|
+
self,
|
|
562
|
+
request_id: str,
|
|
563
|
+
answers: dict[str, str] | None,
|
|
564
|
+
) -> None:
|
|
565
|
+
"""Provide answers to a pending AskUserQuestion request.
|
|
566
|
+
|
|
567
|
+
Pass ``answers=None`` to indicate the user cancelled the question;
|
|
568
|
+
the agent will reply with a Deny so the model knows.
|
|
569
|
+
"""
|
|
570
|
+
if self._permission_manager:
|
|
571
|
+
self._permission_manager.respond_to_question(request_id, answers)
|
|
572
|
+
|
|
573
|
+
def reset_conversation(self) -> None:
|
|
574
|
+
"""Reset the conversation by stopping the worker.
|
|
575
|
+
|
|
576
|
+
The next query will automatically reconnect with a fresh
|
|
577
|
+
conversation via ``_ensure_connected()``.
|
|
578
|
+
"""
|
|
579
|
+
self.stop()
|
|
580
|
+
logger.info("Claude conversation reset")
|
|
581
|
+
|
|
582
|
+
def add_always_allowed_tool(self, tool_name: str) -> None:
|
|
583
|
+
"""
|
|
584
|
+
Add a tool to the always-allowed list.
|
|
585
|
+
|
|
586
|
+
Args:
|
|
587
|
+
tool_name: Full tool name (e.g., "mcp__qt__click_widget")
|
|
588
|
+
"""
|
|
589
|
+
if self._permission_manager:
|
|
590
|
+
self._permission_manager.add_always_allowed(tool_name)
|
|
591
|
+
|
|
592
|
+
def __del__(self):
|
|
593
|
+
"""
|
|
594
|
+
Cleanup when agent is destroyed.
|
|
595
|
+
"""
|
|
596
|
+
self.stop()
|