From 951961a5d3a52d8fd2738e83ca59eadb5e79d144 Mon Sep 17 00:00:00 2001 From: Fede Luzzi Date: Mon, 9 Nov 2026 17:30:43 -0300 Subject: [PATCH] chore(release): bump version to v6.4.0b4 and update documentation --- README.md | 2 +- connpy/__init__.py | 2 +- connpy/_version.py | 2 +- connpy/connapp.py | 2 +- connpy/mcp_server.py | 10 +- docs/connpy/ai.html | 38 +- docs/connpy/cli/ai_handler.html | 115 +- docs/connpy/cli/run_handler.html | 10 +- docs/connpy/cli/terminal_ui.html | 1308 -------- docs/connpy/grpc_layer/connpy_pb2_grpc.html | 27 +- docs/connpy/grpc_layer/remote_plugin_pb2.html | 8 +- .../grpc_layer/remote_plugin_pb2_grpc.html | 3 +- docs/connpy/grpc_layer/server.html | 20 +- docs/connpy/grpc_layer/stubs.html | 2928 ----------------- docs/connpy/index.html | 151 +- docs/connpy/mcp_client.html | 243 +- docs/connpy/mcp_server.html | 1191 +++++++ docs/connpy/services/ai_service.html | 3 +- docs/connpy/services/base.html | 3 +- docs/connpy/services/config_service.html | 3 +- docs/connpy/services/context_service.html | 3 +- docs/connpy/services/execution_service.html | 3 +- .../services/import_export_service.html | 7 +- docs/connpy/services/index.html | 31 +- docs/connpy/services/node_service.html | 3 +- docs/connpy/services/plugin_service.html | 3 +- docs/connpy/services/profile_service.html | 3 +- docs/connpy/services/sync_service.html | 3 +- docs/connpy/services/system_service.html | 3 +- 29 files changed, 1722 insertions(+), 4406 deletions(-) create mode 100644 docs/connpy/mcp_server.html diff --git a/README.md b/README.md index fd34852..4d71746 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@

-# Connpy (v6.4.0b3) +# Connpy (v6.4.0b4) [![](https://img.shields.io/pypi/v/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/pyversions/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/dm/connpy.svg?style=flat-square&cacheSeconds=86400)](https://pypi.org/pypi/connpy/) diff --git a/connpy/__init__.py b/connpy/__init__.py index 3968d83..840d225 100644 --- a/connpy/__init__.py +++ b/connpy/__init__.py @@ -5,7 +5,7 @@

-# Connpy (v6.4.0b3) +# Connpy (v6.4.0b4) [![](https://img.shields.io/pypi/v/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/pyversions/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/dm/connpy.svg?style=flat-square&cacheSeconds=86400)](https://pypi.org/pypi/connpy/) diff --git a/connpy/_version.py b/connpy/_version.py index 45f48a7..410dcb6 100644 --- a/connpy/_version.py +++ b/connpy/_version.py @@ -1 +1 @@ -__version__ = "6.4.0b3" +__version__ = "6.4.0b4" diff --git a/connpy/connapp.py b/connpy/connapp.py index ba4f058..98203b2 100755 --- a/connpy/connapp.py +++ b/connpy/connapp.py @@ -319,7 +319,7 @@ class connapp: aiparser.add_argument("--session", nargs=1, help="Resume a specific AI session by ID") aiparser.add_argument("--resume", action="store_true", help="Resume the most recent AI session") aiparser.add_argument("--delete", "--delete-session", dest="delete_session", nargs=1, help="Delete an AI session by ID") - aiparser.add_argument("--mcp", nargs='*', metavar=('ACTION', 'NAME'), help="Manage MCP servers. Actions: list, add, remove, enable, disable. Leave empty for interactive wizard.") + aiparser.add_argument("--mcp", nargs=argparse.REMAINDER, metavar=('ACTION', 'NAME'), help="Manage MCP servers. Actions: list, add, remove, enable, disable, serve. Leave empty for interactive wizard.") aiparser.set_defaults(func=self._ai.dispatch) #RUNPARSER runparser = subparsers.add_parser("run", help="Run scripts or commands on nodes", description="Run scripts or commands on nodes", formatter_class=RichHelpFormatter) diff --git a/connpy/mcp_server.py b/connpy/mcp_server.py index b78e95d..cbc894e 100644 --- a/connpy/mcp_server.py +++ b/connpy/mcp_server.py @@ -522,7 +522,15 @@ class ConnpyMCPServer: return self.server.run(transport="stdio", **kwargs) if transport == "sse": - return self.server.run(transport="sse", host=host, port=port, **kwargs) + if hasattr(self.server, "settings"): + if hasattr(self.server.settings, "host"): + self.server.settings.host = host + if hasattr(self.server.settings, "port"): + self.server.settings.port = port + try: + return self.server.run(transport="sse", host=host, port=port, **kwargs) + except TypeError: + return self.server.run(transport="sse", **kwargs) msg = f"Unknown transport: {transport}. Supported transports: 'stdio', 'sse'" raise ValueError(msg) diff --git a/docs/connpy/ai.html b/docs/connpy/ai.html index 9f71e5f..5284b0a 100644 --- a/docs/connpy/ai.html +++ b/docs/connpy/ai.html @@ -150,7 +150,7 @@ el.replaceWith(d); import yaml try: # 1. Parse YAML - data = yaml.load(playbook_yaml, Loader=yaml.FullLoader) + data = yaml.safe_load(playbook_yaml) except Exception as e: return {"valid": False, "error": f"YAML Syntax Error: {e}"} @@ -473,7 +473,7 @@ el.replaceWith(d); import yaml try: # 1. Parse YAML - data = yaml.load(playbook_yaml, Loader=yaml.FullLoader) + data = yaml.safe_load(playbook_yaml) except Exception as e: return {"valid": False, "error": f"YAML Syntax Error: {e}"} @@ -638,6 +638,9 @@ class ai: self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json") if self.session_id else None # Agnostic base prompts + self._update_base_prompts() + + def _update_base_prompts(self): architect_instructions = "" if self.has_architect: architect_instructions = """ @@ -678,7 +681,7 @@ class ai: - NO WANDERING: Do not speculate. If stuck, report attempts. - SAFETY: When you use 'run_commands' with configuration commands, the system automatically prompts the user for confirmation. Just execute - don't ask permission first. {architect_instructions} - Network Context: {{self.long_term_memory if self.long_term_memory else "Empty."}} + Network Context: {self.long_term_memory if self.long_term_memory else "Empty."} """).strip() self._architect_base_prompt = dedent(f""" @@ -718,6 +721,7 @@ class ai: @property def engineer_system_prompt(self): """Build engineer system prompt with plugin extensions.""" + self._update_base_prompts() if self.engineer_prompt_extensions: extensions = "\n".join(self.engineer_prompt_extensions) return self._engineer_base_prompt + f"\n\nPlugin Capabilities:\n{extensions}" @@ -726,6 +730,7 @@ class ai: @property def architect_system_prompt(self): """Build architect system prompt with plugin extensions.""" + self._update_base_prompts() prompt = self._architect_base_prompt if getattr(self, "one_shot", False): prompt += "\n\nCRITICAL 1-SHOT DIAGNOSTICS DIRECTIVE:\nYou are running in a 1-shot offline diagnostics mode. There is no active conversation loop, and you are NOT conversing with a Network Engineer. You MUST deliver your complete strategic analysis immediately and directly to the user. Do not suggest or attempt to delegate/return control to the engineer." @@ -1065,6 +1070,7 @@ class ai: # Reload memory after update with open(self.memory_path, "r") as f: self.long_term_memory = f.read() + self._update_base_prompts() return "Memory updated successfully." except PermissionError as e: @@ -1300,7 +1306,7 @@ class ai: # Silently fail for LLM tools pass - if self.architect_key: + if self.has_architect: base_tools.extend([ {"type": "function", "function": {"name": "consult_architect", "description": "Ask the Strategic Reasoning Engine for advice on complex design, architecture, or troubleshooting decisions. You remain in control and will present the response to the user. Use this for: configuration planning, design validation, complex troubleshooting.", "parameters": {"type": "object", "properties": {"question": {"type": "string", "description": "Strategic question or decision needed."}, "technical_summary": {"type": "string", "description": "Technical findings and context gathered so far."}}, "required": ["question", "technical_summary"]}}}, {"type": "function", "function": {"name": "escalate_to_architect", "description": "Transfer full control to the Strategic Reasoning Engine. Use ONLY when the user explicitly requests the Architect or when the problem requires strategic oversight beyond consultation. After escalation, the Architect takes over the conversation.", "parameters": {"type": "object", "properties": {"reason": {"type": "string", "description": "Why you're escalating (e.g. 'User requested Architect', 'Complex multi-site design needed')."}, "context": {"type": "string", "description": "Full context and findings to hand over."}}, "required": ["reason", "context"]}}} @@ -1657,14 +1663,17 @@ class ai: if status: update_status("[architect]Engineer consulting Architect...") try: # Consultation only - Engineer stays in control + auth_kwargs = dict(self.architect_auth or {}) + if self.architect_key and "api_key" not in auth_kwargs: + auth_kwargs["api_key"] = self.architect_key claude_resp = completion( model=self.architect_model, messages=[ {"role": "system", "content": self.architect_system_prompt}, {"role": "user", "content": f"The Engineer needs your strategic advice.\n\nTECHNICAL SUMMARY: {args['technical_summary']}\n\nQUESTION: {args['question']}\n\nProvide strategic guidance. The Engineer will continue handling the user."} ], - api_key=self.architect_key, - num_retries=3 + num_retries=3, + **auth_kwargs ) obs = claude_resp.choices[0].message.content if debug: @@ -2101,11 +2110,11 @@ Node: {node_name}"""
var SAFE_COMMANDS
-

The type of the None singleton.

+
var deferred_class_hooks
-

The type of the None singleton.

+

Instance variables

@@ -2119,6 +2128,7 @@ Node: {node_name}"""
@property
 def architect_system_prompt(self):
     """Build architect system prompt with plugin extensions."""
+    self._update_base_prompts()
     prompt = self._architect_base_prompt
     if getattr(self, "one_shot", False):
         prompt += "\n\nCRITICAL 1-SHOT DIAGNOSTICS DIRECTIVE:\nYou are running in a 1-shot offline diagnostics mode. There is no active conversation loop, and you are NOT conversing with a Network Engineer. You MUST deliver your complete strategic analysis immediately and directly to the user. Do not suggest or attempt to delegate/return control to the engineer."
@@ -2138,6 +2148,7 @@ def architect_system_prompt(self):
 
@property
 def engineer_system_prompt(self):
     """Build engineer system prompt with plugin extensions."""
+    self._update_base_prompts()
     if self.engineer_prompt_extensions:
         extensions = "\n".join(self.engineer_prompt_extensions)
         return self._engineer_base_prompt + f"\n\nPlugin Capabilities:\n{extensions}"
@@ -2661,14 +2672,17 @@ def ask(self, user_input, dryrun=False, chat_history=None, status=None, debug=Fa
                     if status: update_status("[architect]Engineer consulting Architect...")
                     try:
                         # Consultation only - Engineer stays in control
+                        auth_kwargs = dict(self.architect_auth or {})
+                        if self.architect_key and "api_key" not in auth_kwargs:
+                            auth_kwargs["api_key"] = self.architect_key
                         claude_resp = completion(
                             model=self.architect_model, 
                             messages=[
                                 {"role": "system", "content": self.architect_system_prompt},
                                 {"role": "user", "content": f"The Engineer needs your strategic advice.\n\nTECHNICAL SUMMARY: {args['technical_summary']}\n\nQUESTION: {args['question']}\n\nProvide strategic guidance. The Engineer will continue handling the user."}
                             ], 
-                            api_key=self.architect_key, 
-                            num_retries=3
+                            num_retries=3,
+                            **auth_kwargs
                         )
                         obs = claude_resp.choices[0].message.content
                         if debug:
@@ -2976,6 +2990,7 @@ def confirm(self, user_input): return True
# Reload memory after update with open(self.memory_path, "r") as f: self.long_term_memory = f.read() + self._update_base_prompts() return "Memory updated successfully." except PermissionError as e: @@ -3024,8 +3039,9 @@ def confirm(self, user_input): return True
self.tool_status_formatters[name] = status_formatter

Register an external tool for the AI system.

-

Args

+
Args
+
-----=
tool_definition : dict
OpenAI-compatible tool definition.
handler : callable
diff --git a/docs/connpy/cli/ai_handler.html b/docs/connpy/cli/ai_handler.html index f7beb7a..f96e7fe 100644 --- a/docs/connpy/cli/ai_handler.html +++ b/docs/connpy/cli/ai_handler.html @@ -83,7 +83,7 @@ el.replaceWith(d); try: self.app.services.ai.delete_session(args.delete_session[0]) printer.success(f"Session {args.delete_session[0]} deleted.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e)) return @@ -236,7 +236,7 @@ el.replaceWith(d); try: self.app.services.ai.configure_mcp(name, url=url, auto_load_on_os=os_filter) printer.success(f"MCP server '{name}' added/updated.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e)) return @@ -248,7 +248,7 @@ el.replaceWith(d); try: self.app.services.ai.configure_mcp(name, remove=True) printer.success(f"MCP server '{name}' removed.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e)) return @@ -261,13 +261,54 @@ el.replaceWith(d); try: self.app.services.ai.configure_mcp(name, enabled=enabled) printer.success(f"MCP server '{name}' {'enabled' if enabled else 'disabled'}.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e)) return + + elif action == "serve": + transport = "stdio" + host = "127.0.0.1" + port = 8000 + trust = getattr(args, "trust", False) + + idx = 1 + while idx < len(mcp_args): + tok = mcp_args[idx] + if tok in ["--sse", "sse"]: + transport = "sse" + elif tok in ["--stdio", "stdio"]: + transport = "stdio" + elif tok in ["--trust", "trust"]: + trust = True + elif tok in ["--port", "-p"]: + idx += 1 + if idx < len(mcp_args): + try: + port = int(mcp_args[idx]) + except ValueError: + printer.error(f"Invalid port: {mcp_args[idx]}") + return + elif tok.startswith("--port="): + try: + port = int(tok.split("=", 1)[1]) + except ValueError: + printer.error(f"Invalid port: {tok}") + return + elif tok in ["--host", "-h"]: + idx += 1 + if idx < len(mcp_args): + host = mcp_args[idx] + elif tok.startswith("--host="): + host = tok.split("=", 1)[1] + idx += 1 + + from ..mcp_server import ConnpyMCPServer + server = ConnpyMCPServer(config=self.app.config, services=self.app.services, trust=trust) + return server.run(transport=transport, host=host, port=port) else: printer.error(f"Unknown MCP action: {action}") - printer.info("Available actions: list, add, remove, enable, disable") + printer.info("Available actions: list, add, remove, enable, disable, serve") return # 2. Interactive Wizard Mode (if no arguments provided) @@ -309,15 +350,16 @@ el.replaceWith(d); self.app.services.ai.configure_mcp(result["name"], remove=True) printer.success(f"MCP server '{result['name']}' removed.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e)) def _parse_auth_value(self, value): if not value or value.lower() in ["none", "clear"]: return None - import os - import yaml import json + import os + + import yaml if os.path.exists(value): try: with open(value, "r") as f: @@ -326,7 +368,7 @@ el.replaceWith(d); return json.loads(content) except ValueError: return yaml.safe_load(content) - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(f"Failed to read/parse auth file '{value}': {e}") sys.exit(1) @@ -338,7 +380,7 @@ el.replaceWith(d); if isinstance(parsed, dict): return parsed raise ValueError() - except Exception: + except Exception: # noqa: BLE001 printer.error("Auth parameter must be a valid JSON/YAML string, or a path to a JSON/YAML file.") sys.exit(1) @@ -387,7 +429,7 @@ el.replaceWith(d); try: self.app.services.ai.configure_mcp(name, url=url, auto_load_on_os=os_filter) printer.success(f"MCP server '{name}' added/updated.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e)) return @@ -399,7 +441,7 @@ el.replaceWith(d); try: self.app.services.ai.configure_mcp(name, remove=True) printer.success(f"MCP server '{name}' removed.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e)) return @@ -412,13 +454,54 @@ el.replaceWith(d); try: self.app.services.ai.configure_mcp(name, enabled=enabled) printer.success(f"MCP server '{name}' {'enabled' if enabled else 'disabled'}.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e)) return + + elif action == "serve": + transport = "stdio" + host = "127.0.0.1" + port = 8000 + trust = getattr(args, "trust", False) + + idx = 1 + while idx < len(mcp_args): + tok = mcp_args[idx] + if tok in ["--sse", "sse"]: + transport = "sse" + elif tok in ["--stdio", "stdio"]: + transport = "stdio" + elif tok in ["--trust", "trust"]: + trust = True + elif tok in ["--port", "-p"]: + idx += 1 + if idx < len(mcp_args): + try: + port = int(mcp_args[idx]) + except ValueError: + printer.error(f"Invalid port: {mcp_args[idx]}") + return + elif tok.startswith("--port="): + try: + port = int(tok.split("=", 1)[1]) + except ValueError: + printer.error(f"Invalid port: {tok}") + return + elif tok in ["--host", "-h"]: + idx += 1 + if idx < len(mcp_args): + host = mcp_args[idx] + elif tok.startswith("--host="): + host = tok.split("=", 1)[1] + idx += 1 + + from ..mcp_server import ConnpyMCPServer + server = ConnpyMCPServer(config=self.app.config, services=self.app.services, trust=trust) + return server.run(transport=transport, host=host, port=port) else: printer.error(f"Unknown MCP action: {action}") - printer.info("Available actions: list, add, remove, enable, disable") + printer.info("Available actions: list, add, remove, enable, disable, serve") return # 2. Interactive Wizard Mode (if no arguments provided) @@ -460,7 +543,7 @@ el.replaceWith(d); self.app.services.ai.configure_mcp(result["name"], remove=True) printer.success(f"MCP server '{result['name']}' removed.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e))

Handle MCP server configuration via CLI tokens or interactive wizard.

@@ -497,7 +580,7 @@ el.replaceWith(d); try: self.app.services.ai.delete_session(args.delete_session[0]) printer.success(f"Session {args.delete_session[0]} deleted.") - except Exception as e: + except Exception as e: # noqa: BLE001 printer.error(str(e)) return diff --git a/docs/connpy/cli/run_handler.html b/docs/connpy/cli/run_handler.html index b842927..d56bfc4 100644 --- a/docs/connpy/cli/run_handler.html +++ b/docs/connpy/cli/run_handler.html @@ -210,7 +210,10 @@ el.replaceWith(d); path = args.data[0] try: with open(path, "r") as f: - playbook = yaml.load(f, Loader=yaml.FullLoader) + playbook = yaml.safe_load(f) + + if not isinstance(playbook, dict): + raise TypeError("Invalid playbook format: expected a dictionary") # Check preflight first before any task runs if getattr(args, "preflight_ai", False): @@ -1021,7 +1024,10 @@ el.replaceWith(d); path = args.data[0] try: with open(path, "r") as f: - playbook = yaml.load(f, Loader=yaml.FullLoader) + playbook = yaml.safe_load(f) + + if not isinstance(playbook, dict): + raise TypeError("Invalid playbook format: expected a dictionary") # Check preflight first before any task runs if getattr(args, "preflight_ai", False): diff --git a/docs/connpy/cli/terminal_ui.html b/docs/connpy/cli/terminal_ui.html index 122a609..53f8558 100644 --- a/docs/connpy/cli/terminal_ui.html +++ b/docs/connpy/cli/terminal_ui.html @@ -44,1304 +44,6 @@ el.replaceWith(d);
-

Classes

-
-
-class CopilotInterface -(config,
history=None,
pt_input=None,
pt_output=None,
rich_file=None,
session_state=None)
-
-
-
- -Expand source code - -
class CopilotInterface:
-    def __init__(self, config, history=None, pt_input=None, pt_output=None, rich_file=None, session_state=None):
-        from ..services.ai_service import AIService
-        self.config = config
-        self.history = history or InMemoryHistory()
-        self.pt_input = pt_input
-        self.pt_output = pt_output
-        self.rich_file = rich_file
-        self.ai_service = AIService(config)
-        self.mode_range, self.mode_single, self.mode_lines = 0, 1, 2 
-
-        self.session_state = session_state if session_state is not None else {}
-        self.session_state.setdefault('persona', 'engineer')
-        self.session_state.setdefault('trust_mode', False)
-        self.session_state.setdefault('memories', [])
-        self.session_state.setdefault('copilot_chat_history', [])
-        self.session_state.setdefault('os', None)
-        self.session_state.setdefault('prompt', None)
-        self.session_state.setdefault('context_mode', self.mode_range)
-        self.session_state.setdefault('context_cmd', 1)
-        self.session_state.setdefault('context_lines', 50)
-        self.session_state.setdefault('last_total_cmds', None)
-        self.session_state.setdefault('last_total_lines', None)
-
-        if rich_file:
-            self.console = Console(theme=connpy_theme, force_terminal=True, file=rich_file)
-        else:
-            self.console = Console(theme=connpy_theme)
-
-    def _sync_session_context(self, state: dict):
-        """Persist current context mode, depth, total commands, and total lines into session_state."""
-        self.session_state['context_mode'] = state['context_mode']
-        self.session_state['context_cmd'] = state['context_cmd']
-        self.session_state['context_lines'] = state['context_lines']
-        self.session_state['last_total_cmds'] = state['total_cmds']
-        self.session_state['last_total_lines'] = state['total_lines']
-
-    def _get_theme_color(self, style_name: str, fallback: str = "white") -> str:
-        """Extract Hex or ANSI color name from the active rich theme."""
-        try:
-            style = connpy_theme.styles.get(style_name)
-            if style and style.color:
-                # If it's a standard color like 'green', Rich might return its hex triplet
-                if style.color.is_default: return fallback
-                return style.color.triplet.hex if style.color.triplet else style.color.name
-        except: pass
-        return fallback
-
-    async def run_session(self, 
-                          raw_bytes: bytes, 
-                          node_info: dict,
-                          on_ai_call: Callable,
-                          cmd_byte_positions: List[tuple] = None, 
-                          blocks: List[tuple] = None):
-        """
-        Runs the interactive Copilot session.
-        on_ai_call: async function(active_buffer, question) -> result_dict
-        """
-        from rich.rule import Rule
-        
-        try:
-            # Prepare UI state
-            buffer = log_cleaner(raw_bytes.decode(errors='replace'))
-            
-            # Use pre-calculated blocks if provided (remote mode), otherwise calculate locally (local mode)
-            if blocks is None:
-                last_line = buffer.split('\n')[-1].strip() if buffer.strip() else "(prompt)"
-                blocks = self.ai_service.build_context_blocks(raw_bytes, cmd_byte_positions, node_info, last_line=last_line)
-            
-            total_cmds = len(blocks)
-            total_lines = len(buffer.split('\n'))
-
-            saved_mode = self.session_state.get('context_mode', self.mode_range)
-            saved_cmd = self.session_state.get('context_cmd', 1)
-            saved_lines = self.session_state.get('context_lines', min(50, total_lines))
-            last_total_cmds = self.session_state.get('last_total_cmds', None)
-            last_total_lines = self.session_state.get('last_total_lines', None)
-
-            is_range = saved_mode in (self.mode_range, 0, 'RANGE', 'range')
-            is_lines = saved_mode in (self.mode_lines, 2, 'LINES', 'lines')
-            is_single = saved_mode in (self.mode_single, 1, 'SINGLE', 'single')
-
-            if is_range or is_single:
-                is_mission = self.session_state.get('mission', {}).get('active', False)
-                if last_total_cmds is not None and total_cmds > last_total_cmds and (saved_cmd > 1 or is_mission):
-                    new_cmds = total_cmds - last_total_cmds
-                    initial_cmd = saved_cmd + new_cmds
-                else:
-                    initial_cmd = saved_cmd
-                initial_lines = saved_lines
-            elif is_lines:
-                if last_total_lines is not None and total_lines > last_total_lines and saved_lines > 50:
-                    new_lines = total_lines - last_total_lines
-                    initial_lines = saved_lines + new_lines
-                else:
-                    initial_lines = saved_lines
-                initial_cmd = saved_cmd
-            else:
-                initial_cmd = saved_cmd
-                initial_lines = saved_lines
-
-            state = {
-                'context_cmd': min(max(1, initial_cmd), max(1, total_cmds)),
-                'total_cmds': total_cmds,
-                'total_lines': total_lines,
-                'context_lines': min(max(1, initial_lines), max(1, total_lines)),
-                'context_mode': saved_mode,
-                'cancelled': False,
-                'toolbar_msg': '',
-                'msg_expiry': 0
-            }
-            self.session_state['context_mode'] = saved_mode
-            self.session_state['context_cmd'] = max(1, initial_cmd)
-            self.session_state['context_lines'] = max(1, initial_lines)
-            self.session_state['last_total_cmds'] = total_cmds
-            self.session_state['last_total_lines'] = total_lines
-            
-            # 1. Visual Separation (Only show help banner on initial entry)
-            self.console.print("") # Real line break
-            self.console.print(Rule(title="[bold cyan] AI TERMINAL COPILOT [/bold cyan]", style="cyan"))
-            if not self.session_state.get('banner_shown', False):
-                self.console.print(Panel(
-                    "[dim]Type your question. Enter to send, Escape/Ctrl+C to cancel. Type / for commands.\n"
-                    "Tab to change context mode. Ctrl+\u2191/\u2193 to adjust context. \u2191\u2193 for question history.[/dim]",
-                    border_style="cyan"
-                ))
-                self.session_state['banner_shown'] = True
-            self.console.print("") # Small space before the copilot prompt
-
-            bindings = KeyBindings()
-            @bindings.add('c-up')
-            def _(event):
-                if state['context_mode'] == self.mode_lines:
-                    state['context_lines'] = min(state['context_lines'] + 50, state['total_lines'])
-                else:
-                    state['context_cmd'] = min(state['context_cmd'] + 1, state['total_cmds'])
-                self._sync_session_context(state)
-                event.app.invalidate()
-            @bindings.add('c-down')
-            def _(event):
-                if state['context_mode'] == self.mode_lines:
-                    state['context_lines'] = max(state['context_lines'] - 50, min(50, state['total_lines']))
-                else:
-                    state['context_cmd'] = max(state['context_cmd'] - 1, 1)
-                self._sync_session_context(state)
-                event.app.invalidate()
-            @bindings.add('tab')
-            def _(event):
-                buf = event.current_buffer
-                # If typing a slash command (no spaces yet), use tab to autocomplete inline
-                if buf.text.startswith('/') and ' ' not in buf.text:
-                    buf.complete_next()
-                else:
-                    state['context_mode'] = (state['context_mode'] + 1) % 3
-                    self._sync_session_context(state)
-                    event.app.invalidate()
-            @bindings.add('escape', eager=True)
-            @bindings.add('c-c')
-            def _(event):
-                state['cancelled'] = True
-                event.app.exit(result='')
-
-            # Multiline keybindings: Enter to submit, Ctrl+Enter (c-j) or Alt+Enter to add a newline
-            @bindings.add('enter', filter=~has_completions)
-            def _(event):
-                event.current_buffer.validate_and_handle()
-
-            @bindings.add('c-j')
-            @bindings.add('escape', 'enter')
-            def _(event):
-                event.current_buffer.insert_text('\n')
-
-            def get_active_buffer():
-                if state['context_mode'] == self.mode_lines:
-                    return '\n'.join(buffer.split('\n')[-state['context_lines']:])
-                idx = max(0, state['total_cmds'] - state['context_cmd'])
-                start, end, preview = blocks[idx]
-                if state['context_mode'] == self.mode_single:
-                    active_raw = raw_bytes[start:end]
-                else:
-                    # Concat only the bytes of valid blocks to skip intermediate empty/cancelled prompt noise
-                    active_raw = b"".join(raw_bytes[b[0]:b[1]] for b in blocks[idx:])
-                return preview + "\n" + log_cleaner(active_raw.decode(errors='replace'))
-
-            def get_prompt_text():
-                import html
-                # Always use user_prompt color for the Ask prompt
-                color = self._get_theme_color("user_prompt", "cyan")
-                
-                if state['context_mode'] == self.mode_lines:
-                    text = html.escape(f"Ask [Ctx: {state['context_lines']}/{state['total_lines']}L]: ")
-                    return HTML(f'<style fg="{color}">{text}</style>')
-                active = get_active_buffer()
-                lines_count = len(active.split('\n'))
-                mode_str = {self.mode_range: "Range", self.mode_single: "Cmd"}[state['context_mode']]
-                text = html.escape(f"Ask [{mode_str} {state['context_cmd']} ~{lines_count}L]: ")
-                return HTML(f'<style fg="{color}">{text}</style>')
-
-            from prompt_toolkit.application.current import get_app
-
-            def get_toolbar():
-                import html
-                app = get_app()
-                c_warning = self._get_theme_color("warning", "yellow")
-                
-                if app and app.current_buffer:
-                    text = app.current_buffer.text
-                    # Only show command help if typing the first command and there are no spaces
-                    if text.startswith('/') and ' ' not in text:
-                        commands = ['/os', '/prompt', '/architect', '/engineer', '/trust', '/untrust', '/memorize', '/clear', '/mission', '/cancel']
-                        matches = [c for c in commands if c.startswith(text.lower())]
-                        if matches:
-                            m_text = html.escape(f"Available: {' '.join(matches)}")
-                            return HTML(f'<style fg="{c_warning}">{m_text}</style>' + " " * 20)
-
-                m_label = {self.mode_range: "RANGE", self.mode_single: "SINGLE", self.mode_lines: "LINES"}[state['context_mode']]
-                if state['context_mode'] == self.mode_lines:
-                    base_str = f'\u25b6 [Tab: {m_label}] {state["context_lines"]}/{state["total_lines"]}L (Ctrl+\u2191/\u2193 adjusts lines)'
-                else:
-                    idx = max(0, state['total_cmds'] - state['context_cmd'])
-                    
-                    def clean_preview(text):
-                        # Clean newlines and the initial prompt (all up to #, > or $) to leave only the command
-                        original = text.strip().replace('\r', '').replace('\n', ' ')
-                        cleaned = re.sub(r'^.*?[#>\$]\s*', '', original)
-                        # If cleaning the prompt leaves us with an empty string (e.g. it was just "iol#"), return the original
-                        return cleaned if cleaned else original
-
-                    if state['context_mode'] == self.mode_range:
-                        range_blocks = blocks[idx:]
-                        # If there is more than one block, the last one is always the empty/current prompt. We omit it visually.
-                        if len(range_blocks) > 1:
-                            range_blocks = range_blocks[:-1]
-                            
-                        # Clean and truncate very long commands so they don't break the UI
-                        previews = []
-                        for b in range_blocks:
-                            p = clean_preview(b[2])
-                            if p:
-                                # Truncar comandos individuales largos
-                                if len(p) > 25: p = p[:22].rstrip(' .,-_') + "..."
-                                previews.append(p)
-                        
-                        if not previews:
-                            desc = clean_preview(blocks[idx][2])
-                        elif len(previews) <= 3:
-                            desc = " + ".join(previews)
-                        else:
-                            desc = f"{previews[0]} + {previews[1]} + {previews[2]} (+{len(previews)-3})"
-                    else:
-                        # Modo SINGLE original
-                        desc = clean_preview(blocks[idx][2])
-                        
-                    base_str = f'\u25b6 [Tab: {m_label}] {desc}'
-                
-                # Wrap base_str in a style to maintain consistency and avoid glitches
-                # The fg color will be inherited from bottom-toolbar global style if not specified here
-                base_html = f'<span>{html.escape(base_str)}</span>'
-                
-                res_html = base_html
-                if state.get('toolbar_msg'):
-                    if time.time() < state.get('msg_expiry', 0):
-                        msg = html.escape(state['toolbar_msg'])
-                        res_html = f'<style fg="{c_warning}">⚙️ {msg}</style> | ' + base_html
-                    else:
-                        state['toolbar_msg'] = ''
-                
-                # Pad with spaces to ensure the line is cleared when the message disappears
-                return HTML(res_html + " " * 20)
-
-            from prompt_toolkit.completion import Completer, Completion
-            class SlashCommandCompleter(Completer):
-                def get_completions(self, document, complete_event):
-                    text = document.text_before_cursor
-                    if text.startswith('/'):
-                        parts = text.split()
-                        # Only autocomplete the first word
-                        if len(parts) <= 1 or (len(parts) == 1 and not text.endswith(' ')):
-                            cmd_part = parts[0] if parts else text
-                            commands = [
-                                ('/os', 'Set device OS (e.g. cisco_ios)'),
-                                ('/prompt', 'Override prompt regex'),
-                                ('/architect', 'Switch to Architect persona'),
-                                ('/engineer', 'Switch to Engineer persona'),
-                                ('/trust', 'Enable auto-execute'),
-                                ('/untrust', 'Disable auto-execute'),
-                                ('/memorize', 'Add fact to memory'),
-                                ('/clear', 'Clear memory'),
-                                ('/mission', 'Start autonomous mission'),
-                                ('/cancel', 'Cancel active mission')
-                            ]
-                            for cmd, desc in commands:
-                                if cmd.startswith(cmd_part.lower()):
-                                    yield Completion(cmd, start_position=-len(cmd_part), display_meta=desc)
-
-            copilot_completer = SlashCommandCompleter()
-
-            def _finalize_mission(reason="completed", final_guide=""):
-                mission = self.session_state.get('mission', {})
-                if not mission or not mission.get('active', False):
-                    return
-                mission['active'] = False
-                if reason == "completed":
-                    self.console.print("\n[bold green]🎉 Mission Completed[/bold green]")
-                elif reason == "user_cancelled":
-                    self.console.print("\n[yellow]Mission cancelled by user.[/yellow]")
-                elif reason == "limit_reached":
-                    self.console.print("\n[yellow]Mission step limit reached.[/yellow]")
-
-                final_notes = "\n".join(mission.get('scratchpad_notes', []))
-                guide = final_guide or mission.get('last_guide', '')
-                asst_msg = f"Notes: {final_notes}\nGuide: {guide}" if final_notes else guide
-                hist = self.session_state.setdefault("copilot_chat_history", [])
-                hist.append({"role": "user", "content": f"/mission {mission.get('goal', '')}"})
-                hist.append({"role": "assistant", "content": asst_msg})
-                self.session_state["copilot_chat_history"] = hist[-10:]
-
-            while True:
-                overrides = {}
-                # Check for active mission auto-looping
-                mission = self.session_state.get('mission', {})
-                is_mission = mission.get('active', False) and not mission.get('paused', False)
-
-                if is_mission:
-                    # Force mode_range for mission mode
-                    state['context_mode'] = self.mode_range
-                    self.session_state['context_mode'] = self.mode_range
-
-                    if mission.get('start_block_idx') is None:
-                        mission['start_block_idx'] = state['total_cmds']
-
-                    start_idx = mission.get('start_block_idx', state['total_cmds'])
-                    cmds_since_start = max(1, (state['total_cmds'] - start_idx) + 1)
-                    state['context_cmd'] = max(state.get('context_cmd', 1), cmds_since_start)
-                    self.session_state['context_cmd'] = state['context_cmd']
-
-                    step = mission.get('step', 1)
-                    max_steps = mission.get('max_steps', 10)
-
-                    if step > max_steps:
-                        ext_session = PromptSession(input=self.pt_input, output=self.pt_output)
-                        c_warn = self._get_theme_color("warning", "yellow")
-                        import html
-                        p_warn = html.escape(f"[Mission Limit Reached ({max_steps} steps)] Extend mission for 10 more steps? (y/n) [y]: ")
-                        try:
-                            ext_ans = await ext_session.prompt_async(HTML(f'<style fg="{c_warn}" bold="true">{p_warn}</style>'))
-                        except (KeyboardInterrupt, EOFError):
-                            ext_ans = 'n'
-
-                        if (ext_ans or 'y').lower().strip() in ('y', 'yes'):
-                            mission['max_steps'] += 10
-                        else:
-                            goal = mission.get('goal', '')
-                            question = f"[MISSION SUMMARY]: Step limit reached ({max_steps} steps). Provide a concise summary of all findings and current status for: {goal}"
-                            clean_question = question
-                            mission['active'] = False
-                            is_mission = False
-                            self.console.print(f"\n[bold cyan]🤖 Generating Final Mission Summary ({max_steps} steps reached)...[/bold cyan]")
-
-                if is_mission:
-                    goal = mission.get('goal', '')
-                    step = mission.get('step', 1)
-                    question = f"[MISSION STEP {step}]: Continue analysis of: {goal}"
-                    
-                    scratchpad = mission.get('scratchpad_notes', [])
-                    if scratchpad:
-                        notes_text = "\n".join(f"- {n}" for n in scratchpad)
-                        question += f"\n\nPast Mission Notes:\n{notes_text}"
-                        
-                    clean_question = question
-                    self.console.print(f"\n[bold cyan]🤖 Executing Mission Step {step}: {goal}[/bold cyan]")
-                elif not is_mission and 'clean_question' in locals() and clean_question.startswith("[MISSION SUMMARY]"):
-                    # Pass-through to AI execution for generating final summary
-                    pass
-                else:
-                    # 2. Ask question
-                    from prompt_toolkit.styles import Style
-                    c_contrast = self._get_theme_color("contrast", "gray")
-                    ui_style = Style.from_dict({
-                        'bottom-toolbar': f'fg:{c_contrast}',
-                    })
-                    
-                    session = PromptSession(
-                        history=self.history, 
-                        input=self.pt_input, 
-                        output=self.pt_output,
-                        completer=copilot_completer,
-                        reserve_space_for_menu=0,
-                        style=ui_style
-                    )
-                    try:
-                        question = await session.prompt_async(
-                            get_prompt_text, 
-                            key_bindings=bindings, 
-                            bottom_toolbar=get_toolbar,
-                            multiline=True
-                        )
-                    except (KeyboardInterrupt, EOFError):
-                        state['cancelled'] = True
-                        question = ""
-                    
-                    if state['cancelled'] or not question.strip() or question.strip().lower() in ['cancel', 'exit', 'quit']:
-                        _finalize_mission("user_cancelled")
-                        return "cancel", None, None
-
-                    # 3. Process Input via AIService
-                    directive = self.ai_service.process_copilot_input(question, self.session_state)
-                    
-                    if directive["action"] == "mission_start":
-                        mission = self.session_state.get('mission', {})
-                        mission['start_block_idx'] = state['total_cmds']
-                        state['context_mode'] = self.mode_range
-                        self.session_state['context_mode'] = self.mode_range
-                        state['context_cmd'] = 1
-                        self.session_state['context_cmd'] = 1
-                        clean_question = f"[MISSION STEP 1]: {directive['clean_prompt']}"
-                        overrides = directive.get("overrides", {})
-                        self.console.print(f"\n[bold cyan]🤖 Starting Mission: {directive['clean_prompt']}[/bold cyan]")
-                    elif directive["action"] == "mission_cancel":
-                        _finalize_mission("user_cancelled")
-                        state['toolbar_msg'] = 'Mission cancelled'
-                        continue
-                    elif directive["action"] == "state_update":
-                        msg = directive['message']
-                        state['toolbar_msg'] = msg
-                        state['msg_expiry'] = time.time() + 3 # 3 seconds timeout
-                        
-                        async def delayed_refresh():
-                            await asyncio.sleep(3.1)
-                            if state.get('toolbar_msg') == msg:
-                                state['toolbar_msg'] = ''
-                                try:
-                                    from prompt_toolkit.application.current import get_app
-                                    app = get_app()
-                                    if app: app.invalidate()
-                                except: pass
-                        asyncio.create_task(delayed_refresh())
-
-                        sys.stdout.write('\x1b[1A\x1b[2K')
-                        sys.stdout.flush()
-                        continue
-                    else:
-                        state['toolbar_msg'] = ''
-                        if mission.get('active', False):
-                            mission['paused'] = False
-                            step = mission.get('step', 1)
-                            goal = mission.get('goal', '')
-                            clean_question = f"[MISSION FEEDBACK (Step {step})]: User provided guidance: {question}. Continue the mission for goal: {goal}"
-                            self.console.print(f"\n[bold cyan]🤖 Continuing Mission with User Feedback: {question}[/bold cyan]")
-                            overrides = directive.get("overrides", {})
-                        else:
-                            clean_question = directive.get("clean_prompt", question)
-                            overrides = directive.get("overrides", {})
-                
-                # Merge node_info with session_state and overrides
-                merged_node_info = node_info.copy()
-                if self.session_state['os']: merged_node_info['os'] = self.session_state['os']
-                if self.session_state['prompt']: merged_node_info['prompt'] = self.session_state['prompt']
-                merged_node_info['persona'] = self.session_state['persona']
-                merged_node_info['trust'] = self.session_state['trust_mode']
-                merged_node_info['memories'] = list(self.session_state['memories'])
-                merged_node_info['chat_history'] = list(self.session_state.get('copilot_chat_history', []))
-                
-                for k, v in overrides.items():
-                    merged_node_info[k] = v
-
-                # 3. AI Execution
-                active_persona = merged_node_info.get('persona', self.session_state.get('persona', 'engineer'))
-                persona_color = self._get_theme_color(active_persona, fallback="cyan")
-                persona_title = "Network Architect" if active_persona == "architect" else "Network Engineer"
-                
-                active_buffer = get_active_buffer()
-                
-                live_text = ""
-                first_chunk = True
-                
-                from rich.rule import Rule
-                from rich.status import Status
-                from connpy.printer import IncrementalMarkdownParser
-                
-                md_parser = IncrementalMarkdownParser(console=self.console)
-                
-                status_spinner = Status(
-                    f"[bold {persona_color}]{persona_title}:[/bold {persona_color}] [dim]Thinking...[/dim]",
-                    console=self.console,
-                    spinner="dots"
-                )
-                status_spinner.start()
-                
-                def on_chunk(text):
-                    nonlocal live_text, first_chunk
-                    if first_chunk:
-                        status_spinner.stop()
-                        self.console.print(Rule(
-                            f"[bold {persona_color}]{persona_title}[/bold {persona_color}]",
-                            style=persona_color
-                        ))
-                        first_chunk = False
-                    live_text += text
-                    md_parser.feed(text)
-                
-                ai_task = asyncio.create_task(on_ai_call(active_buffer, clean_question, on_chunk, merged_node_info))
-                
-                try:
-                    while not ai_task.done():
-                        await asyncio.sleep(0.05)
-                    result = await ai_task
-                except asyncio.CancelledError:
-                    status_spinner.stop()
-                    _finalize_mission("user_cancelled")
-                    return "cancel", None, None
-                
-                if first_chunk:
-                    status_spinner.stop()
-
-                if not first_chunk:
-                    md_parser.flush()
-                    self.console.print(Rule(style=persona_color))
-                
-                if not result or result.get("error"):
-                    if first_chunk and result and result.get("error"):
-                        self.console.print(f"[red]Error: {result['error']}[/red]")
-                    _finalize_mission("user_cancelled")
-                    return "cancel", None, None
-
-                if first_chunk and result and result.get("guide"):
-                    from rich.markdown import Markdown
-                    self.console.print(Panel(Markdown(result["guide"]), title=f"[bold {persona_color}]{persona_title}[/bold {persona_color}]", border_style=persona_color))
-
-                # Update copilot_chat_history or mission scratchpad
-                if result and not result.get("error"):
-                    guide = result.get("guide", "")
-                    notes = result.get("notes", "")
-                    mission = self.session_state.get('mission', {})
-                    if mission.get('active', False):
-                        if notes:
-                            mission.setdefault('scratchpad_notes', []).append(notes)
-                        if guide:
-                            mission['last_guide'] = guide
-                    else:
-                        if guide or notes:
-                            asst_msg = f"Notes: {notes}\nGuide: {guide}" if notes else guide
-                            hist = self.session_state.setdefault("copilot_chat_history", [])
-                            hist.append({"role": "user", "content": clean_question})
-                            hist.append({"role": "assistant", "content": asst_msg})
-                            self.session_state["copilot_chat_history"] = hist[-10:]
-                commands = result.get("commands", [])
-                mission = self.session_state.get('mission', {})
-                if not commands:
-                    if mission.get('active', False):
-                        _finalize_mission("completed", result.get("guide", ""))
-                    self.console.print("")
-                    return "continue", None, None
-
-                risk = result.get("risk_level", "low")
-                risk_style = {"low": "success", "high": "warning", "destructive": "error"}.get(risk, "success")
-                style_color = self._get_theme_color(risk_style, fallback="green")
-                
-                cmd_text = "\n".join(f"  {i+1}. {c}" for i, c in enumerate(commands))
-                self.console.print(Panel(cmd_text, title=f"[bold {style_color}]Suggested Commands [{risk.upper()}][/bold {style_color}]", border_style=f"bold {style_color}"))
-
-                if merged_node_info.get('trust', False) and risk != "destructive":
-                    self.console.print(f"[dim]⚙️ Auto-executing (Trust Mode)[/dim]")
-                    if mission.get('active', False):
-                        mission['step'] = mission.get('step', 1) + 1
-                    return "send_all", commands, None
-
-                confirm_session = PromptSession(input=self.pt_input, output=self.pt_output)
-                c_bindings = KeyBindings()
-                @c_bindings.add('escape', eager=True)
-                @c_bindings.add('c-c')
-                def _(ev): ev.app.exit(result='n')
-                
-                import html
-                try:
-                    p_text = html.escape(f"Send? (y/n/e/range) [n]: ")
-                    action = await confirm_session.prompt_async(HTML(f'<style fg="{style_color}" bold="true">{p_text}</style>'), key_bindings=c_bindings)
-                except (KeyboardInterrupt, EOFError):
-                    _finalize_mission("user_cancelled", result.get("guide", ""))
-                    self.console.print("")
-                    return "continue", None, None
-
-                def parse_indices(text, max_len):
-                    indices = []
-                    parts = text.replace(',', ' ').split()
-                    for part in parts:
-                        if '-' in part:
-                            try:
-                                start, end = map(int, part.split('-'))
-                                indices.extend(range(start-1, end))
-                            except: continue
-                        elif part.isdigit():
-                            indices.append(int(part)-1)
-                    return [i for i in sorted(set(indices)) if 0 <= i < max_len]
-
-                action_l = (action or "n").lower().strip()
-                if action_l in ('y', 'yes', 'all'):
-                    if mission.get('active', False):
-                        mission['step'] = mission.get('step', 1) + 1
-                    return "send_all", commands, None
-                
-                if re.match(r'^[0-9,\-\s]+$', action_l):
-                    selected_idxs = parse_indices(action_l, len(commands))
-                    if selected_idxs:
-                        if mission.get('active', False):
-                            mission['step'] = mission.get('step', 1) + 1
-                        return "send_all", [commands[i] for i in selected_idxs], None
-
-                elif action_l.startswith('e'):
-                    selection_str = action_l[1:].strip()
-                    if selection_str:
-                        idxs = parse_indices(selection_str, len(commands))
-                        cmds_to_edit = [commands[i] for i in idxs] if idxs else commands
-                    else:
-                        cmds_to_edit = commands
-
-                    target = "\n".join(cmds_to_edit)
-                    e_bindings = KeyBindings()
-                    @e_bindings.add('c-j')
-                    def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
-                    @e_bindings.add('escape', 'enter')
-                    def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
-                    @e_bindings.add('escape')
-                    def _(ev): ev.app.exit(result='')
-                    
-                    c_edit = self._get_theme_color("user_prompt", "cyan")
-                    import html
-                    e_text = html.escape("Edit (Ctrl+Enter or Esc+Enter to submit):\n")
-                    try:
-                        edited = await confirm_session.prompt_async(
-                            HTML(f'<style fg="{c_edit}">{e_text}</style>'),
-                            default=target, multiline=True, key_bindings=e_bindings
-                        )
-                    except (KeyboardInterrupt, EOFError):
-                        if mission.get('active', False):
-                            mission['paused'] = True
-                            self.console.print("\n[yellow]⏸️  Mission Paused — Provide feedback to redirect, or type /cancel to abort.[/yellow]")
-                        self.console.print("")
-                        return "continue", None, None
-
-                    if edited and edited.strip():
-                        lines = [l.strip() for l in edited.split('\n') if l.strip()]
-                        if mission.get('active', False):
-                            mission['step'] = mission.get('step', 1) + 1
-                        return "custom", None, lines
-
-                # User rejected/cancelled the commands
-                if mission.get('active', False):
-                    mission['paused'] = True
-                    self.console.print("\n[yellow]⏸️  Mission Paused — Provide feedback to redirect, or type /cancel to abort.[/yellow]")
-                    
-                self.console.print("")
-                return "continue", None, None
-            
-            return "cancel", None, None
-
-        finally:
-            state['cancelled'] = True
-
-
-

Methods

-
-
-async def run_session(self,
raw_bytes: bytes,
node_info: dict,
on_ai_call: Callable,
cmd_byte_positions: List[tuple] = None,
blocks: List[tuple] = None)
-
-
-
- -Expand source code - -
async def run_session(self, 
-                      raw_bytes: bytes, 
-                      node_info: dict,
-                      on_ai_call: Callable,
-                      cmd_byte_positions: List[tuple] = None, 
-                      blocks: List[tuple] = None):
-    """
-    Runs the interactive Copilot session.
-    on_ai_call: async function(active_buffer, question) -> result_dict
-    """
-    from rich.rule import Rule
-    
-    try:
-        # Prepare UI state
-        buffer = log_cleaner(raw_bytes.decode(errors='replace'))
-        
-        # Use pre-calculated blocks if provided (remote mode), otherwise calculate locally (local mode)
-        if blocks is None:
-            last_line = buffer.split('\n')[-1].strip() if buffer.strip() else "(prompt)"
-            blocks = self.ai_service.build_context_blocks(raw_bytes, cmd_byte_positions, node_info, last_line=last_line)
-        
-        total_cmds = len(blocks)
-        total_lines = len(buffer.split('\n'))
-
-        saved_mode = self.session_state.get('context_mode', self.mode_range)
-        saved_cmd = self.session_state.get('context_cmd', 1)
-        saved_lines = self.session_state.get('context_lines', min(50, total_lines))
-        last_total_cmds = self.session_state.get('last_total_cmds', None)
-        last_total_lines = self.session_state.get('last_total_lines', None)
-
-        is_range = saved_mode in (self.mode_range, 0, 'RANGE', 'range')
-        is_lines = saved_mode in (self.mode_lines, 2, 'LINES', 'lines')
-        is_single = saved_mode in (self.mode_single, 1, 'SINGLE', 'single')
-
-        if is_range or is_single:
-            is_mission = self.session_state.get('mission', {}).get('active', False)
-            if last_total_cmds is not None and total_cmds > last_total_cmds and (saved_cmd > 1 or is_mission):
-                new_cmds = total_cmds - last_total_cmds
-                initial_cmd = saved_cmd + new_cmds
-            else:
-                initial_cmd = saved_cmd
-            initial_lines = saved_lines
-        elif is_lines:
-            if last_total_lines is not None and total_lines > last_total_lines and saved_lines > 50:
-                new_lines = total_lines - last_total_lines
-                initial_lines = saved_lines + new_lines
-            else:
-                initial_lines = saved_lines
-            initial_cmd = saved_cmd
-        else:
-            initial_cmd = saved_cmd
-            initial_lines = saved_lines
-
-        state = {
-            'context_cmd': min(max(1, initial_cmd), max(1, total_cmds)),
-            'total_cmds': total_cmds,
-            'total_lines': total_lines,
-            'context_lines': min(max(1, initial_lines), max(1, total_lines)),
-            'context_mode': saved_mode,
-            'cancelled': False,
-            'toolbar_msg': '',
-            'msg_expiry': 0
-        }
-        self.session_state['context_mode'] = saved_mode
-        self.session_state['context_cmd'] = max(1, initial_cmd)
-        self.session_state['context_lines'] = max(1, initial_lines)
-        self.session_state['last_total_cmds'] = total_cmds
-        self.session_state['last_total_lines'] = total_lines
-        
-        # 1. Visual Separation (Only show help banner on initial entry)
-        self.console.print("") # Real line break
-        self.console.print(Rule(title="[bold cyan] AI TERMINAL COPILOT [/bold cyan]", style="cyan"))
-        if not self.session_state.get('banner_shown', False):
-            self.console.print(Panel(
-                "[dim]Type your question. Enter to send, Escape/Ctrl+C to cancel. Type / for commands.\n"
-                "Tab to change context mode. Ctrl+\u2191/\u2193 to adjust context. \u2191\u2193 for question history.[/dim]",
-                border_style="cyan"
-            ))
-            self.session_state['banner_shown'] = True
-        self.console.print("") # Small space before the copilot prompt
-
-        bindings = KeyBindings()
-        @bindings.add('c-up')
-        def _(event):
-            if state['context_mode'] == self.mode_lines:
-                state['context_lines'] = min(state['context_lines'] + 50, state['total_lines'])
-            else:
-                state['context_cmd'] = min(state['context_cmd'] + 1, state['total_cmds'])
-            self._sync_session_context(state)
-            event.app.invalidate()
-        @bindings.add('c-down')
-        def _(event):
-            if state['context_mode'] == self.mode_lines:
-                state['context_lines'] = max(state['context_lines'] - 50, min(50, state['total_lines']))
-            else:
-                state['context_cmd'] = max(state['context_cmd'] - 1, 1)
-            self._sync_session_context(state)
-            event.app.invalidate()
-        @bindings.add('tab')
-        def _(event):
-            buf = event.current_buffer
-            # If typing a slash command (no spaces yet), use tab to autocomplete inline
-            if buf.text.startswith('/') and ' ' not in buf.text:
-                buf.complete_next()
-            else:
-                state['context_mode'] = (state['context_mode'] + 1) % 3
-                self._sync_session_context(state)
-                event.app.invalidate()
-        @bindings.add('escape', eager=True)
-        @bindings.add('c-c')
-        def _(event):
-            state['cancelled'] = True
-            event.app.exit(result='')
-
-        # Multiline keybindings: Enter to submit, Ctrl+Enter (c-j) or Alt+Enter to add a newline
-        @bindings.add('enter', filter=~has_completions)
-        def _(event):
-            event.current_buffer.validate_and_handle()
-
-        @bindings.add('c-j')
-        @bindings.add('escape', 'enter')
-        def _(event):
-            event.current_buffer.insert_text('\n')
-
-        def get_active_buffer():
-            if state['context_mode'] == self.mode_lines:
-                return '\n'.join(buffer.split('\n')[-state['context_lines']:])
-            idx = max(0, state['total_cmds'] - state['context_cmd'])
-            start, end, preview = blocks[idx]
-            if state['context_mode'] == self.mode_single:
-                active_raw = raw_bytes[start:end]
-            else:
-                # Concat only the bytes of valid blocks to skip intermediate empty/cancelled prompt noise
-                active_raw = b"".join(raw_bytes[b[0]:b[1]] for b in blocks[idx:])
-            return preview + "\n" + log_cleaner(active_raw.decode(errors='replace'))
-
-        def get_prompt_text():
-            import html
-            # Always use user_prompt color for the Ask prompt
-            color = self._get_theme_color("user_prompt", "cyan")
-            
-            if state['context_mode'] == self.mode_lines:
-                text = html.escape(f"Ask [Ctx: {state['context_lines']}/{state['total_lines']}L]: ")
-                return HTML(f'<style fg="{color}">{text}</style>')
-            active = get_active_buffer()
-            lines_count = len(active.split('\n'))
-            mode_str = {self.mode_range: "Range", self.mode_single: "Cmd"}[state['context_mode']]
-            text = html.escape(f"Ask [{mode_str} {state['context_cmd']} ~{lines_count}L]: ")
-            return HTML(f'<style fg="{color}">{text}</style>')
-
-        from prompt_toolkit.application.current import get_app
-
-        def get_toolbar():
-            import html
-            app = get_app()
-            c_warning = self._get_theme_color("warning", "yellow")
-            
-            if app and app.current_buffer:
-                text = app.current_buffer.text
-                # Only show command help if typing the first command and there are no spaces
-                if text.startswith('/') and ' ' not in text:
-                    commands = ['/os', '/prompt', '/architect', '/engineer', '/trust', '/untrust', '/memorize', '/clear', '/mission', '/cancel']
-                    matches = [c for c in commands if c.startswith(text.lower())]
-                    if matches:
-                        m_text = html.escape(f"Available: {' '.join(matches)}")
-                        return HTML(f'<style fg="{c_warning}">{m_text}</style>' + " " * 20)
-
-            m_label = {self.mode_range: "RANGE", self.mode_single: "SINGLE", self.mode_lines: "LINES"}[state['context_mode']]
-            if state['context_mode'] == self.mode_lines:
-                base_str = f'\u25b6 [Tab: {m_label}] {state["context_lines"]}/{state["total_lines"]}L (Ctrl+\u2191/\u2193 adjusts lines)'
-            else:
-                idx = max(0, state['total_cmds'] - state['context_cmd'])
-                
-                def clean_preview(text):
-                    # Clean newlines and the initial prompt (all up to #, > or $) to leave only the command
-                    original = text.strip().replace('\r', '').replace('\n', ' ')
-                    cleaned = re.sub(r'^.*?[#>\$]\s*', '', original)
-                    # If cleaning the prompt leaves us with an empty string (e.g. it was just "iol#"), return the original
-                    return cleaned if cleaned else original
-
-                if state['context_mode'] == self.mode_range:
-                    range_blocks = blocks[idx:]
-                    # If there is more than one block, the last one is always the empty/current prompt. We omit it visually.
-                    if len(range_blocks) > 1:
-                        range_blocks = range_blocks[:-1]
-                        
-                    # Clean and truncate very long commands so they don't break the UI
-                    previews = []
-                    for b in range_blocks:
-                        p = clean_preview(b[2])
-                        if p:
-                            # Truncar comandos individuales largos
-                            if len(p) > 25: p = p[:22].rstrip(' .,-_') + "..."
-                            previews.append(p)
-                    
-                    if not previews:
-                        desc = clean_preview(blocks[idx][2])
-                    elif len(previews) <= 3:
-                        desc = " + ".join(previews)
-                    else:
-                        desc = f"{previews[0]} + {previews[1]} + {previews[2]} (+{len(previews)-3})"
-                else:
-                    # Modo SINGLE original
-                    desc = clean_preview(blocks[idx][2])
-                    
-                base_str = f'\u25b6 [Tab: {m_label}] {desc}'
-            
-            # Wrap base_str in a style to maintain consistency and avoid glitches
-            # The fg color will be inherited from bottom-toolbar global style if not specified here
-            base_html = f'<span>{html.escape(base_str)}</span>'
-            
-            res_html = base_html
-            if state.get('toolbar_msg'):
-                if time.time() < state.get('msg_expiry', 0):
-                    msg = html.escape(state['toolbar_msg'])
-                    res_html = f'<style fg="{c_warning}">⚙️ {msg}</style> | ' + base_html
-                else:
-                    state['toolbar_msg'] = ''
-            
-            # Pad with spaces to ensure the line is cleared when the message disappears
-            return HTML(res_html + " " * 20)
-
-        from prompt_toolkit.completion import Completer, Completion
-        class SlashCommandCompleter(Completer):
-            def get_completions(self, document, complete_event):
-                text = document.text_before_cursor
-                if text.startswith('/'):
-                    parts = text.split()
-                    # Only autocomplete the first word
-                    if len(parts) <= 1 or (len(parts) == 1 and not text.endswith(' ')):
-                        cmd_part = parts[0] if parts else text
-                        commands = [
-                            ('/os', 'Set device OS (e.g. cisco_ios)'),
-                            ('/prompt', 'Override prompt regex'),
-                            ('/architect', 'Switch to Architect persona'),
-                            ('/engineer', 'Switch to Engineer persona'),
-                            ('/trust', 'Enable auto-execute'),
-                            ('/untrust', 'Disable auto-execute'),
-                            ('/memorize', 'Add fact to memory'),
-                            ('/clear', 'Clear memory'),
-                            ('/mission', 'Start autonomous mission'),
-                            ('/cancel', 'Cancel active mission')
-                        ]
-                        for cmd, desc in commands:
-                            if cmd.startswith(cmd_part.lower()):
-                                yield Completion(cmd, start_position=-len(cmd_part), display_meta=desc)
-
-        copilot_completer = SlashCommandCompleter()
-
-        def _finalize_mission(reason="completed", final_guide=""):
-            mission = self.session_state.get('mission', {})
-            if not mission or not mission.get('active', False):
-                return
-            mission['active'] = False
-            if reason == "completed":
-                self.console.print("\n[bold green]🎉 Mission Completed[/bold green]")
-            elif reason == "user_cancelled":
-                self.console.print("\n[yellow]Mission cancelled by user.[/yellow]")
-            elif reason == "limit_reached":
-                self.console.print("\n[yellow]Mission step limit reached.[/yellow]")
-
-            final_notes = "\n".join(mission.get('scratchpad_notes', []))
-            guide = final_guide or mission.get('last_guide', '')
-            asst_msg = f"Notes: {final_notes}\nGuide: {guide}" if final_notes else guide
-            hist = self.session_state.setdefault("copilot_chat_history", [])
-            hist.append({"role": "user", "content": f"/mission {mission.get('goal', '')}"})
-            hist.append({"role": "assistant", "content": asst_msg})
-            self.session_state["copilot_chat_history"] = hist[-10:]
-
-        while True:
-            overrides = {}
-            # Check for active mission auto-looping
-            mission = self.session_state.get('mission', {})
-            is_mission = mission.get('active', False) and not mission.get('paused', False)
-
-            if is_mission:
-                # Force mode_range for mission mode
-                state['context_mode'] = self.mode_range
-                self.session_state['context_mode'] = self.mode_range
-
-                if mission.get('start_block_idx') is None:
-                    mission['start_block_idx'] = state['total_cmds']
-
-                start_idx = mission.get('start_block_idx', state['total_cmds'])
-                cmds_since_start = max(1, (state['total_cmds'] - start_idx) + 1)
-                state['context_cmd'] = max(state.get('context_cmd', 1), cmds_since_start)
-                self.session_state['context_cmd'] = state['context_cmd']
-
-                step = mission.get('step', 1)
-                max_steps = mission.get('max_steps', 10)
-
-                if step > max_steps:
-                    ext_session = PromptSession(input=self.pt_input, output=self.pt_output)
-                    c_warn = self._get_theme_color("warning", "yellow")
-                    import html
-                    p_warn = html.escape(f"[Mission Limit Reached ({max_steps} steps)] Extend mission for 10 more steps? (y/n) [y]: ")
-                    try:
-                        ext_ans = await ext_session.prompt_async(HTML(f'<style fg="{c_warn}" bold="true">{p_warn}</style>'))
-                    except (KeyboardInterrupt, EOFError):
-                        ext_ans = 'n'
-
-                    if (ext_ans or 'y').lower().strip() in ('y', 'yes'):
-                        mission['max_steps'] += 10
-                    else:
-                        goal = mission.get('goal', '')
-                        question = f"[MISSION SUMMARY]: Step limit reached ({max_steps} steps). Provide a concise summary of all findings and current status for: {goal}"
-                        clean_question = question
-                        mission['active'] = False
-                        is_mission = False
-                        self.console.print(f"\n[bold cyan]🤖 Generating Final Mission Summary ({max_steps} steps reached)...[/bold cyan]")
-
-            if is_mission:
-                goal = mission.get('goal', '')
-                step = mission.get('step', 1)
-                question = f"[MISSION STEP {step}]: Continue analysis of: {goal}"
-                
-                scratchpad = mission.get('scratchpad_notes', [])
-                if scratchpad:
-                    notes_text = "\n".join(f"- {n}" for n in scratchpad)
-                    question += f"\n\nPast Mission Notes:\n{notes_text}"
-                    
-                clean_question = question
-                self.console.print(f"\n[bold cyan]🤖 Executing Mission Step {step}: {goal}[/bold cyan]")
-            elif not is_mission and 'clean_question' in locals() and clean_question.startswith("[MISSION SUMMARY]"):
-                # Pass-through to AI execution for generating final summary
-                pass
-            else:
-                # 2. Ask question
-                from prompt_toolkit.styles import Style
-                c_contrast = self._get_theme_color("contrast", "gray")
-                ui_style = Style.from_dict({
-                    'bottom-toolbar': f'fg:{c_contrast}',
-                })
-                
-                session = PromptSession(
-                    history=self.history, 
-                    input=self.pt_input, 
-                    output=self.pt_output,
-                    completer=copilot_completer,
-                    reserve_space_for_menu=0,
-                    style=ui_style
-                )
-                try:
-                    question = await session.prompt_async(
-                        get_prompt_text, 
-                        key_bindings=bindings, 
-                        bottom_toolbar=get_toolbar,
-                        multiline=True
-                    )
-                except (KeyboardInterrupt, EOFError):
-                    state['cancelled'] = True
-                    question = ""
-                
-                if state['cancelled'] or not question.strip() or question.strip().lower() in ['cancel', 'exit', 'quit']:
-                    _finalize_mission("user_cancelled")
-                    return "cancel", None, None
-
-                # 3. Process Input via AIService
-                directive = self.ai_service.process_copilot_input(question, self.session_state)
-                
-                if directive["action"] == "mission_start":
-                    mission = self.session_state.get('mission', {})
-                    mission['start_block_idx'] = state['total_cmds']
-                    state['context_mode'] = self.mode_range
-                    self.session_state['context_mode'] = self.mode_range
-                    state['context_cmd'] = 1
-                    self.session_state['context_cmd'] = 1
-                    clean_question = f"[MISSION STEP 1]: {directive['clean_prompt']}"
-                    overrides = directive.get("overrides", {})
-                    self.console.print(f"\n[bold cyan]🤖 Starting Mission: {directive['clean_prompt']}[/bold cyan]")
-                elif directive["action"] == "mission_cancel":
-                    _finalize_mission("user_cancelled")
-                    state['toolbar_msg'] = 'Mission cancelled'
-                    continue
-                elif directive["action"] == "state_update":
-                    msg = directive['message']
-                    state['toolbar_msg'] = msg
-                    state['msg_expiry'] = time.time() + 3 # 3 seconds timeout
-                    
-                    async def delayed_refresh():
-                        await asyncio.sleep(3.1)
-                        if state.get('toolbar_msg') == msg:
-                            state['toolbar_msg'] = ''
-                            try:
-                                from prompt_toolkit.application.current import get_app
-                                app = get_app()
-                                if app: app.invalidate()
-                            except: pass
-                    asyncio.create_task(delayed_refresh())
-
-                    sys.stdout.write('\x1b[1A\x1b[2K')
-                    sys.stdout.flush()
-                    continue
-                else:
-                    state['toolbar_msg'] = ''
-                    if mission.get('active', False):
-                        mission['paused'] = False
-                        step = mission.get('step', 1)
-                        goal = mission.get('goal', '')
-                        clean_question = f"[MISSION FEEDBACK (Step {step})]: User provided guidance: {question}. Continue the mission for goal: {goal}"
-                        self.console.print(f"\n[bold cyan]🤖 Continuing Mission with User Feedback: {question}[/bold cyan]")
-                        overrides = directive.get("overrides", {})
-                    else:
-                        clean_question = directive.get("clean_prompt", question)
-                        overrides = directive.get("overrides", {})
-            
-            # Merge node_info with session_state and overrides
-            merged_node_info = node_info.copy()
-            if self.session_state['os']: merged_node_info['os'] = self.session_state['os']
-            if self.session_state['prompt']: merged_node_info['prompt'] = self.session_state['prompt']
-            merged_node_info['persona'] = self.session_state['persona']
-            merged_node_info['trust'] = self.session_state['trust_mode']
-            merged_node_info['memories'] = list(self.session_state['memories'])
-            merged_node_info['chat_history'] = list(self.session_state.get('copilot_chat_history', []))
-            
-            for k, v in overrides.items():
-                merged_node_info[k] = v
-
-            # 3. AI Execution
-            active_persona = merged_node_info.get('persona', self.session_state.get('persona', 'engineer'))
-            persona_color = self._get_theme_color(active_persona, fallback="cyan")
-            persona_title = "Network Architect" if active_persona == "architect" else "Network Engineer"
-            
-            active_buffer = get_active_buffer()
-            
-            live_text = ""
-            first_chunk = True
-            
-            from rich.rule import Rule
-            from rich.status import Status
-            from connpy.printer import IncrementalMarkdownParser
-            
-            md_parser = IncrementalMarkdownParser(console=self.console)
-            
-            status_spinner = Status(
-                f"[bold {persona_color}]{persona_title}:[/bold {persona_color}] [dim]Thinking...[/dim]",
-                console=self.console,
-                spinner="dots"
-            )
-            status_spinner.start()
-            
-            def on_chunk(text):
-                nonlocal live_text, first_chunk
-                if first_chunk:
-                    status_spinner.stop()
-                    self.console.print(Rule(
-                        f"[bold {persona_color}]{persona_title}[/bold {persona_color}]",
-                        style=persona_color
-                    ))
-                    first_chunk = False
-                live_text += text
-                md_parser.feed(text)
-            
-            ai_task = asyncio.create_task(on_ai_call(active_buffer, clean_question, on_chunk, merged_node_info))
-            
-            try:
-                while not ai_task.done():
-                    await asyncio.sleep(0.05)
-                result = await ai_task
-            except asyncio.CancelledError:
-                status_spinner.stop()
-                _finalize_mission("user_cancelled")
-                return "cancel", None, None
-            
-            if first_chunk:
-                status_spinner.stop()
-
-            if not first_chunk:
-                md_parser.flush()
-                self.console.print(Rule(style=persona_color))
-            
-            if not result or result.get("error"):
-                if first_chunk and result and result.get("error"):
-                    self.console.print(f"[red]Error: {result['error']}[/red]")
-                _finalize_mission("user_cancelled")
-                return "cancel", None, None
-
-            if first_chunk and result and result.get("guide"):
-                from rich.markdown import Markdown
-                self.console.print(Panel(Markdown(result["guide"]), title=f"[bold {persona_color}]{persona_title}[/bold {persona_color}]", border_style=persona_color))
-
-            # Update copilot_chat_history or mission scratchpad
-            if result and not result.get("error"):
-                guide = result.get("guide", "")
-                notes = result.get("notes", "")
-                mission = self.session_state.get('mission', {})
-                if mission.get('active', False):
-                    if notes:
-                        mission.setdefault('scratchpad_notes', []).append(notes)
-                    if guide:
-                        mission['last_guide'] = guide
-                else:
-                    if guide or notes:
-                        asst_msg = f"Notes: {notes}\nGuide: {guide}" if notes else guide
-                        hist = self.session_state.setdefault("copilot_chat_history", [])
-                        hist.append({"role": "user", "content": clean_question})
-                        hist.append({"role": "assistant", "content": asst_msg})
-                        self.session_state["copilot_chat_history"] = hist[-10:]
-            commands = result.get("commands", [])
-            mission = self.session_state.get('mission', {})
-            if not commands:
-                if mission.get('active', False):
-                    _finalize_mission("completed", result.get("guide", ""))
-                self.console.print("")
-                return "continue", None, None
-
-            risk = result.get("risk_level", "low")
-            risk_style = {"low": "success", "high": "warning", "destructive": "error"}.get(risk, "success")
-            style_color = self._get_theme_color(risk_style, fallback="green")
-            
-            cmd_text = "\n".join(f"  {i+1}. {c}" for i, c in enumerate(commands))
-            self.console.print(Panel(cmd_text, title=f"[bold {style_color}]Suggested Commands [{risk.upper()}][/bold {style_color}]", border_style=f"bold {style_color}"))
-
-            if merged_node_info.get('trust', False) and risk != "destructive":
-                self.console.print(f"[dim]⚙️ Auto-executing (Trust Mode)[/dim]")
-                if mission.get('active', False):
-                    mission['step'] = mission.get('step', 1) + 1
-                return "send_all", commands, None
-
-            confirm_session = PromptSession(input=self.pt_input, output=self.pt_output)
-            c_bindings = KeyBindings()
-            @c_bindings.add('escape', eager=True)
-            @c_bindings.add('c-c')
-            def _(ev): ev.app.exit(result='n')
-            
-            import html
-            try:
-                p_text = html.escape(f"Send? (y/n/e/range) [n]: ")
-                action = await confirm_session.prompt_async(HTML(f'<style fg="{style_color}" bold="true">{p_text}</style>'), key_bindings=c_bindings)
-            except (KeyboardInterrupt, EOFError):
-                _finalize_mission("user_cancelled", result.get("guide", ""))
-                self.console.print("")
-                return "continue", None, None
-
-            def parse_indices(text, max_len):
-                indices = []
-                parts = text.replace(',', ' ').split()
-                for part in parts:
-                    if '-' in part:
-                        try:
-                            start, end = map(int, part.split('-'))
-                            indices.extend(range(start-1, end))
-                        except: continue
-                    elif part.isdigit():
-                        indices.append(int(part)-1)
-                return [i for i in sorted(set(indices)) if 0 <= i < max_len]
-
-            action_l = (action or "n").lower().strip()
-            if action_l in ('y', 'yes', 'all'):
-                if mission.get('active', False):
-                    mission['step'] = mission.get('step', 1) + 1
-                return "send_all", commands, None
-            
-            if re.match(r'^[0-9,\-\s]+$', action_l):
-                selected_idxs = parse_indices(action_l, len(commands))
-                if selected_idxs:
-                    if mission.get('active', False):
-                        mission['step'] = mission.get('step', 1) + 1
-                    return "send_all", [commands[i] for i in selected_idxs], None
-
-            elif action_l.startswith('e'):
-                selection_str = action_l[1:].strip()
-                if selection_str:
-                    idxs = parse_indices(selection_str, len(commands))
-                    cmds_to_edit = [commands[i] for i in idxs] if idxs else commands
-                else:
-                    cmds_to_edit = commands
-
-                target = "\n".join(cmds_to_edit)
-                e_bindings = KeyBindings()
-                @e_bindings.add('c-j')
-                def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
-                @e_bindings.add('escape', 'enter')
-                def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
-                @e_bindings.add('escape')
-                def _(ev): ev.app.exit(result='')
-                
-                c_edit = self._get_theme_color("user_prompt", "cyan")
-                import html
-                e_text = html.escape("Edit (Ctrl+Enter or Esc+Enter to submit):\n")
-                try:
-                    edited = await confirm_session.prompt_async(
-                        HTML(f'<style fg="{c_edit}">{e_text}</style>'),
-                        default=target, multiline=True, key_bindings=e_bindings
-                    )
-                except (KeyboardInterrupt, EOFError):
-                    if mission.get('active', False):
-                        mission['paused'] = True
-                        self.console.print("\n[yellow]⏸️  Mission Paused — Provide feedback to redirect, or type /cancel to abort.[/yellow]")
-                    self.console.print("")
-                    return "continue", None, None
-
-                if edited and edited.strip():
-                    lines = [l.strip() for l in edited.split('\n') if l.strip()]
-                    if mission.get('active', False):
-                        mission['step'] = mission.get('step', 1) + 1
-                    return "custom", None, lines
-
-            # User rejected/cancelled the commands
-            if mission.get('active', False):
-                mission['paused'] = True
-                self.console.print("\n[yellow]⏸️  Mission Paused — Provide feedback to redirect, or type /cancel to abort.[/yellow]")
-                
-            self.console.print("")
-            return "continue", None, None
-        
-        return "cancel", None, None
-
-    finally:
-        state['cancelled'] = True
-
-

Runs the interactive Copilot session. -on_ai_call: async function(active_buffer, question) -> result_dict

-
-
-
-
  • connpy.cli
  • -
  • Classes

    - -
  • diff --git a/docs/connpy/grpc_layer/connpy_pb2_grpc.html b/docs/connpy/grpc_layer/connpy_pb2_grpc.html index 81dc2f5..6436804 100644 --- a/docs/connpy/grpc_layer/connpy_pb2_grpc.html +++ b/docs/connpy/grpc_layer/connpy_pb2_grpc.html @@ -1671,8 +1671,9 @@ def predict_execution_results(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    @@ -2371,8 +2372,9 @@ def revoke_api_token(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    @@ -2980,8 +2982,9 @@ def update_setting(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    @@ -3316,8 +3319,9 @@ def test_commands(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    @@ -3652,8 +3656,9 @@ def set_reserved_names(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    @@ -5080,8 +5085,9 @@ def validate_parent_folder(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    @@ -5598,8 +5604,9 @@ def list_plugins(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    @@ -6207,8 +6214,9 @@ def update_profile(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    @@ -6725,8 +6733,9 @@ def stop_api(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    diff --git a/docs/connpy/grpc_layer/remote_plugin_pb2.html b/docs/connpy/grpc_layer/remote_plugin_pb2.html index c841aa0..578f9ee 100644 --- a/docs/connpy/grpc_layer/remote_plugin_pb2.html +++ b/docs/connpy/grpc_layer/remote_plugin_pb2.html @@ -62,7 +62,7 @@ el.replaceWith(d);
    var DESCRIPTOR
    -

    The type of the None singleton.

    +
    @@ -81,7 +81,7 @@ el.replaceWith(d);
    var DESCRIPTOR
    -

    The type of the None singleton.

    +
    @@ -100,7 +100,7 @@ el.replaceWith(d);
    var DESCRIPTOR
    -

    The type of the None singleton.

    +
    @@ -119,7 +119,7 @@ el.replaceWith(d);
    var DESCRIPTOR
    -

    The type of the None singleton.

    +
    diff --git a/docs/connpy/grpc_layer/remote_plugin_pb2_grpc.html b/docs/connpy/grpc_layer/remote_plugin_pb2_grpc.html index 61ed251..5770d8d 100644 --- a/docs/connpy/grpc_layer/remote_plugin_pb2_grpc.html +++ b/docs/connpy/grpc_layer/remote_plugin_pb2_grpc.html @@ -317,8 +317,9 @@ def invoke_plugin(request,

    Missing associated documentation comment in .proto file.

    Constructor.

    -

    Args

    +
    Args
    +
    -----=
    channel
    A grpc.Channel.
    diff --git a/docs/connpy/grpc_layer/server.html b/docs/connpy/grpc_layer/server.html index cd55201..5782d20 100644 --- a/docs/connpy/grpc_layer/server.html +++ b/docs/connpy/grpc_layer/server.html @@ -604,7 +604,7 @@ def service(self):
    var OPEN_METHODS
    -

    The type of the None singleton.

    +

    Methods

    @@ -648,8 +648,9 @@ contextvars.Context, and the same Context is used for downstream interceptors and for the final handler call. Note that there are no guarantees that interceptors and handlers will be called from the same thread.

    -

    Args

    +
    Args
    +
    -----=
    continuation
    A function that takes a HandlerCallDetails and proceeds to invoke the next interceptor in the chain, if any, @@ -659,8 +660,9 @@ the RPC is considered serviced, or None otherwise.
    handler_call_details
    A HandlerCallDetails describing the RPC.
    -

    Returns

    -

    An RpcMethodHandler with which the RPC may be serviced if the +

    Returns +-----= +An RpcMethodHandler with which the RPC may be serviced if the interceptor chooses to service this RPC, or None otherwise.

    @@ -1213,7 +1215,7 @@ def service(self): if request.value.startswith("---YAML---\n"): import yaml content = request.value[len("---YAML---\n"):] - data = yaml.load(content, Loader=yaml.FullLoader) + data = yaml.safe_load(content) self.service.import_from_dict(data) else: self.service.import_from_file(request.value) @@ -1340,8 +1342,9 @@ contextvars.Context, and the same Context is used for downstream interceptors and for the final handler call. Note that there are no guarantees that interceptors and handlers will be called from the same thread.

    -

    Args

    +
    Args
    +
    -----=
    continuation
    A function that takes a HandlerCallDetails and proceeds to invoke the next interceptor in the chain, if any, @@ -1351,8 +1354,9 @@ the RPC is considered serviced, or None otherwise.
    handler_call_details
    A HandlerCallDetails describing the RPC.
    -

    Returns

    -

    An RpcMethodHandler with which the RPC may be serviced if the +

    Returns +-----= +An RpcMethodHandler with which the RPC may be serviced if the interceptor chooses to service this RPC, or None otherwise.

    diff --git a/docs/connpy/grpc_layer/stubs.html b/docs/connpy/grpc_layer/stubs.html index e446c7f..82f62f7 100644 --- a/docs/connpy/grpc_layer/stubs.html +++ b/docs/connpy/grpc_layer/stubs.html @@ -42,2812 +42,8 @@ el.replaceWith(d);
    -

    Functions

    -
    -
    -def handle_errors(func) -
    -
    -
    - -Expand source code - -
    def handle_errors(func):
    -    @wraps(func)
    -    def wrapper(*args, **kwargs):
    -        try:
    -            return func(*args, **kwargs)
    -        except grpc.RpcError as e:
    -            # Re-raise gRPC errors as native ConnpyError to keep CLI handlers agnostic
    -            details = e.details()
    -
    -            # Identify the host if available on the instance
    -            instance = args[0] if args else None
    -            host = getattr(instance, "remote_host", "remote host")
    -
    -            # Make common gRPC errors more readable
    -            if "failed to connect to all addresses" in details:
    -                simplified = f"Failed to connect to remote host at {host} (Connection refused)"
    -            elif "Method not found" in details:
    -                simplified = f"Remote server at {host} is using an incompatible version"
    -            elif "Deadline Exceeded" in details:
    -                simplified = f"Request to {host} timed out"
    -            else:
    -                simplified = details
    -
    -            raise ConnpyError(simplified)
    -    return wrapper
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class AIStub -(channel, remote_host) -
    -
    -
    - -Expand source code - -
    class AIStub:
    -    def __init__(self, channel, remote_host):
    -        self.stub = connpy_pb2_grpc.AIServiceStub(channel)
    -        self.remote_host = remote_host
    -
    -    def _ai_chat_stream(self, stub_method, input_text, dryrun=False, chat_history=None, session_id=None, debug=False, status=None, chunk_callback=None, **overrides):
    -        import queue
    -        from rich.prompt import Prompt
    -        from rich.text import Text
    -        from rich.panel import Panel
    -        from rich.markdown import Markdown
    -        
    -        req_queue = queue.Queue()
    -        
    -        initial_req = connpy_pb2.AskRequest(
    -            input_text=input_text,
    -            dryrun=dryrun,
    -            session_id=session_id or "",
    -            debug=debug,
    -            engineer_model=overrides.get("engineer_model", ""),
    -            engineer_api_key=overrides.get("engineer_api_key", ""),
    -            architect_model=overrides.get("architect_model", ""),
    -            architect_api_key=overrides.get("architect_api_key", ""),
    -            trust=overrides.get("trust", False)
    -        )
    -        if chat_history is not None:
    -            initial_req.chat_history.CopyFrom(to_value(chat_history))
    -        if "engineer_auth" in overrides and overrides["engineer_auth"]:
    -            initial_req.engineer_auth.CopyFrom(to_struct(overrides["engineer_auth"]))
    -        if "architect_auth" in overrides and overrides["architect_auth"]:
    -            initial_req.architect_auth.CopyFrom(to_struct(overrides["architect_auth"]))
    -            
    -        req_queue.put(initial_req)
    -
    -        def request_generator():
    -            while True:
    -                req = req_queue.get()
    -                if req is None: break
    -                yield req
    -
    -        responses = stub_method(request_generator())
    -        
    -        full_content = ""
    -        header_printed = False
    -        current_responder = "engineer"
    -        final_result = {"response": "", "chat_history": []}
    -
    -        # Background thread to pull responses from gRPC into a local queue
    -        # This prevents KeyboardInterrupt from corrupting the gRPC iterator state
    -        response_queue = queue.Queue()
    -        
    -        def pull_responses():
    -            try:
    -                for response in responses:
    -                    response_queue.put(("data", response))
    -            except Exception as e:
    -                response_queue.put(("error", e))
    -            finally:
    -                response_queue.put((None, None))
    -
    -        threading.Thread(target=pull_responses, daemon=True).start()
    -
    -        try:
    -            while True:
    -                try:
    -                    # BLOCKING GET from local queue (interruptible by signal)
    -                    msg_type, response = response_queue.get()
    -                except KeyboardInterrupt:
    -                    # Signal interruption to the server
    -                    if status:
    -                        status.update("[error]Interrupted! Closing pending tasks...")
    -                    
    -                    # Send the interrupt signal to the server
    -                    req_queue.put(connpy_pb2.AskRequest(interrupt=True))
    -                    
    -                    # CONTINUE the loop to receive remaining data and summary from the queue
    -                    continue
    -                
    -                if msg_type is None: # Sentinel
    -                    break
    -                
    -                if msg_type == "error":
    -                    # Re-raise or handle gRPC error from background thread
    -                    if isinstance(response, grpc.RpcError):
    -                        raise response
    -                    printer.warning(f"Stream interrupted: {response}")
    -                    break
    -
    -                if response.status_update:
    -                    if response.status_update.startswith("__RESPONDER__:"):
    -                        current_responder = response.status_update.split(":")[1].lower()
    -                        continue
    -                        
    -                    if response.requires_confirmation:
    -                        if status: status.stop()
    -                        
    -                        # Show prompt and wait for answer
    -                        prompt_text = Text.from_ansi(response.status_update)
    -                        ans = Prompt.ask(prompt_text)
    -                        
    -                        if status: 
    -                            status.update("[ai_status]Agent: Resuming...")
    -                            status.start()
    -                        
    -                        req_queue.put(connpy_pb2.AskRequest(confirmation_answer=ans))
    -                        continue
    -                        
    -                    if status:
    -                        status.update(response.status_update)
    -                    continue
    -                
    -                if response.debug_message:
    -                    if debug:
    -                        if status:
    -                            try: status.stop()
    -                            except: pass
    -                        printer.console.print(Text.from_ansi(response.debug_message))
    -                        if status:
    -                            try: status.start()
    -                            except: pass
    -                    continue
    -                
    -                if response.important_message:
    -                    if status:
    -                        try: status.stop()
    -                        except: pass
    -                    printer.console.print(Text.from_ansi(response.important_message))
    -                    if status:
    -                        try: status.start()
    -                        except: pass
    -                    continue
    -
    -                if not response.is_final:
    -                    if response.text_chunk:
    -                        if not header_printed:
    -                            if status:
    -                                try: status.stop()
    -                                except: pass
    -                            
    -                            if chunk_callback:
    -                                header_printed = True
    -                            else:
    -                                from rich.console import Console as RichConsole
    -                                from rich.rule import Rule
    -                                from ..printer import connpy_theme, get_original_stdout, IncrementalMarkdownParser
    -                                stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
    -                                
    -                                # Print header on first chunk
    -                                alias = "architect" if current_responder == "architect" else "engineer"
    -                                role_label = "Network Architect" if current_responder == "architect" else "Network Engineer"
    -                                stable_console.print(Rule(f"[bold {alias}]{role_label}[/bold {alias}]", style=alias))
    -                                header_printed = True
    -                                
    -                                # Initialize parser
    -                                md_parser = IncrementalMarkdownParser(console=stable_console)
    -                        
    -                        full_content += response.text_chunk
    -                        if chunk_callback:
    -                            chunk_callback(response.text_chunk)
    -                        elif md_parser:
    -                            md_parser.feed(response.text_chunk)
    -                    continue
    -                
    -                if response.is_final:
    -                    if not chunk_callback and header_printed:
    -                        from rich.rule import Rule
    -                        md_parser.flush()
    -                        
    -                    if status:
    -                        try: status.stop()
    -                        except: pass
    -
    -                    final_result = from_struct(response.full_result)
    -                    
    -                    if not chunk_callback and header_printed:
    -                        from rich.console import Console as RichConsole
    -                        from ..printer import connpy_theme, get_original_stdout
    -                        stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
    -                        stable_console.print(Rule(style=alias))
    -                    break
    -        except Exception as e:
    -            # Check if it was a gRPC error that we should let handle_errors catch
    -            if isinstance(e, grpc.RpcError):
    -                raise
    -            printer.warning(f"Stream interrupted: {e}")
    -        finally:
    -            req_queue.put(None)
    -        
    -        if full_content:
    -            final_result["streamed"] = True
    -            
    -        return final_result
    -
    -    @handle_errors
    -    def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debug=False, status=None, **overrides):
    -        return self._ai_chat_stream(self.stub.ask, input_text, dryrun=dryrun, chat_history=chat_history, session_id=session_id, debug=debug, status=status, **overrides)
    -
    -    @handle_errors
    -    def build_playbook_chat(self, user_input, chat_history=None, status=None, chunk_callback=None):
    -        return self._ai_chat_stream(self.stub.build_playbook_chat, user_input, chat_history=chat_history, status=status, chunk_callback=chunk_callback)
    -
    -    def _process_unary_stream(self, responses, status=None, chunk_callback=None):
    -        full_content = ""
    -        header_printed = False
    -        final_result = {"response": "", "chat_history": []}
    -        md_parser = None
    -
    -        try:
    -            for response in responses:
    -                if response.status_update:
    -                    if status:
    -                        status.update(response.status_update)
    -                    continue
    -                
    -                if response.important_message:
    -                    if status:
    -                        try: status.stop()
    -                        except: pass
    -                    printer.console.print(Text.from_ansi(response.important_message))
    -                    if status:
    -                        try: status.start()
    -                        except: pass
    -                    continue
    -
    -                if not response.is_final:
    -                    if response.text_chunk:
    -                        if not header_printed:
    -                            if status:
    -                                try: status.stop()
    -                                except: pass
    -                            
    -                            if chunk_callback:
    -                                header_printed = True
    -                            else:
    -                                from rich.console import Console as RichConsole
    -                                from rich.rule import Rule
    -                                from ..printer import connpy_theme, get_original_stdout, IncrementalMarkdownParser
    -                                stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
    -                                
    -                                # Print default header
    -                                stable_console.print(Rule("[bold engineer]AI Analysis[/bold engineer]", style="engineer"))
    -                                header_printed = True
    -                                md_parser = IncrementalMarkdownParser(console=stable_console)
    -                        
    -                        full_content += response.text_chunk
    -                        if chunk_callback:
    -                            chunk_callback(response.text_chunk)
    -                        elif md_parser:
    -                            md_parser.feed(response.text_chunk)
    -                    continue
    -                
    -                if response.is_final:
    -                    if md_parser:
    -                        md_parser.flush()
    -                        
    -                    if status:
    -                        try: status.stop()
    -                        except: pass
    -
    -                    final_result = from_struct(response.full_result)
    -                    
    -                    if md_parser:
    -                        from rich.console import Console as RichConsole
    -                        from rich.rule import Rule
    -                        from ..printer import connpy_theme, get_original_stdout
    -                        stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
    -                        stable_console.print(Rule(style="engineer"))
    -                    break
    -        except Exception as e:
    -            if isinstance(e, grpc.RpcError):
    -                raise
    -            printer.warning(f"Stream interrupted: {e}")
    -            
    -        if full_content:
    -            final_result["streamed"] = True
    -            
    -        return final_result
    -
    -    @handle_errors
    -    def analyze_execution_results(self, results, query=None, status=None, chunk_callback=None):
    -        req = connpy_pb2.AnalyzeRequest(query=query or "")
    -        req.results.CopyFrom(to_struct(results))
    -        responses = self.stub.analyze_execution_results(req)
    -        return self._process_unary_stream(responses, status, chunk_callback)
    -
    -    @handle_errors
    -    def predict_execution_results(self, target_nodes, commands, status=None, chunk_callback=None):
    -        req = connpy_pb2.PreflightRequest(target_nodes=target_nodes, commands=commands)
    -        responses = self.stub.predict_execution_results(req)
    -        return self._process_unary_stream(responses, status, chunk_callback)
    -
    -    @handle_errors
    -    def confirm(self, input_text, console=None):
    -        return self.stub.confirm(connpy_pb2.StringRequest(value=input_text)).value
    -
    -    @handle_errors
    -    def list_sessions(self, limit=None):
    -        from .utils import from_value
    -        res = self.stub.list_sessions(Empty())
    -        sessions = from_value(res.data) or []
    -        if limit and len(sessions) > limit:
    -            return sessions[:limit], len(sessions)
    -        return sessions, len(sessions)
    -
    -    @handle_errors
    -    def delete_session(self, session_id):
    -        self.stub.delete_session(connpy_pb2.StringRequest(value=session_id))
    -
    -    @handle_errors
    -    def configure_provider(self, provider, model=None, api_key=None, auth=None):
    -        req = connpy_pb2.ProviderRequest(provider=provider, model=model or "", api_key=api_key or "")
    -        if auth:
    -            req.auth.CopyFrom(to_struct(auth))
    -        self.stub.configure_provider(req)
    -
    -    @handle_errors
    -    def configure_mcp(self, name, url=None, enabled=True, auto_load_on_os=None, remove=False):
    -        req = connpy_pb2.MCPRequest(
    -            name=name,
    -            url=url or "",
    -            enabled=enabled,
    -            auto_load_on_os=auto_load_on_os or "",
    -            remove=remove
    -        )
    -        self.stub.configure_mcp(req)
    -
    -    @handle_errors
    -    def list_mcp_servers(self):
    -        res = self.stub.list_mcp_servers(Empty())
    -        return from_value(res.data) or {}
    -
    -    @handle_errors
    -    def load_session_data(self, session_id):
    -        return from_struct(self.stub.load_session_data(connpy_pb2.StringRequest(value=session_id)).data)
    -
    -
    -

    Methods

    -
    -
    -def analyze_execution_results(self, results, query=None, status=None, chunk_callback=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def analyze_execution_results(self, results, query=None, status=None, chunk_callback=None):
    -    req = connpy_pb2.AnalyzeRequest(query=query or "")
    -    req.results.CopyFrom(to_struct(results))
    -    responses = self.stub.analyze_execution_results(req)
    -    return self._process_unary_stream(responses, status, chunk_callback)
    -
    -
    -
    -
    -def ask(self,
    input_text,
    dryrun=False,
    chat_history=None,
    session_id=None,
    debug=False,
    status=None,
    **overrides)
    -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debug=False, status=None, **overrides):
    -    return self._ai_chat_stream(self.stub.ask, input_text, dryrun=dryrun, chat_history=chat_history, session_id=session_id, debug=debug, status=status, **overrides)
    -
    -
    -
    -
    -def build_playbook_chat(self, user_input, chat_history=None, status=None, chunk_callback=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def build_playbook_chat(self, user_input, chat_history=None, status=None, chunk_callback=None):
    -    return self._ai_chat_stream(self.stub.build_playbook_chat, user_input, chat_history=chat_history, status=status, chunk_callback=chunk_callback)
    -
    -
    -
    -
    -def configure_mcp(self, name, url=None, enabled=True, auto_load_on_os=None, remove=False) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def configure_mcp(self, name, url=None, enabled=True, auto_load_on_os=None, remove=False):
    -    req = connpy_pb2.MCPRequest(
    -        name=name,
    -        url=url or "",
    -        enabled=enabled,
    -        auto_load_on_os=auto_load_on_os or "",
    -        remove=remove
    -    )
    -    self.stub.configure_mcp(req)
    -
    -
    -
    -
    -def configure_provider(self, provider, model=None, api_key=None, auth=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def configure_provider(self, provider, model=None, api_key=None, auth=None):
    -    req = connpy_pb2.ProviderRequest(provider=provider, model=model or "", api_key=api_key or "")
    -    if auth:
    -        req.auth.CopyFrom(to_struct(auth))
    -    self.stub.configure_provider(req)
    -
    -
    -
    -
    -def confirm(self, input_text, console=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def confirm(self, input_text, console=None):
    -    return self.stub.confirm(connpy_pb2.StringRequest(value=input_text)).value
    -
    -
    -
    -
    -def delete_session(self, session_id) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def delete_session(self, session_id):
    -    self.stub.delete_session(connpy_pb2.StringRequest(value=session_id))
    -
    -
    -
    -
    -def list_mcp_servers(self) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def list_mcp_servers(self):
    -    res = self.stub.list_mcp_servers(Empty())
    -    return from_value(res.data) or {}
    -
    -
    -
    -
    -def list_sessions(self, limit=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def list_sessions(self, limit=None):
    -    from .utils import from_value
    -    res = self.stub.list_sessions(Empty())
    -    sessions = from_value(res.data) or []
    -    if limit and len(sessions) > limit:
    -        return sessions[:limit], len(sessions)
    -    return sessions, len(sessions)
    -
    -
    -
    -
    -def load_session_data(self, session_id) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def load_session_data(self, session_id):
    -    return from_struct(self.stub.load_session_data(connpy_pb2.StringRequest(value=session_id)).data)
    -
    -
    -
    -
    -def predict_execution_results(self, target_nodes, commands, status=None, chunk_callback=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def predict_execution_results(self, target_nodes, commands, status=None, chunk_callback=None):
    -    req = connpy_pb2.PreflightRequest(target_nodes=target_nodes, commands=commands)
    -    responses = self.stub.predict_execution_results(req)
    -    return self._process_unary_stream(responses, status, chunk_callback)
    -
    -
    -
    -
    -
    -
    -class AuthClientInterceptor -(token_provider) -
    -
    -
    - -Expand source code - -
    class AuthClientInterceptor(grpc.UnaryUnaryClientInterceptor,
    -                            grpc.UnaryStreamClientInterceptor,
    -                            grpc.StreamUnaryClientInterceptor,
    -                            grpc.StreamStreamClientInterceptor):
    -    def __init__(self, token_provider):
    -        self.token_provider = token_provider
    -
    -    def _add_metadata(self, client_call_details):
    -        token = self.token_provider()
    -        if not token:
    -            return client_call_details
    -        
    -        metadata = []
    -        if client_call_details.metadata:
    -            metadata = list(client_call_details.metadata)
    -            
    -        # Check if already present to avoid duplicates
    -        if not any(k.lower() == "authorization" for k, v in metadata):
    -            metadata.append(("authorization", f"Bearer {token}"))
    -            
    -        return _ClientCallDetails(
    -            method=client_call_details.method,
    -            timeout=client_call_details.timeout,
    -            metadata=metadata,
    -            credentials=client_call_details.credentials,
    -            wait_for_ready=client_call_details.wait_for_ready,
    -            compression=client_call_details.compression,
    -        )
    -
    -    def intercept_unary_unary(self, continuation, client_call_details, request):
    -        new_details = self._add_metadata(client_call_details)
    -        return continuation(new_details, request)
    -
    -    def intercept_unary_stream(self, continuation, client_call_details, request):
    -        new_details = self._add_metadata(client_call_details)
    -        return continuation(new_details, request)
    -
    -    def intercept_stream_unary(self, continuation, client_call_details, request_iterator):
    -        new_details = self._add_metadata(client_call_details)
    -        return continuation(new_details, request_iterator)
    -
    -    def intercept_stream_stream(self, continuation, client_call_details, request_iterator):
    -        new_details = self._add_metadata(client_call_details)
    -        return continuation(new_details, request_iterator)
    -
    -

    Affords intercepting unary-unary invocations.

    -

    Ancestors

    -
      -
    • grpc.UnaryUnaryClientInterceptor
    • -
    • grpc.UnaryStreamClientInterceptor
    • -
    • grpc.StreamUnaryClientInterceptor
    • -
    • grpc.StreamStreamClientInterceptor
    • -
    • abc.ABC
    • -
    -

    Methods

    -
    -
    -def intercept_stream_stream(self, continuation, client_call_details, request_iterator) -
    -
    -
    - -Expand source code - -
    def intercept_stream_stream(self, continuation, client_call_details, request_iterator):
    -    new_details = self._add_metadata(client_call_details)
    -    return continuation(new_details, request_iterator)
    -
    -

    Intercepts a stream-stream invocation.

    -

    Args

    -
    -
    continuation
    -
    A function that proceeds with the invocation by -executing the next interceptor in chain or invoking the -actual RPC on the underlying Channel. It is the interceptor's -responsibility to call it if it decides to move the RPC forward. -The interceptor can use -response_iterator = continuation(client_call_details, request_iterator) -to continue with the RPC. continuation returns an object that is -both a Call for the RPC and an iterator for response values. -Drawing response values from the returned Call-iterator may -raise RpcError indicating termination of the RPC with non-OK -status.
    -
    client_call_details
    -
    A ClientCallDetails object describing the -outgoing RPC.
    -
    request_iterator
    -
    An iterator that yields request values for the RPC.
    -
    -

    Returns

    -

    An object that is both a Call for the RPC and an iterator of -response values. Drawing response values from the returned -Call-iterator may raise RpcError indicating termination of -the RPC with non-OK status. This object should also fulfill the -Future interface, though it may not.

    -
    -
    -def intercept_stream_unary(self, continuation, client_call_details, request_iterator) -
    -
    -
    - -Expand source code - -
    def intercept_stream_unary(self, continuation, client_call_details, request_iterator):
    -    new_details = self._add_metadata(client_call_details)
    -    return continuation(new_details, request_iterator)
    -
    -

    Intercepts a stream-unary invocation asynchronously.

    -

    Args

    -
    -
    continuation
    -
    A function that proceeds with the invocation by -executing the next interceptor in chain or invoking the -actual RPC on the underlying Channel. It is the interceptor's -responsibility to call it if it decides to move the RPC forward. -The interceptor can use -response_future = continuation(client_call_details, request_iterator) -to continue with the RPC. continuation returns an object that is -both a Call for the RPC and a Future. In the event of RPC completion, -the return Call-Future's result value will be the response message -of the RPC. Should the event terminate with non-OK status, the -returned Call-Future's exception value will be an RpcError.
    -
    client_call_details
    -
    A ClientCallDetails object describing the -outgoing RPC.
    -
    request_iterator
    -
    An iterator that yields request values for the RPC.
    -
    -

    Returns

    -

    An object that is both a Call for the RPC and a Future. -In the event of RPC completion, the return Call-Future's -result value will be the response message of the RPC. -Should the event terminate with non-OK status, the returned -Call-Future's exception value will be an RpcError.

    -
    -
    -def intercept_unary_stream(self, continuation, client_call_details, request) -
    -
    -
    - -Expand source code - -
    def intercept_unary_stream(self, continuation, client_call_details, request):
    -    new_details = self._add_metadata(client_call_details)
    -    return continuation(new_details, request)
    -
    -

    Intercepts a unary-stream invocation.

    -

    Args

    -
    -
    continuation
    -
    A function that proceeds with the invocation by -executing the next interceptor in chain or invoking the -actual RPC on the underlying Channel. It is the interceptor's -responsibility to call it if it decides to move the RPC forward. -The interceptor can use -response_iterator = continuation(client_call_details, request) -to continue with the RPC. continuation returns an object that is -both a Call for the RPC and an iterator for response values. -Drawing response values from the returned Call-iterator may -raise RpcError indicating termination of the RPC with non-OK -status.
    -
    client_call_details
    -
    A ClientCallDetails object describing the -outgoing RPC.
    -
    request
    -
    The request value for the RPC.
    -
    -

    Returns

    -

    An object that is both a Call for the RPC and an iterator of -response values. Drawing response values from the returned -Call-iterator may raise RpcError indicating termination of -the RPC with non-OK status. This object should also fulfill the -Future interface, though it may not.

    -
    -
    -def intercept_unary_unary(self, continuation, client_call_details, request) -
    -
    -
    - -Expand source code - -
    def intercept_unary_unary(self, continuation, client_call_details, request):
    -    new_details = self._add_metadata(client_call_details)
    -    return continuation(new_details, request)
    -
    -

    Intercepts a unary-unary invocation asynchronously.

    -

    Args

    -
    -
    continuation
    -
    A function that proceeds with the invocation by -executing the next interceptor in chain or invoking the -actual RPC on the underlying Channel. It is the interceptor's -responsibility to call it if it decides to move the RPC forward. -The interceptor can use -response_future = continuation(client_call_details, request) -to continue with the RPC. continuation returns an object that is -both a Call for the RPC and a Future. In the event of RPC -completion, the return Call-Future's result value will be -the response message of the RPC. Should the event terminate -with non-OK status, the returned Call-Future's exception value -will be an RpcError.
    -
    client_call_details
    -
    A ClientCallDetails object describing the -outgoing RPC.
    -
    request
    -
    The request value for the RPC.
    -
    -

    Returns

    -

    An object that is both a Call for the RPC and a Future. -In the event of RPC completion, the return Call-Future's -result value will be the response message of the RPC. -Should the event terminate with non-OK status, the returned -Call-Future's exception value will be an RpcError.

    -
    -
    -
    -
    -class AuthStub -(channel, remote_host) -
    -
    -
    - -Expand source code - -
    class AuthStub:
    -    def __init__(self, channel, remote_host):
    -        self.stub = connpy_pb2_grpc.AuthServiceStub(channel)
    -        self.remote_host = remote_host
    -
    -    @handle_errors
    -    def login(self, username, password):
    -        req = connpy_pb2.LoginRequest(username=username, password=password)
    -        resp = self.stub.login(req)
    -        return {
    -            "token": resp.token,
    -            "username": resp.username,
    -            "expires_at": resp.expires_at
    -        }
    -
    -    @handle_errors
    -    def change_password(self, old_password, new_password):
    -        req = connpy_pb2.ChangePasswordRequest(old_password=old_password, new_password=new_password)
    -        self.stub.change_password(req)
    -
    -    @handle_errors
    -    def create_api_token(self, name, expires_in_days=0):
    -        req = connpy_pb2.CreateApiTokenRequest(name=name, expires_in_days=expires_in_days)
    -        resp = self.stub.create_api_token(req)
    -        return {
    -            "token_id": resp.token_id,
    -            "raw_token": resp.raw_token,
    -            "name": resp.name,
    -        }
    -
    -    @handle_errors
    -    def list_api_tokens(self):
    -        resp = self.stub.list_api_tokens(Empty())
    -        return [
    -            {
    -                "token_id": t.token_id,
    -                "name": t.name,
    -                "token_prefix": t.token_prefix,
    -                "created_at": t.created_at,
    -                "last_used_at": t.last_used_at,
    -                "expires_at": t.expires_at,
    -            }
    -            for t in resp.tokens
    -        ]
    -
    -    @handle_errors
    -    def revoke_api_token(self, token_id):
    -        req = connpy_pb2.RevokeApiTokenRequest(token_id=token_id)
    -        self.stub.revoke_api_token(req)
    -
    -
    -

    Methods

    -
    -
    -def change_password(self, old_password, new_password) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def change_password(self, old_password, new_password):
    -    req = connpy_pb2.ChangePasswordRequest(old_password=old_password, new_password=new_password)
    -    self.stub.change_password(req)
    -
    -
    -
    -
    -def create_api_token(self, name, expires_in_days=0) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def create_api_token(self, name, expires_in_days=0):
    -    req = connpy_pb2.CreateApiTokenRequest(name=name, expires_in_days=expires_in_days)
    -    resp = self.stub.create_api_token(req)
    -    return {
    -        "token_id": resp.token_id,
    -        "raw_token": resp.raw_token,
    -        "name": resp.name,
    -    }
    -
    -
    -
    -
    -def list_api_tokens(self) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def list_api_tokens(self):
    -    resp = self.stub.list_api_tokens(Empty())
    -    return [
    -        {
    -            "token_id": t.token_id,
    -            "name": t.name,
    -            "token_prefix": t.token_prefix,
    -            "created_at": t.created_at,
    -            "last_used_at": t.last_used_at,
    -            "expires_at": t.expires_at,
    -        }
    -        for t in resp.tokens
    -    ]
    -
    -
    -
    -
    -def login(self, username, password) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def login(self, username, password):
    -    req = connpy_pb2.LoginRequest(username=username, password=password)
    -    resp = self.stub.login(req)
    -    return {
    -        "token": resp.token,
    -        "username": resp.username,
    -        "expires_at": resp.expires_at
    -    }
    -
    -
    -
    -
    -def revoke_api_token(self, token_id) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def revoke_api_token(self, token_id):
    -    req = connpy_pb2.RevokeApiTokenRequest(token_id=token_id)
    -    self.stub.revoke_api_token(req)
    -
    -
    -
    -
    -
    -
    -class ConfigStub -(channel, remote_host) -
    -
    -
    - -Expand source code - -
    class ConfigStub:
    -    def __init__(self, channel, remote_host):
    -        self.stub = connpy_pb2_grpc.ConfigServiceStub(channel)
    -        self.remote_host = remote_host
    -
    -    @handle_errors
    -    def get_settings(self):
    -        return from_struct(self.stub.get_settings(Empty()).data)
    -
    -    @handle_errors
    -    def update_setting(self, key, value):
    -        self.stub.update_setting(connpy_pb2.UpdateRequest(key=key, value=to_value(value)))
    -
    -    @handle_errors
    -    def get_default_dir(self):
    -        return self.stub.get_default_dir(Empty()).value
    -
    -    @handle_errors
    -    def set_config_folder(self, folder):
    -        self.stub.set_config_folder(connpy_pb2.StringRequest(value=folder))
    -
    -    @handle_errors
    -    def encrypt_password(self, password):
    -        return self.stub.encrypt_password(connpy_pb2.StringRequest(value=password)).value
    -
    -
    -

    Methods

    -
    -
    -def encrypt_password(self, password) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def encrypt_password(self, password):
    -    return self.stub.encrypt_password(connpy_pb2.StringRequest(value=password)).value
    -
    -
    -
    -
    -def get_default_dir(self) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def get_default_dir(self):
    -    return self.stub.get_default_dir(Empty()).value
    -
    -
    -
    -
    -def get_settings(self) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def get_settings(self):
    -    return from_struct(self.stub.get_settings(Empty()).data)
    -
    -
    -
    -
    -def set_config_folder(self, folder) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def set_config_folder(self, folder):
    -    self.stub.set_config_folder(connpy_pb2.StringRequest(value=folder))
    -
    -
    -
    -
    -def update_setting(self, key, value) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def update_setting(self, key, value):
    -    self.stub.update_setting(connpy_pb2.UpdateRequest(key=key, value=to_value(value)))
    -
    -
    -
    -
    -
    -
    -class ExecutionStub -(channel, remote_host) -
    -
    -
    - -Expand source code - -
    class ExecutionStub:
    -    def __init__(self, channel, remote_host):
    -        self.stub = connpy_pb2_grpc.ExecutionServiceStub(channel)
    -        self.remote_host = remote_host
    -
    -    @handle_errors
    -    def run_commands(self, nodes_filter, commands, variables=None, parallel=10, timeout=10, folder=None, prompt=None, **kwargs):
    -        nodes_list = [nodes_filter] if isinstance(nodes_filter, str) else list(nodes_filter)
    -        req = connpy_pb2.RunRequest(
    -            nodes=nodes_list,
    -            commands=commands,
    -            folder=folder or "",
    -            prompt=prompt or "",
    -            parallel=parallel,
    -            timeout=timeout,
    -            name=kwargs.get("name", "")
    -        )
    -        if variables is not None:
    -            req.vars.CopyFrom(to_struct(variables))
    -            
    -        final_results = {}
    -        on_complete = kwargs.get("on_node_complete")
    -        
    -        for response in self.stub.run_commands(req):
    -            if on_complete:
    -                on_complete(response.unique_id, response.output, response.status)
    -            final_results[response.unique_id] = {
    -                "output": response.output,
    -                "status": response.status
    -            }
    -                
    -        return final_results
    -
    -    @handle_errors
    -    def test_commands(self, nodes_filter, commands, expected, variables=None, parallel=10, timeout=10, prompt=None, **kwargs):
    -        nodes_list = [nodes_filter] if isinstance(nodes_filter, str) else list(nodes_filter)
    -        req = connpy_pb2.TestRequest(
    -            nodes=nodes_list,
    -            commands=commands,
    -            expected=expected if isinstance(expected, list) else [expected],
    -            folder=kwargs.get("folder", ""),
    -            prompt=prompt or "",
    -            parallel=parallel,
    -            timeout=timeout,
    -            name=kwargs.get("name", "")
    -        )
    -        if variables is not None:
    -            req.vars.CopyFrom(to_struct(variables))
    -            
    -        final_results = {}
    -        on_complete = kwargs.get("on_node_complete")
    -        
    -        for response in self.stub.test_commands(req):
    -            result_dict = from_struct(response.test_result) if response.HasField("test_result") else {}
    -            if on_complete:
    -                on_complete(response.unique_id, response.output, response.status, result_dict)
    -            final_results[response.unique_id] = result_dict
    -                
    -        return final_results
    -
    -    @handle_errors
    -    def run_cli_script(self, nodes_filter, script_path, parallel=10):
    -        req = connpy_pb2.ScriptRequest(param1=nodes_filter, param2=script_path, parallel=parallel)
    -        return from_struct(self.stub.run_cli_script(req).data)
    -
    -
    -

    Methods

    -
    -
    -def run_cli_script(self, nodes_filter, script_path, parallel=10) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def run_cli_script(self, nodes_filter, script_path, parallel=10):
    -    req = connpy_pb2.ScriptRequest(param1=nodes_filter, param2=script_path, parallel=parallel)
    -    return from_struct(self.stub.run_cli_script(req).data)
    -
    -
    -
    -
    -def run_commands(self,
    nodes_filter,
    commands,
    variables=None,
    parallel=10,
    timeout=10,
    folder=None,
    prompt=None,
    **kwargs)
    -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def run_commands(self, nodes_filter, commands, variables=None, parallel=10, timeout=10, folder=None, prompt=None, **kwargs):
    -    nodes_list = [nodes_filter] if isinstance(nodes_filter, str) else list(nodes_filter)
    -    req = connpy_pb2.RunRequest(
    -        nodes=nodes_list,
    -        commands=commands,
    -        folder=folder or "",
    -        prompt=prompt or "",
    -        parallel=parallel,
    -        timeout=timeout,
    -        name=kwargs.get("name", "")
    -    )
    -    if variables is not None:
    -        req.vars.CopyFrom(to_struct(variables))
    -        
    -    final_results = {}
    -    on_complete = kwargs.get("on_node_complete")
    -    
    -    for response in self.stub.run_commands(req):
    -        if on_complete:
    -            on_complete(response.unique_id, response.output, response.status)
    -        final_results[response.unique_id] = {
    -            "output": response.output,
    -            "status": response.status
    -        }
    -            
    -    return final_results
    -
    -
    -
    -
    -def test_commands(self,
    nodes_filter,
    commands,
    expected,
    variables=None,
    parallel=10,
    timeout=10,
    prompt=None,
    **kwargs)
    -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def test_commands(self, nodes_filter, commands, expected, variables=None, parallel=10, timeout=10, prompt=None, **kwargs):
    -    nodes_list = [nodes_filter] if isinstance(nodes_filter, str) else list(nodes_filter)
    -    req = connpy_pb2.TestRequest(
    -        nodes=nodes_list,
    -        commands=commands,
    -        expected=expected if isinstance(expected, list) else [expected],
    -        folder=kwargs.get("folder", ""),
    -        prompt=prompt or "",
    -        parallel=parallel,
    -        timeout=timeout,
    -        name=kwargs.get("name", "")
    -    )
    -    if variables is not None:
    -        req.vars.CopyFrom(to_struct(variables))
    -        
    -    final_results = {}
    -    on_complete = kwargs.get("on_node_complete")
    -    
    -    for response in self.stub.test_commands(req):
    -        result_dict = from_struct(response.test_result) if response.HasField("test_result") else {}
    -        if on_complete:
    -            on_complete(response.unique_id, response.output, response.status, result_dict)
    -        final_results[response.unique_id] = result_dict
    -            
    -    return final_results
    -
    -
    -
    -
    -
    -
    -class ImportExportStub -(channel, remote_host) -
    -
    -
    - -Expand source code - -
    class ImportExportStub:
    -    def __init__(self, channel, remote_host):
    -        self.stub = connpy_pb2_grpc.ImportExportServiceStub(channel)
    -        self.remote_host = remote_host
    -
    -    @handle_errors
    -    def export_to_file(self, file_path, folders=None):
    -        req = connpy_pb2.ExportRequest(file_path=file_path, folders=folders or [])
    -        self.stub.export_to_file(req)
    -
    -    @handle_errors
    -    def import_from_file(self, file_path):
    -        with open(file_path, "r") as f:
    -            content = f.read()
    -        # Marker to tell the server this is content, not a path
    -        marker_content = f"---YAML---\n{content}"
    -        self.stub.import_from_file(connpy_pb2.StringRequest(value=marker_content))
    -
    -    @handle_errors
    -    def set_reserved_names(self, names):
    -        self.stub.set_reserved_names(connpy_pb2.ListRequest(items=names))
    -
    -
    -

    Methods

    -
    -
    -def export_to_file(self, file_path, folders=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def export_to_file(self, file_path, folders=None):
    -    req = connpy_pb2.ExportRequest(file_path=file_path, folders=folders or [])
    -    self.stub.export_to_file(req)
    -
    -
    -
    -
    -def import_from_file(self, file_path) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def import_from_file(self, file_path):
    -    with open(file_path, "r") as f:
    -        content = f.read()
    -    # Marker to tell the server this is content, not a path
    -    marker_content = f"---YAML---\n{content}"
    -    self.stub.import_from_file(connpy_pb2.StringRequest(value=marker_content))
    -
    -
    -
    -
    -def set_reserved_names(self, names) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def set_reserved_names(self, names):
    -    self.stub.set_reserved_names(connpy_pb2.ListRequest(items=names))
    -
    -
    -
    -
    -
    -
    -class NodeStub -(channel, remote_host, config=None) -
    -
    -
    - -Expand source code - -
    class NodeStub:
    -    def __init__(self, channel, remote_host, config=None):
    -        self.stub = connpy_pb2_grpc.NodeServiceStub(channel)
    -        self.remote_host = remote_host
    -        self.config = config
    -
    -    def _handle_remote_copilot(self, res, request_queue, response_queue, client_buffer_bytes, pause_generator, resume_generator, old_tty):
    -        import json, asyncio, termios, sys, tty, queue, os
    -        from ..core import copilot_terminal_mode
    -        from . import connpy_pb2
    -
    -        pause_generator()
    -        
    -        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -        
    -        node_info = json.loads(res.copilot_node_info_json) if res.copilot_node_info_json else {}
    -        blocks = node_info.get("context_blocks", [])
    -
    -        interface = CopilotInterface(
    -            self.config, 
    -            history=getattr(self, 'copilot_history', None),
    -            session_state=getattr(self, 'copilot_state', None)
    -        )
    -        self.copilot_history = interface.history
    -        self.copilot_state = interface.session_state
    -        interface.session_state['banner_shown'] = False
    -
    -        async def on_ai_call_remote(active_buffer, question, chunk_callback, merged_node_info):
    -            # Send request to server
    -            request_queue.put(connpy_pb2.InteractRequest(
    -                copilot_question=question, 
    -                copilot_context_buffer=active_buffer,
    -                copilot_node_info_json=json.dumps(merged_node_info)
    -            ))
    -            # Wait for chunks from server
    -            while True:
    -                try:
    -                    chunk_res = response_queue.get(timeout=0.1)
    -                    if chunk_res is None: return {"error": "Server disconnected"}
    -                    if chunk_res.copilot_stream_chunk:
    -                        chunk_callback(chunk_res.copilot_stream_chunk)
    -                    elif chunk_res.copilot_response_json:
    -                        return json.loads(chunk_res.copilot_response_json)
    -                except queue.Empty:
    -                    await asyncio.sleep(0.05)
    -
    -        # Wrap in async loop
    -        async def run_remote_copilot():
    -            nonlocal blocks, node_info
    -            while True:
    -                action, commands, custom_cmd = await interface.run_session(
    -                    raw_bytes=bytes(client_buffer_bytes),
    -                    node_info=node_info,
    -                    on_ai_call=on_ai_call_remote,
    -                    blocks=blocks
    -                )
    -                
    -                if action == "continue":
    -                    # Send continue signal to server to loop back for another question
    -                    request_queue.put(connpy_pb2.InteractRequest(copilot_action="continue"))
    -                    continue
    -                
    -                if action in ("send_all", "custom"):
    -                    action_sent = "cancel"
    -                    if action == "send_all" and commands:
    -                        action_sent = f"custom:{chr(10).join(commands)}"
    -                    elif action == "custom" and custom_cmd:
    -                        action_sent = f"custom:{chr(10).join(custom_cmd)}"
    -                    request_queue.put(connpy_pb2.InteractRequest(copilot_action=action_sent))
    -
    -                    print("\r\n\033[2m [Remote] Ejecutando comandos y esperando al prompt...\033[0m\r\n", flush=True)
    -                    while True:
    -                        try:
    -                            prompt_res = response_queue.get(timeout=0.1)
    -                            if prompt_res is None:
    -                                return "cancel", None, None
    -                            if prompt_res.stdout_data:
    -                                os.write(sys.stdout.fileno(), prompt_res.stdout_data)
    -                                client_buffer_bytes.extend(prompt_res.stdout_data)
    -                            if prompt_res.copilot_prompt:
    -                                if prompt_res.copilot_node_info_json:
    -                                    node_info = json.loads(prompt_res.copilot_node_info_json)
    -                                    blocks = node_info.get("context_blocks", [])
    -                                break
    -                        except queue.Empty:
    -                            await asyncio.sleep(0.05)
    -                    continue
    -
    -                return action, commands, custom_cmd
    -        
    -        with copilot_terminal_mode():
    -            action, commands, custom_cmd = asyncio.run(run_remote_copilot())
    -        
    -        print("\033[2m Returning to session...\033[0m", flush=True)
    -        # Prepare final action for server
    -        request_queue.put(connpy_pb2.InteractRequest(copilot_action="cancel"))
    -        resume_generator()
    -        tty.setraw(sys.stdin.fileno())
    -
    -    @handle_errors
    -    def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
    -        import sys
    -        import select
    -        import tty
    -        import termios
    -        import queue
    -        import os
    -        import threading
    -        
    -        request_queue = queue.Queue()
    -        client_buffer_bytes = bytearray()
    -        pause_stdin = [False]
    -        wake_r, wake_w = os.pipe()
    -
    -        def pause_generator():
    -            pause_stdin[0] = True
    -            os.write(wake_w, b'\x00')
    -
    -        def resume_generator():
    -            pause_stdin[0] = False
    -
    -        def request_generator():
    -            cols, rows = 80, 24
    -            try:
    -                size = os.get_terminal_size()
    -                cols, rows = size.columns, size.lines
    -            except OSError:
    -                pass
    -                
    -            yield connpy_pb2.InteractRequest(
    -                id=unique_id, sftp=sftp, debug=debug, cols=cols, rows=rows
    -            )
    -            
    -            while True:
    -                try:
    -                    while True:
    -                        req = request_queue.get_nowait()
    -                        if req is None:
    -                            return
    -                        yield req
    -                except queue.Empty:
    -                    pass
    -
    -                if pause_stdin[0]:
    -                    import time
    -                    time.sleep(0.05)
    -                    continue
    -
    -                r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
    -                if wake_r in r:
    -                    os.read(wake_r, 1)
    -                    continue
    -                if sys.stdin.fileno() in r and not pause_stdin[0]:
    -                    try:
    -                        data = os.read(sys.stdin.fileno(), 1024)
    -                        if not data:
    -                            break
    -                        yield connpy_pb2.InteractRequest(stdin_data=data)
    -                    except OSError:
    -                        break
    -
    -        # Fetch node details for the connection message
    -        try:
    -            node_details = self.get_node_details(unique_id)
    -            host = node_details.get("host", "unknown")
    -            port = str(node_details.get("port", ""))
    -            protocol = "sftp" if sftp else node_details.get("protocol", "ssh")
    -            port_str = f":{port}" if port and protocol not in ["ssm", "kubectl", "docker"] else ""
    -            conn_msg = f"Connected to {unique_id} at {host}{port_str} via: {protocol}"
    -        except Exception:
    -            conn_msg = f"Connected to {unique_id}"
    -
    -        old_tty = termios.tcgetattr(sys.stdin)
    -        try:
    -            import time
    -            tty.setraw(sys.stdin.fileno())
    -            response_iterator = self.stub.interact_node(request_generator())
    -            
    -            import queue
    -            response_queue = queue.Queue()
    -            
    -            def response_consumer():
    -                try:
    -                    for r in response_iterator:
    -                        response_queue.put(r)
    -                except Exception:
    -                    pass
    -                response_queue.put(None)
    -                
    -            t_consumer = threading.Thread(target=response_consumer, daemon=True)
    -            t_consumer.start()
    -            
    -            # First phase: Wait for connection status, print early data
    -            try:
    -                while True:
    -                    res = response_queue.get()
    -                    if res is None:
    -                        return
    -                    if res.stdout_data:
    -                        data = res.stdout_data
    -                        if debug:
    -                            data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
    -                        os.write(sys.stdout.fileno(), data)
    -                    
    -                    if res.success:
    -                        # Connection established on server, show success message
    -                        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -                        printer.success(conn_msg)
    -                        pause_stdin[0] = False
    -                        tty.setraw(sys.stdin.fileno())
    -                        break
    -                    
    -                    if res.error_message:
    -                        # Connection failed on server
    -                        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -                        printer.error(f"Connection failed: {res.error_message}")
    -                        return
    -            except queue.Empty:
    -                return
    -            
    -            # Second phase: Stream active session
    -            # Clear screen filter is only applied before success (Phase 1).
    -            # Once the user has a prompt, Ctrl+L must work normally.
    -            while True:
    -                res = response_queue.get()
    -                if res is None:
    -                    break
    -                if res.copilot_prompt:
    -                    self._handle_remote_copilot(
    -                        res, request_queue, response_queue, 
    -                        client_buffer_bytes, 
    -                        pause_generator, resume_generator, old_tty
    -                    )
    -                    continue
    -
    -                if res.stdout_data:
    -                    os.write(sys.stdout.fileno(), res.stdout_data)
    -                    client_buffer_bytes.extend(res.stdout_data)
    -        finally:
    -            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -            os.close(wake_r)
    -            os.close(wake_w)
    -
    -    @handle_errors
    -    def connect_dynamic(self, connection_params, debug=False):
    -        import sys
    -        import select
    -        import tty
    -        import termios
    -        import queue
    -        import os
    -        import json
    -        
    -        params_json = json.dumps(connection_params)
    -        request_queue = queue.Queue()
    -        client_buffer_bytes = bytearray()
    -        pause_stdin = [False]
    -        wake_r, wake_w = os.pipe()
    -
    -        def pause_generator():
    -            pause_stdin[0] = True
    -            os.write(wake_w, b'\x00')
    -
    -        def resume_generator():
    -            pause_stdin[0] = False
    -        
    -        def request_generator():
    -            cols, rows = 80, 24
    -            try:
    -                size = os.get_terminal_size()
    -                cols, rows = size.columns, size.lines
    -            except OSError:
    -                pass
    -                
    -            yield connpy_pb2.InteractRequest(
    -                id="dynamic", debug=debug, cols=cols, rows=rows,
    -                connection_params_json=params_json
    -            )
    -            
    -            while True:
    -                try:
    -                    while True:
    -                        req = request_queue.get_nowait()
    -                        if req is None:
    -                            return
    -                        yield req
    -                except queue.Empty:
    -                    pass
    -
    -                if pause_stdin[0]:
    -                    import time
    -                    time.sleep(0.05)
    -                    continue
    -
    -                r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
    -                if wake_r in r:
    -                    os.read(wake_r, 1)
    -                    continue
    -                if sys.stdin.fileno() in r and not pause_stdin[0]:
    -                    try:
    -                        data = os.read(sys.stdin.fileno(), 1024)
    -                        if not data:
    -                            break
    -                        yield connpy_pb2.InteractRequest(stdin_data=data)
    -                    except OSError:
    -                        break
    -
    -        # Prepare connection message
    -        try:
    -            node_name = connection_params.get("name", "dynamic@remote")
    -            host = connection_params.get("host", "dynamic")
    -            port = str(connection_params.get("port", ""))
    -            protocol = connection_params.get("protocol", "ssh")
    -            port_str = f":{port}" if port and protocol not in ["ssm", "kubectl", "docker"] else ""
    -            conn_msg = f"Connected to {node_name} at {host}{port_str} via: {protocol}"
    -        except Exception:
    -            node_name = connection_params.get("name", "dynamic@remote") if isinstance(connection_params, dict) else "dynamic@remote"
    -            conn_msg = f"Connected to {node_name}"
    -
    -        old_tty = termios.tcgetattr(sys.stdin)
    -        try:
    -            import time
    -            tty.setraw(sys.stdin.fileno())
    -            response_iterator = self.stub.interact_node(request_generator())
    -            
    -            import queue
    -            response_queue = queue.Queue()
    -            
    -            def response_consumer():
    -                try:
    -                    for r in response_iterator:
    -                        response_queue.put(r)
    -                except Exception:
    -                    pass
    -                response_queue.put(None)
    -                
    -            t_consumer = threading.Thread(target=response_consumer, daemon=True)
    -            t_consumer.start()
    -            
    -            # First phase: Wait for connection status, print early data
    -            try:
    -                while True:
    -                    res = response_queue.get()
    -                    if res is None:
    -                        return
    -                    if res.stdout_data:
    -                        data = res.stdout_data
    -                        if debug:
    -                            data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
    -                        os.write(sys.stdout.fileno(), data)
    -                    
    -                    if res.success:
    -                        # Connection established on server, show success message
    -                        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -                        printer.success(conn_msg)
    -                        pause_stdin[0] = False
    -                        tty.setraw(sys.stdin.fileno())
    -                        break
    -                    
    -                    if res.error_message:
    -                        # Connection failed on server
    -                        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -                        printer.error(f"Connection failed: {res.error_message}")
    -                        return
    -            except queue.Empty:
    -                return
    -                
    -            # Second phase: Stream active session
    -            while True:
    -                res = response_queue.get()
    -                if res is None:
    -                    break
    -                if res.copilot_prompt:
    -                    self._handle_remote_copilot(
    -                        res, request_queue, response_queue, 
    -                        client_buffer_bytes, 
    -                        pause_generator, resume_generator, old_tty
    -                    )
    -                    continue
    -
    -                if res.stdout_data:
    -                    os.write(sys.stdout.fileno(), res.stdout_data)
    -                    client_buffer_bytes.extend(res.stdout_data)
    -        finally:
    -            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -            os.close(wake_r)
    -            os.close(wake_w)
    -
    -    @MethodHook
    -    @handle_errors
    -    def list_nodes(self, filter_str=None, format_str=None):
    -        req = connpy_pb2.FilterRequest(filter_str=filter_str or "", format_str=format_str or "")
    -        return from_value(self.stub.list_nodes(req).data) or []
    -
    -    @MethodHook
    -    @handle_errors
    -    def list_folders(self, filter_str=None):
    -        req = connpy_pb2.FilterRequest(filter_str=filter_str or "")
    -        return from_value(self.stub.list_folders(req).data) or []
    -
    -    @handle_errors
    -    def get_node_details(self, unique_id):
    -        return from_struct(self.stub.get_node_details(connpy_pb2.IdRequest(id=unique_id)).data)
    -
    -    @handle_errors
    -    def explode_unique(self, unique_id):
    -        return from_value(self.stub.explode_unique(connpy_pb2.IdRequest(id=unique_id)).data)
    -
    -    @handle_errors
    -    def validate_parent_folder(self, unique_id):
    -        self.stub.validate_parent_folder(connpy_pb2.IdRequest(id=unique_id))
    -
    -    @handle_errors
    -    def generate_cache(self, nodes=None, folders=None, profiles=None):
    -        # 1. Update remote cache on server
    -        self.stub.generate_cache(Empty())
    -        
    -        # 2. Update local fzf/text cache files
    -        # If no data provided, we fetch it all from remote to sync local files
    -        if nodes is None and folders is None and profiles is None:
    -            nodes = self.list_nodes()
    -            folders = self.list_folders()
    -            # We don't have direct access to ProfileStub here, but usually 
    -            # node cache is what matters for fzf. We'll fetch profiles if we can.
    -            # For now, let's sync what we have.
    -            
    -        if nodes is not None or folders is not None or profiles is not None:
    -            self.config._generate_nodes_cache(nodes=nodes, folders=folders, profiles=profiles)
    -
    -    def _trigger_local_cache_sync(self):
    -        """Helper to fetch remote data and update local fzf cache files after a change."""
    -        try:
    -            nodes = self.list_nodes()
    -            folders = self.list_folders()
    -            self.generate_cache(nodes=nodes, folders=folders)
    -        except Exception:
    -            # Failure to sync cache shouldn't break the main operation's success feedback
    -            pass
    -
    -    @handle_errors
    -    def add_node(self, unique_id, data, is_folder=False):
    -        req = connpy_pb2.NodeRequest(id=unique_id, data=to_struct(data), is_folder=is_folder)
    -        self.stub.add_node(req)
    -        self._trigger_local_cache_sync()
    -
    -    @handle_errors
    -    def update_node(self, unique_id, data, save=True):
    -        req = connpy_pb2.NodeRequest(id=unique_id, data=to_struct(data), is_folder=False)
    -        self.stub.update_node(req)
    -        if save:
    -            self._trigger_local_cache_sync()
    -
    -    @handle_errors
    -    def delete_node(self, unique_id, is_folder=False, save=True):
    -        req = connpy_pb2.DeleteRequest(id=unique_id, is_folder=is_folder)
    -        self.stub.delete_node(req)
    -        if save:
    -            self._trigger_local_cache_sync()
    -
    -    @handle_errors
    -    def move_node(self, src_id, dst_id, copy=False):
    -        req = connpy_pb2.MoveRequest(src_id=src_id, dst_id=dst_id, copy=copy)
    -        self.stub.move_node(req)
    -        self._trigger_local_cache_sync()
    -
    -    @handle_errors
    -    def bulk_add(self, ids, hosts, common_data):
    -        req = connpy_pb2.BulkRequest(ids=ids, hosts=hosts, common_data=to_struct(common_data))
    -        self.stub.bulk_add(req)
    -        self._trigger_local_cache_sync()
    -
    -    @handle_errors
    -    def set_reserved_names(self, names):
    -        self.stub.set_reserved_names(connpy_pb2.ListRequest(items=names))
    -        self._trigger_local_cache_sync()
    -
    -    @handle_errors
    -    def full_replace(self, connections, profiles):
    -        req = connpy_pb2.FullReplaceRequest(
    -            connections=to_struct(connections),
    -            profiles=to_struct(profiles)
    -        )
    -        self.stub.full_replace(req)
    -        self._trigger_local_cache_sync()
    -
    -    @handle_errors
    -    def get_inventory(self):
    -        resp = self.stub.get_inventory(Empty())
    -        return {
    -            "connections": from_struct(resp.connections),
    -            "profiles": from_struct(resp.profiles)
    -        }
    -
    -
    -

    Methods

    -
    -
    -def add_node(self, unique_id, data, is_folder=False) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def add_node(self, unique_id, data, is_folder=False):
    -    req = connpy_pb2.NodeRequest(id=unique_id, data=to_struct(data), is_folder=is_folder)
    -    self.stub.add_node(req)
    -    self._trigger_local_cache_sync()
    -
    -
    -
    -
    -def bulk_add(self, ids, hosts, common_data) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def bulk_add(self, ids, hosts, common_data):
    -    req = connpy_pb2.BulkRequest(ids=ids, hosts=hosts, common_data=to_struct(common_data))
    -    self.stub.bulk_add(req)
    -    self._trigger_local_cache_sync()
    -
    -
    -
    -
    -def connect_dynamic(self, connection_params, debug=False) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def connect_dynamic(self, connection_params, debug=False):
    -    import sys
    -    import select
    -    import tty
    -    import termios
    -    import queue
    -    import os
    -    import json
    -    
    -    params_json = json.dumps(connection_params)
    -    request_queue = queue.Queue()
    -    client_buffer_bytes = bytearray()
    -    pause_stdin = [False]
    -    wake_r, wake_w = os.pipe()
    -
    -    def pause_generator():
    -        pause_stdin[0] = True
    -        os.write(wake_w, b'\x00')
    -
    -    def resume_generator():
    -        pause_stdin[0] = False
    -    
    -    def request_generator():
    -        cols, rows = 80, 24
    -        try:
    -            size = os.get_terminal_size()
    -            cols, rows = size.columns, size.lines
    -        except OSError:
    -            pass
    -            
    -        yield connpy_pb2.InteractRequest(
    -            id="dynamic", debug=debug, cols=cols, rows=rows,
    -            connection_params_json=params_json
    -        )
    -        
    -        while True:
    -            try:
    -                while True:
    -                    req = request_queue.get_nowait()
    -                    if req is None:
    -                        return
    -                    yield req
    -            except queue.Empty:
    -                pass
    -
    -            if pause_stdin[0]:
    -                import time
    -                time.sleep(0.05)
    -                continue
    -
    -            r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
    -            if wake_r in r:
    -                os.read(wake_r, 1)
    -                continue
    -            if sys.stdin.fileno() in r and not pause_stdin[0]:
    -                try:
    -                    data = os.read(sys.stdin.fileno(), 1024)
    -                    if not data:
    -                        break
    -                    yield connpy_pb2.InteractRequest(stdin_data=data)
    -                except OSError:
    -                    break
    -
    -    # Prepare connection message
    -    try:
    -        node_name = connection_params.get("name", "dynamic@remote")
    -        host = connection_params.get("host", "dynamic")
    -        port = str(connection_params.get("port", ""))
    -        protocol = connection_params.get("protocol", "ssh")
    -        port_str = f":{port}" if port and protocol not in ["ssm", "kubectl", "docker"] else ""
    -        conn_msg = f"Connected to {node_name} at {host}{port_str} via: {protocol}"
    -    except Exception:
    -        node_name = connection_params.get("name", "dynamic@remote") if isinstance(connection_params, dict) else "dynamic@remote"
    -        conn_msg = f"Connected to {node_name}"
    -
    -    old_tty = termios.tcgetattr(sys.stdin)
    -    try:
    -        import time
    -        tty.setraw(sys.stdin.fileno())
    -        response_iterator = self.stub.interact_node(request_generator())
    -        
    -        import queue
    -        response_queue = queue.Queue()
    -        
    -        def response_consumer():
    -            try:
    -                for r in response_iterator:
    -                    response_queue.put(r)
    -            except Exception:
    -                pass
    -            response_queue.put(None)
    -            
    -        t_consumer = threading.Thread(target=response_consumer, daemon=True)
    -        t_consumer.start()
    -        
    -        # First phase: Wait for connection status, print early data
    -        try:
    -            while True:
    -                res = response_queue.get()
    -                if res is None:
    -                    return
    -                if res.stdout_data:
    -                    data = res.stdout_data
    -                    if debug:
    -                        data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
    -                    os.write(sys.stdout.fileno(), data)
    -                
    -                if res.success:
    -                    # Connection established on server, show success message
    -                    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -                    printer.success(conn_msg)
    -                    pause_stdin[0] = False
    -                    tty.setraw(sys.stdin.fileno())
    -                    break
    -                
    -                if res.error_message:
    -                    # Connection failed on server
    -                    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -                    printer.error(f"Connection failed: {res.error_message}")
    -                    return
    -        except queue.Empty:
    -            return
    -            
    -        # Second phase: Stream active session
    -        while True:
    -            res = response_queue.get()
    -            if res is None:
    -                break
    -            if res.copilot_prompt:
    -                self._handle_remote_copilot(
    -                    res, request_queue, response_queue, 
    -                    client_buffer_bytes, 
    -                    pause_generator, resume_generator, old_tty
    -                )
    -                continue
    -
    -            if res.stdout_data:
    -                os.write(sys.stdout.fileno(), res.stdout_data)
    -                client_buffer_bytes.extend(res.stdout_data)
    -    finally:
    -        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -        os.close(wake_r)
    -        os.close(wake_w)
    -
    -
    -
    -
    -def connect_node(self, unique_id, sftp=False, debug=False, logger=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
    -    import sys
    -    import select
    -    import tty
    -    import termios
    -    import queue
    -    import os
    -    import threading
    -    
    -    request_queue = queue.Queue()
    -    client_buffer_bytes = bytearray()
    -    pause_stdin = [False]
    -    wake_r, wake_w = os.pipe()
    -
    -    def pause_generator():
    -        pause_stdin[0] = True
    -        os.write(wake_w, b'\x00')
    -
    -    def resume_generator():
    -        pause_stdin[0] = False
    -
    -    def request_generator():
    -        cols, rows = 80, 24
    -        try:
    -            size = os.get_terminal_size()
    -            cols, rows = size.columns, size.lines
    -        except OSError:
    -            pass
    -            
    -        yield connpy_pb2.InteractRequest(
    -            id=unique_id, sftp=sftp, debug=debug, cols=cols, rows=rows
    -        )
    -        
    -        while True:
    -            try:
    -                while True:
    -                    req = request_queue.get_nowait()
    -                    if req is None:
    -                        return
    -                    yield req
    -            except queue.Empty:
    -                pass
    -
    -            if pause_stdin[0]:
    -                import time
    -                time.sleep(0.05)
    -                continue
    -
    -            r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
    -            if wake_r in r:
    -                os.read(wake_r, 1)
    -                continue
    -            if sys.stdin.fileno() in r and not pause_stdin[0]:
    -                try:
    -                    data = os.read(sys.stdin.fileno(), 1024)
    -                    if not data:
    -                        break
    -                    yield connpy_pb2.InteractRequest(stdin_data=data)
    -                except OSError:
    -                    break
    -
    -    # Fetch node details for the connection message
    -    try:
    -        node_details = self.get_node_details(unique_id)
    -        host = node_details.get("host", "unknown")
    -        port = str(node_details.get("port", ""))
    -        protocol = "sftp" if sftp else node_details.get("protocol", "ssh")
    -        port_str = f":{port}" if port and protocol not in ["ssm", "kubectl", "docker"] else ""
    -        conn_msg = f"Connected to {unique_id} at {host}{port_str} via: {protocol}"
    -    except Exception:
    -        conn_msg = f"Connected to {unique_id}"
    -
    -    old_tty = termios.tcgetattr(sys.stdin)
    -    try:
    -        import time
    -        tty.setraw(sys.stdin.fileno())
    -        response_iterator = self.stub.interact_node(request_generator())
    -        
    -        import queue
    -        response_queue = queue.Queue()
    -        
    -        def response_consumer():
    -            try:
    -                for r in response_iterator:
    -                    response_queue.put(r)
    -            except Exception:
    -                pass
    -            response_queue.put(None)
    -            
    -        t_consumer = threading.Thread(target=response_consumer, daemon=True)
    -        t_consumer.start()
    -        
    -        # First phase: Wait for connection status, print early data
    -        try:
    -            while True:
    -                res = response_queue.get()
    -                if res is None:
    -                    return
    -                if res.stdout_data:
    -                    data = res.stdout_data
    -                    if debug:
    -                        data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
    -                    os.write(sys.stdout.fileno(), data)
    -                
    -                if res.success:
    -                    # Connection established on server, show success message
    -                    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -                    printer.success(conn_msg)
    -                    pause_stdin[0] = False
    -                    tty.setraw(sys.stdin.fileno())
    -                    break
    -                
    -                if res.error_message:
    -                    # Connection failed on server
    -                    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -                    printer.error(f"Connection failed: {res.error_message}")
    -                    return
    -        except queue.Empty:
    -            return
    -        
    -        # Second phase: Stream active session
    -        # Clear screen filter is only applied before success (Phase 1).
    -        # Once the user has a prompt, Ctrl+L must work normally.
    -        while True:
    -            res = response_queue.get()
    -            if res is None:
    -                break
    -            if res.copilot_prompt:
    -                self._handle_remote_copilot(
    -                    res, request_queue, response_queue, 
    -                    client_buffer_bytes, 
    -                    pause_generator, resume_generator, old_tty
    -                )
    -                continue
    -
    -            if res.stdout_data:
    -                os.write(sys.stdout.fileno(), res.stdout_data)
    -                client_buffer_bytes.extend(res.stdout_data)
    -    finally:
    -        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    -        os.close(wake_r)
    -        os.close(wake_w)
    -
    -
    -
    -
    -def delete_node(self, unique_id, is_folder=False, save=True) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def delete_node(self, unique_id, is_folder=False, save=True):
    -    req = connpy_pb2.DeleteRequest(id=unique_id, is_folder=is_folder)
    -    self.stub.delete_node(req)
    -    if save:
    -        self._trigger_local_cache_sync()
    -
    -
    -
    -
    -def explode_unique(self, unique_id) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def explode_unique(self, unique_id):
    -    return from_value(self.stub.explode_unique(connpy_pb2.IdRequest(id=unique_id)).data)
    -
    -
    -
    -
    -def full_replace(self, connections, profiles) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def full_replace(self, connections, profiles):
    -    req = connpy_pb2.FullReplaceRequest(
    -        connections=to_struct(connections),
    -        profiles=to_struct(profiles)
    -    )
    -    self.stub.full_replace(req)
    -    self._trigger_local_cache_sync()
    -
    -
    -
    -
    -def generate_cache(self, nodes=None, folders=None, profiles=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def generate_cache(self, nodes=None, folders=None, profiles=None):
    -    # 1. Update remote cache on server
    -    self.stub.generate_cache(Empty())
    -    
    -    # 2. Update local fzf/text cache files
    -    # If no data provided, we fetch it all from remote to sync local files
    -    if nodes is None and folders is None and profiles is None:
    -        nodes = self.list_nodes()
    -        folders = self.list_folders()
    -        # We don't have direct access to ProfileStub here, but usually 
    -        # node cache is what matters for fzf. We'll fetch profiles if we can.
    -        # For now, let's sync what we have.
    -        
    -    if nodes is not None or folders is not None or profiles is not None:
    -        self.config._generate_nodes_cache(nodes=nodes, folders=folders, profiles=profiles)
    -
    -
    -
    -
    -def get_inventory(self) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def get_inventory(self):
    -    resp = self.stub.get_inventory(Empty())
    -    return {
    -        "connections": from_struct(resp.connections),
    -        "profiles": from_struct(resp.profiles)
    -    }
    -
    -
    -
    -
    -def get_node_details(self, unique_id) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def get_node_details(self, unique_id):
    -    return from_struct(self.stub.get_node_details(connpy_pb2.IdRequest(id=unique_id)).data)
    -
    -
    -
    -
    -def list_folders(self, filter_str=None) -
    -
    -
    - -Expand source code - -
    @MethodHook
    -@handle_errors
    -def list_folders(self, filter_str=None):
    -    req = connpy_pb2.FilterRequest(filter_str=filter_str or "")
    -    return from_value(self.stub.list_folders(req).data) or []
    -
    -
    -
    -
    -def list_nodes(self, filter_str=None, format_str=None) -
    -
    -
    - -Expand source code - -
    @MethodHook
    -@handle_errors
    -def list_nodes(self, filter_str=None, format_str=None):
    -    req = connpy_pb2.FilterRequest(filter_str=filter_str or "", format_str=format_str or "")
    -    return from_value(self.stub.list_nodes(req).data) or []
    -
    -
    -
    -
    -def move_node(self, src_id, dst_id, copy=False) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def move_node(self, src_id, dst_id, copy=False):
    -    req = connpy_pb2.MoveRequest(src_id=src_id, dst_id=dst_id, copy=copy)
    -    self.stub.move_node(req)
    -    self._trigger_local_cache_sync()
    -
    -
    -
    -
    -def set_reserved_names(self, names) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def set_reserved_names(self, names):
    -    self.stub.set_reserved_names(connpy_pb2.ListRequest(items=names))
    -    self._trigger_local_cache_sync()
    -
    -
    -
    -
    -def update_node(self, unique_id, data, save=True) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def update_node(self, unique_id, data, save=True):
    -    req = connpy_pb2.NodeRequest(id=unique_id, data=to_struct(data), is_folder=False)
    -    self.stub.update_node(req)
    -    if save:
    -        self._trigger_local_cache_sync()
    -
    -
    -
    -
    -def validate_parent_folder(self, unique_id) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def validate_parent_folder(self, unique_id):
    -    self.stub.validate_parent_folder(connpy_pb2.IdRequest(id=unique_id))
    -
    -
    -
    -
    -
    -
    -class PluginStub -(channel, remote_host) -
    -
    -
    - -Expand source code - -
    class PluginStub:
    -    def __init__(self, channel, remote_host):
    -        self.stub = connpy_pb2_grpc.PluginServiceStub(channel)
    -        self.remote_stub = remote_plugin_pb2_grpc.RemotePluginServiceStub(channel)
    -        self.remote_host = remote_host
    -
    -    @handle_errors
    -    def list_plugins(self):
    -        return from_value(self.stub.list_plugins(Empty()).data)
    -
    -    @handle_errors
    -    def add_plugin(self, name, source_file, update=False):
    -        # Read the local file content to send it to the server
    -        with open(source_file, "r") as f:
    -            content = f.read()
    -        
    -        # Use source_file as a marker for "content-inside"
    -        marker_content = f"---CONTENT---\n{content}"
    -        req = connpy_pb2.PluginRequest(name=name, source_file=marker_content, update=update)
    -        self.stub.add_plugin(req)
    -
    -    @handle_errors
    -    def delete_plugin(self, name):
    -        self.stub.delete_plugin(connpy_pb2.IdRequest(id=name))
    -
    -    @handle_errors
    -    def enable_plugin(self, name):
    -        self.stub.enable_plugin(connpy_pb2.IdRequest(id=name))
    -
    -    @handle_errors
    -    def disable_plugin(self, name):
    -        self.stub.disable_plugin(connpy_pb2.IdRequest(id=name))
    -
    -    @handle_errors
    -    def get_plugin_source(self, name):
    -        resp = self.remote_stub.get_plugin_source(remote_plugin_pb2.IdRequest(id=name))
    -        return resp.value
    -
    -    @handle_errors
    -    def invoke_plugin(self, name, args_namespace):
    -        import json
    -        args_dict = {k: v for k, v in vars(args_namespace).items()
    -                     if isinstance(v, (str, int, float, bool, list, type(None)))}
    -        if hasattr(args_namespace, "func") and hasattr(args_namespace.func, "__name__"):
    -            args_dict["__func_name__"] = args_namespace.func.__name__
    -            
    -        req = remote_plugin_pb2.PluginInvokeRequest(name=name, args_json=json.dumps(args_dict))
    -        for chunk in self.remote_stub.invoke_plugin(req):
    -            yield chunk.text
    -
    -
    -

    Methods

    -
    -
    -def add_plugin(self, name, source_file, update=False) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def add_plugin(self, name, source_file, update=False):
    -    # Read the local file content to send it to the server
    -    with open(source_file, "r") as f:
    -        content = f.read()
    -    
    -    # Use source_file as a marker for "content-inside"
    -    marker_content = f"---CONTENT---\n{content}"
    -    req = connpy_pb2.PluginRequest(name=name, source_file=marker_content, update=update)
    -    self.stub.add_plugin(req)
    -
    -
    -
    -
    -def delete_plugin(self, name) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def delete_plugin(self, name):
    -    self.stub.delete_plugin(connpy_pb2.IdRequest(id=name))
    -
    -
    -
    -
    -def disable_plugin(self, name) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def disable_plugin(self, name):
    -    self.stub.disable_plugin(connpy_pb2.IdRequest(id=name))
    -
    -
    -
    -
    -def enable_plugin(self, name) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def enable_plugin(self, name):
    -    self.stub.enable_plugin(connpy_pb2.IdRequest(id=name))
    -
    -
    -
    -
    -def get_plugin_source(self, name) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def get_plugin_source(self, name):
    -    resp = self.remote_stub.get_plugin_source(remote_plugin_pb2.IdRequest(id=name))
    -    return resp.value
    -
    -
    -
    -
    -def invoke_plugin(self, name, args_namespace) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def invoke_plugin(self, name, args_namespace):
    -    import json
    -    args_dict = {k: v for k, v in vars(args_namespace).items()
    -                 if isinstance(v, (str, int, float, bool, list, type(None)))}
    -    if hasattr(args_namespace, "func") and hasattr(args_namespace.func, "__name__"):
    -        args_dict["__func_name__"] = args_namespace.func.__name__
    -        
    -    req = remote_plugin_pb2.PluginInvokeRequest(name=name, args_json=json.dumps(args_dict))
    -    for chunk in self.remote_stub.invoke_plugin(req):
    -        yield chunk.text
    -
    -
    -
    -
    -def list_plugins(self) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def list_plugins(self):
    -    return from_value(self.stub.list_plugins(Empty()).data)
    -
    -
    -
    -
    -
    -
    -class ProfileStub -(channel, remote_host, node_stub=None) -
    -
    -
    - -Expand source code - -
    class ProfileStub:
    -    def __init__(self, channel, remote_host, node_stub=None):
    -        self.stub = connpy_pb2_grpc.ProfileServiceStub(channel)
    -        self.remote_host = remote_host
    -        self.node_stub = node_stub
    -
    -    @handle_errors
    -    def list_profiles(self, filter_str=None):
    -        req = connpy_pb2.FilterRequest(filter_str=filter_str or "")
    -        return from_value(self.stub.list_profiles(req).data) or []
    -
    -    @handle_errors
    -    def get_profile(self, name, resolve=True):
    -        req = connpy_pb2.ProfileRequest(name=name, resolve=resolve)
    -        return from_struct(self.stub.get_profile(req).data)
    -
    -    @handle_errors
    -    def add_profile(self, name, data):
    -        req = connpy_pb2.NodeRequest(id=name, data=to_struct(data))
    -        self.stub.add_profile(req)
    -        if self.node_stub:
    -            self.node_stub._trigger_local_cache_sync()
    -
    -    @handle_errors
    -    def resolve_node_data(self, node_data):
    -        req = connpy_pb2.StructRequest(data=to_struct(node_data))
    -        return from_struct(self.stub.resolve_node_data(req).data)
    -
    -    @handle_errors
    -    def delete_profile(self, name):
    -        req = connpy_pb2.IdRequest(id=name)
    -        self.stub.delete_profile(req)
    -        if self.node_stub:
    -            self.node_stub._trigger_local_cache_sync()
    -
    -    @handle_errors
    -    def update_profile(self, name, data):
    -        req = connpy_pb2.NodeRequest(id=name, data=to_struct(data))
    -        self.stub.update_profile(req)
    -        if self.node_stub:
    -            self.node_stub._trigger_local_cache_sync()
    -
    -
    -

    Methods

    -
    -
    -def add_profile(self, name, data) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def add_profile(self, name, data):
    -    req = connpy_pb2.NodeRequest(id=name, data=to_struct(data))
    -    self.stub.add_profile(req)
    -    if self.node_stub:
    -        self.node_stub._trigger_local_cache_sync()
    -
    -
    -
    -
    -def delete_profile(self, name) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def delete_profile(self, name):
    -    req = connpy_pb2.IdRequest(id=name)
    -    self.stub.delete_profile(req)
    -    if self.node_stub:
    -        self.node_stub._trigger_local_cache_sync()
    -
    -
    -
    -
    -def get_profile(self, name, resolve=True) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def get_profile(self, name, resolve=True):
    -    req = connpy_pb2.ProfileRequest(name=name, resolve=resolve)
    -    return from_struct(self.stub.get_profile(req).data)
    -
    -
    -
    -
    -def list_profiles(self, filter_str=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def list_profiles(self, filter_str=None):
    -    req = connpy_pb2.FilterRequest(filter_str=filter_str or "")
    -    return from_value(self.stub.list_profiles(req).data) or []
    -
    -
    -
    -
    -def resolve_node_data(self, node_data) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def resolve_node_data(self, node_data):
    -    req = connpy_pb2.StructRequest(data=to_struct(node_data))
    -    return from_struct(self.stub.resolve_node_data(req).data)
    -
    -
    -
    -
    -def update_profile(self, name, data) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def update_profile(self, name, data):
    -    req = connpy_pb2.NodeRequest(id=name, data=to_struct(data))
    -    self.stub.update_profile(req)
    -    if self.node_stub:
    -        self.node_stub._trigger_local_cache_sync()
    -
    -
    -
    -
    -
    -
    -class SystemStub -(channel, remote_host) -
    -
    -
    - -Expand source code - -
    class SystemStub:
    -    def __init__(self, channel, remote_host):
    -        self.stub = connpy_pb2_grpc.SystemServiceStub(channel)
    -        self.remote_host = remote_host
    -
    -    @handle_errors
    -    def start_api(self, port=None):
    -        self.stub.start_api(connpy_pb2.IntRequest(value=port or 8048))
    -
    -    @handle_errors
    -    def debug_api(self, port=None):
    -        self.stub.debug_api(connpy_pb2.IntRequest(value=port or 8048))
    -
    -    @handle_errors
    -    def stop_api(self):
    -        self.stub.stop_api(Empty())
    -
    -    @handle_errors
    -    def restart_api(self, port=None):
    -        self.stub.restart_api(connpy_pb2.IntRequest(value=port or 8048))
    -
    -    @handle_errors
    -    def get_api_status(self):
    -        return self.stub.get_api_status(Empty()).value
    -
    -
    -

    Methods

    -
    -
    -def debug_api(self, port=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def debug_api(self, port=None):
    -    self.stub.debug_api(connpy_pb2.IntRequest(value=port or 8048))
    -
    -
    -
    -
    -def get_api_status(self) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def get_api_status(self):
    -    return self.stub.get_api_status(Empty()).value
    -
    -
    -
    -
    -def restart_api(self, port=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def restart_api(self, port=None):
    -    self.stub.restart_api(connpy_pb2.IntRequest(value=port or 8048))
    -
    -
    -
    -
    -def start_api(self, port=None) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def start_api(self, port=None):
    -    self.stub.start_api(connpy_pb2.IntRequest(value=port or 8048))
    -
    -
    -
    -
    -def stop_api(self) -
    -
    -
    - -Expand source code - -
    @handle_errors
    -def stop_api(self):
    -    self.stub.stop_api(Empty())
    -
    -
    -
    -
    -
    -
    diff --git a/docs/connpy/index.html b/docs/connpy/index.html index 26b7458..b90da42 100644 --- a/docs/connpy/index.html +++ b/docs/connpy/index.html @@ -41,7 +41,7 @@ el.replaceWith(d);

    App Logo

    -

    Connpy (v6.4.0b3)

    +

    Connpy (v6.4.0b4)

    @@ -282,6 +282,10 @@ print(response)

    +
    connpy.mcp_server
    +
    +
    +
    connpy.proto
    @@ -1676,7 +1680,7 @@ def getitems(self, uniques, extract = False):
    class node -(unique,
    host,
    options='',
    logs='',
    password='',
    port='',
    protocol='',
    user='',
    config='',
    tags='',
    jumphost='')
    +(unique,
    host,
    options='',
    logs='',
    password='',
    port='',
    protocol='',
    user='',
    config='',
    tags='',
    jumphost='',
    allow_unsafe_options=None)
    @@ -1701,7 +1705,7 @@ class node: ''' - def __init__(self, unique, host, options='', logs='', password='', port='', protocol='', user='', config='', tags='', jumphost=''): + def __init__(self, unique, host, options='', logs='', password='', port='', protocol='', user='', config='', tags='', jumphost='', allow_unsafe_options=None): ''' ### Parameters: @@ -1736,14 +1740,22 @@ class node: like "os", "prompt" and "screenleght_command" - jumphost (str): Reference another node to be used as a jumphost + + - allow_unsafe_options (bool): Explicitly override safety restrictions. ''' self.config = config if config == '': self.idletime = 0 self.key = None else: - self.idletime = config.config["idletime"] - self.key = config.key + self.idletime = config.config["idletime"] if (hasattr(config, "config") and isinstance(config.config, dict) and "idletime" in config.config) else 0 + self.key = getattr(config, "key", None) + if allow_unsafe_options is not None: + self.allow_unsafe_options = bool(allow_unsafe_options) + elif config != '' and config is not None and hasattr(config, "config") and isinstance(config.config, dict): + self.allow_unsafe_options = bool(config.config.get("allow_unsafe_options", False)) + else: + self.allow_unsafe_options = False self.unique = unique attr = {"host": host, "logs": logs, "options":options, "port": port, "protocol": protocol, "user": user, "tags": tags, "jumphost": jumphost} for key in attr: @@ -1814,6 +1826,79 @@ class node: jh_dict["password"] = [jh_dict["password"]] return jh_dict + def _is_unsafe_allowed(self) -> bool: + if getattr(self, "allow_unsafe_options", False): + return True + if hasattr(self, "config") and self.config and hasattr(self.config, "config") and isinstance(self.config.config, dict): + return bool(self.config.config.get("allow_unsafe_options", False)) + return False + + def _validate_base_fields(self, check_port=True): + """Sanitize host, user, and port against argument injection and shell metacharacters.""" + host_s = str(self.host) if self.host is not None else "" + if not host_s: + raise ValueError("Host cannot be empty") + if host_s.startswith("-"): + raise ValueError(f"Host cannot start with '-': '{self.host}'") + host_bare = ( + host_s[1:-1] + if (host_s.startswith("[") and host_s.endswith("]")) + else host_s + ) + if not host_bare or host_bare.startswith("-"): + raise ValueError(f"Invalid characters in host: '{self.host}'") + if _LEGACY_SSH_UNSAFE_RE.search(host_bare): + raise ValueError(f"Invalid characters in host: '{self.host}'") + + user_s = str(self.user) if self.user is not None else "" + if user_s: + if user_s.startswith("-"): + raise ValueError(f"User cannot start with '-': '{self.user}'") + if _LEGACY_SSH_UNSAFE_RE.search(user_s): + raise ValueError(f"Invalid characters in user: '{self.user}'") + + if check_port and self.port != "" and self.port is not None: + if isinstance(self.port, (bool, float)): + raise ValueError(f"Invalid TCP SSH port '{self.port}'") + port_s = str(self.port).strip() + if port_s: + if ( + not port_s.isascii() + or not re.fullmatch(r"[0-9]+", port_s, re.ASCII) + or not (1 <= int(port_s) <= 65535) + ): + raise ValueError(f"Invalid TCP SSH port '{self.port}'") + + def _validate_options_and_safety(self): + """Validate options string for unbalanced quotes and dangerous control characters.""" + if not self.options: + return + opts_str = str(self.options).strip() + if not opts_str: + return + if not self._is_unsafe_allowed(): + if any(c in opts_str for c in ("\n", "\r", "\x00")): + raise ValueError("Options cannot contain newlines or null bytes") + try: + shlex.split(opts_str) + except ValueError as e: + raise ValueError(f"Invalid options: unbalanced quotes ({e})") from e + + def _validate_ssh_options(self): + """Sanitize SSH options against local command execution directives.""" + self._validate_options_and_safety() + if not self.options: + return + opts_str = str(self.options).strip() + if not opts_str: + return + if not self._is_unsafe_allowed(): + dangerous_directives = ("ProxyCommand", "LocalCommand", "PermitLocalCommand", "KnownHostsCommand") + pattern = r'(?:' + '|'.join(dangerous_directives) + r')' + match = re.search(pattern, opts_str, re.IGNORECASE) + if match: + raise ValueError(f"Disallowed SSH directive in options: '{match.group(0)}'") + @staticmethod def _validate_legacy_ssh_hop_fields(host, user, port): """Minimal injection guard for legacy SSH jumphost fields (preserves DOMAIN\\user, %scope, etc.).""" @@ -3040,10 +3125,13 @@ class node: @MethodHook def _generate_ssh_sftp_cmd(self, force_ssh=False, allow_reverse_tunnel_port=None): + self._validate_base_fields(check_port=True) is_from_mosh = ( self.protocol == "mosh" or getattr(self, "_orig_protocol", "") == "mosh" ) + if not is_from_mosh: + self._validate_ssh_options() proto = "ssh" if force_ssh else self.protocol cmd = proto if is_from_mosh: @@ -3134,8 +3222,9 @@ class node: if isinstance(self.tags, dict) and self.tags.get("mosh_ssh_options"): ssh_opts = str(self.tags["mosh_ssh_options"]).strip() if ssh_opts: - if re.search(r'(?:LocalCommand|ProxyCommand)', ssh_opts, re.IGNORECASE): - raise ValueError("mosh_ssh_options cannot contain LocalCommand or ProxyCommand") + if not self._is_unsafe_allowed(): + if re.search(r'(?:LocalCommand|ProxyCommand|PermitLocalCommand|KnownHostsCommand)', ssh_opts, re.IGNORECASE): + raise ValueError("mosh_ssh_options cannot contain LocalCommand or ProxyCommand") try: shlex.split(ssh_opts) except ValueError as exc: @@ -3153,8 +3242,9 @@ class node: if opts: if re.search(r'--(?:ssh|server|client)(?:=|\s|$)', opts): raise ValueError("Options cannot override --ssh, --server or --client for mosh") - if re.search(r'(?:LocalCommand|ProxyCommand)', opts, re.IGNORECASE): - raise ValueError("Options cannot contain LocalCommand or ProxyCommand") + if not self._is_unsafe_allowed(): + if re.search(r'(?:LocalCommand|ProxyCommand|PermitLocalCommand|KnownHostsCommand)', opts, re.IGNORECASE): + raise ValueError("Options cannot contain LocalCommand or ProxyCommand") try: shlex.split(opts) except ValueError as exc: @@ -3167,6 +3257,8 @@ class node: @MethodHook def _generate_telnet_cmd(self): + self._validate_base_fields(check_port=True) + self._validate_options_and_safety() cmd = f"telnet {self.host}" if self.port: cmd += f" {self.port}" @@ -3176,22 +3268,52 @@ class node: @MethodHook def _generate_kube_cmd(self): - cmd = f"kubectl exec {self.options} {self.host} -it --" + self._validate_base_fields(check_port=False) + self._validate_options_and_safety() kube_command = self.tags.get("kube_command", "/bin/bash") if isinstance(self.tags, dict) else "/bin/bash" + if not self._is_unsafe_allowed() and kube_command: + k_str = str(kube_command) + if any(c in k_str for c in ("\n", "\r", "\x00")): + raise ValueError("kube_command cannot contain newlines or null bytes") + try: + shlex.split(k_str) + except ValueError as e: + raise ValueError(f"Invalid kube_command: unbalanced quotes ({e})") from e + cmd = f"kubectl exec {self.options} {self.host} -it --" cmd += f" {kube_command}" return cmd @MethodHook def _generate_docker_cmd(self): - cmd = f"docker {self.options} exec -it {self.host}" + self._validate_base_fields(check_port=False) + self._validate_options_and_safety() docker_command = self.tags.get("docker_command", "/bin/bash") if isinstance(self.tags, dict) else "/bin/bash" + if not self._is_unsafe_allowed() and docker_command: + d_str = str(docker_command) + if any(c in d_str for c in ("\n", "\r", "\x00")): + raise ValueError("docker_command cannot contain newlines or null bytes") + try: + shlex.split(d_str) + except ValueError as e: + raise ValueError(f"Invalid docker_command: unbalanced quotes ({e})") from e + cmd = f"docker {self.options} exec -it {self.host}" cmd += f" {docker_command}" return cmd @MethodHook def _generate_ssm_cmd(self): + self._validate_base_fields(check_port=False) + self._validate_options_and_safety() region = self.tags.get("region", "") if isinstance(self.tags, dict) else "" profile = self.tags.get("profile", "") if isinstance(self.tags, dict) else "" + if not self._is_unsafe_allowed(): + for field_name, field_val in [("region", region), ("profile", profile)]: + if field_val: + f_str = str(field_val) + if f_str.startswith("-"): + raise ValueError(f"SSM tag '{field_name}' cannot start with '-': '{field_val}'") + if re.search(r'[\s\x00-\x1f\x7f;|&$`><"\']', f_str): + raise ValueError(f"Invalid characters in SSM tag '{field_name}': '{field_val}'") cmd = f"aws ssm start-session --target {self.host}" if region: cmd += f" --region {region}" @@ -3492,6 +3614,8 @@ class node: like "os", "prompt" and "screenleght_command" - jumphost (str): Reference another node to be used as a jumphost + +- allow_unsafe_options (bool): Explicitly override safety restrictions.

    Methods

    @@ -4606,11 +4730,11 @@ def test(self, commands, expected, vars = None,*, folder = None, prompt = None,

    Manages MCP SSE client connections for connpy.

    Methods

    -async def call_tool(self, full_tool_name: str, arguments: Dict[str, Any]) ‑> Any +async def call_tool(self, full_tool_name: str, arguments: dict[str, typing.Any]) ‑> Any
    Expand source code -
    async def call_tool(self, full_tool_name: str, arguments: Dict[str, Any]) -> Any:
    +
    async def call_tool(self, full_tool_name: str, arguments: dict[str, Any]) -> Any:
         """Calls an MCP tool and returns text result."""
         if not MCP_AVAILABLE:
             return "Error: MCP SDK is not installed."
     
         if "__" not in full_tool_name:
             return f"Error: Tool {full_tool_name} is not a valid MCP tool."
    -        
    -    clean_name = full_tool_name[4:] if full_tool_name.startswith("mcp_") else full_tool_name
    +
    +    clean_name = full_tool_name.removeprefix("mcp_")
         server_name, tool_name = clean_name.split("__", 1)
    -    
    +
         if server_name not in self.sessions:
             return f"Error: MCP server {server_name} is not connected."
    -        
    +
         session = self.sessions[server_name]["session"]
         try:
             result = await asyncio.wait_for(session.call_tool(tool_name, arguments), timeout=60.0)
             text_outputs = [content.text for content in result.content if hasattr(content, "text")]
             return "\n".join(text_outputs) if text_outputs else str(result)
    -    except Exception as e:
    -        return f"Error calling tool {tool_name} on {server_name}: {str(e)}"
    + except Exception as e: # noqa: BLE001 + return f"Error calling tool {tool_name} on {server_name}: {e!s}"

    Calls an MCP tool and returns text result.

    -async def get_tools_for_llm(self, os_filter: str | None = None) ‑> List[Dict[str, Any]] +async def get_tools_for_llm(self, os_filter: str | None = None) ‑> list[dict[str, typing.Any]]
    Expand source code -
    async def get_tools_for_llm(self, os_filter: Optional[str] = None) -> List[Dict[str, Any]]:
    -    """
    -    Fetches tools from enabled MCP servers that match the OS filter.
    -    """
    +
    async def get_tools_for_llm(self, os_filter: str | None = None) -> list[dict[str, Any]]:
    +    """Fetches tools from enabled MCP servers that match the OS filter."""
         if not MCP_AVAILABLE:
             return []
     
    @@ -267,35 +321,59 @@ el.replaceWith(d);
                 mcp_config = self.config.get_effective_setting("ai", {}).get("mcp_servers", {})
             else:
                 mcp_config = self.config.config.get("ai", {}).get("mcp_servers", {}) if hasattr(self.config, "config") else {}
    -    except Exception:
    +    except Exception:  # noqa: BLE001
             return []
    -    
    +
    +    if not isinstance(mcp_config, dict):
    +        mcp_config = {}
    +
    +    # Invalidate cache and reconnect if server configuration changed or server was removed
    +    current_names = set(mcp_config.keys())
    +    for old_name in list(self._server_configs.keys()):
    +        if old_name not in current_names:
    +            self.tool_cache.pop(old_name, None)
    +            old_data = self.sessions.pop(old_name, None)
    +            if old_data and old_data.get("stack"):
    +                with suppress(Exception):
    +                    await old_data["stack"].aclose()
    +            self._server_configs.pop(old_name, None)
    +
    +    for name, cfg in mcp_config.items():
    +        cached_cfg = self._server_configs.get(name)
    +        if cached_cfg is not None and cached_cfg != cfg:
    +            self.tool_cache.pop(name, None)
    +            old_data = self.sessions.pop(name, None)
    +            if old_data and old_data.get("stack"):
    +                with suppress(Exception):
    +                    await old_data["stack"].aclose()
    +        self._server_configs[name] = dict(cfg) if isinstance(cfg, dict) else cfg
    +
         async def _fetch(name, cfg):
    -        if not cfg.get("enabled", True): return []
    -        
    +        if not isinstance(cfg, dict) or not cfg.get("enabled", True):
    +            return []
    +
             # Filter by OS if specified in config (primarily used for copilot strict matching)
             auto_os = cfg.get("auto_load_on_os")
             if os_filter is not None and auto_os and os_filter.lower() != auto_os.lower():
                 return []
     
    -        try:
    +        with suppress(Exception):
                 session = await self._ensure_connected(name, cfg)
                 if session:
    -                if name in self.tool_cache: return self.tool_cache[name]
    +                if name in self.tool_cache:
    +                    return self.tool_cache[name]
                     llm_tools = await self._fetch_tools_as_openai(name, session)
                     self.tool_cache[name] = llm_tools
                     return llm_tools
    -        except Exception:
    -            pass
             return []
     
    -    tasks = [ _fetch(name, cfg) for name, cfg in mcp_config.items() ]
    -    
    +    tasks = [_fetch(name, cfg) for name, cfg in mcp_config.items()]
    +
         if tasks:
             results = await asyncio.gather(*tasks)
             for tools in results:
                 all_llm_tools.extend(tools)
    -            
    +
         return all_llm_tools

    Fetches tools from enabled MCP servers that match the OS filter.

    @@ -309,14 +387,25 @@ el.replaceWith(d); Expand source code
    async def shutdown(self):
    -    """Close all SSE connections."""
    -    for name, data in self.sessions.items():
    +    """Close all SSE connections and clean up resources."""
    +    for data in list(self.sessions.values()):
             stack = data.get("stack")
             if stack:
    -            await stack.aclose()
    -    self.sessions = {}
    + with suppress(Exception): + await stack.aclose() + self.sessions.clear() + self.tool_cache.clear() + self._server_configs.clear() + for fut in list(self._connecting.values()): + if not fut.done(): + fut.cancel() + self._connecting.clear() + with self._lock: + if hasattr(self, "_scope_key") and self._scope_key in self._instances: + del self._instances[self._scope_key] + self._initialized = False
    -

    Close all SSE connections.

    +

    Close all SSE connections and clean up resources.

    diff --git a/docs/connpy/mcp_server.html b/docs/connpy/mcp_server.html new file mode 100644 index 0000000..218f8e7 --- /dev/null +++ b/docs/connpy/mcp_server.html @@ -0,0 +1,1191 @@ + + + + + + +connpy.mcp_server API documentation + + + + + + + + + + + +
    +
    +
    +

    Module connpy.mcp_server

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class ConnpyMCPServer +(config=None, services=None, trust: bool = False) +
    +
    +
    + +Expand source code + +
    class ConnpyMCPServer:
    +    """Native Model Context Protocol (MCP) Server for connpy."""
    +
    +    SAFE_COMMANDS: ClassVar[list[str]] = [
    +        r"^show\s+",
    +        r"^ls\s*",
    +        r"^cat\s+",
    +        r"^ip\s+",
    +        r"^pwd$",
    +        r"^hostname$",
    +        r"^uname",
    +        r"^df\s*",
    +        r"^free\s*",
    +        r"^ps\s*",
    +        r"^ping\s+",
    +        r"^traceroute\s+",
    +        r"^whois\s+",
    +        r"^kubectl\s+(get|describe|version|logs|top|explain|cluster-info|api-resources|api-versions)\s+",
    +        r"^systemctl\s+status\s+",
    +        r"^journalctl\s+",
    +    ]
    +
    +    def __init__(self, config=None, services=None, trust: bool = False):
    +        self.config = config
    +        self.services = services
    +        if self.services is None:
    +            if self.config is not None:
    +                from .services.provider import ServiceProvider
    +
    +                self.services = ServiceProvider(self.config)
    +        elif self.config is None and hasattr(self.services, "config"):
    +            self.config = self.services.config
    +
    +        self.trust = bool(trust)
    +
    +        # Build list of safe commands (SAFE_COMMANDS + trusted_commands from config)
    +        aiconfig = {}
    +        if self.config:
    +            if hasattr(self.config, "get_effective_setting"):
    +                aiconfig = self.config.get_effective_setting("ai", {})
    +            elif hasattr(self.config, "config") and isinstance(self.config.config, dict):
    +                aiconfig = self.config.config.get("ai", {})
    +
    +        custom_trusted = aiconfig.get("trusted_commands", []) if isinstance(aiconfig, dict) else []
    +        if isinstance(custom_trusted, str):
    +            custom_trusted = [c.strip() for c in custom_trusted.split(",") if c.strip()]
    +        self.safe_commands = list(self.SAFE_COMMANDS) + (
    +            custom_trusted if isinstance(custom_trusted, list) else []
    +        )
    +
    +        # Initialize MCP Server
    +        if MCPServer is not None:
    +            self.server = MCPServer("connpy")
    +            self._register_tools()
    +        else:
    +            self.server = None
    +
    +    def _register_tools(self):
    +        """Register the 3 tiers of MCP tools."""
    +        if not self.server:
    +            return
    +
    +        # Level 1 Tools (Read-Only)
    +        self.server.tool()(self.list_nodes)
    +        self.server.tool()(self.list_folders)
    +        self.server.tool()(self.get_node_info)
    +        self.server.tool()(self.list_profiles)
    +        self.server.tool()(self.get_active_context)
    +
    +        # Level 2 Tools (Execution, Testing, Playbooks)
    +        self.server.tool()(self.run_commands)
    +        self.server.tool()(self.test_commands)
    +        self.server.tool()(self.validate_playbook)
    +        self.server.tool()(self.run_playbook)
    +
    +        # Level 3 Tools (CRUD - Requires trust=True)
    +        self.server.tool()(self.add_node)
    +        self.server.tool()(self.update_node)
    +        self.server.tool()(self.delete_node)
    +
    +    # -------------------------------------------------------------------------
    +    # Security Validation
    +    # -------------------------------------------------------------------------
    +
    +    def is_safe_command(self, cmd: str) -> bool:
    +        """Validate if a command is considered safe under current trust settings.
    +
    +        - If trust is True, all commands are allowed.
    +        - Block chaining/injection characters: ';', '&&', '||', '|', '`', '$(', '>', '<', '\\n', '\\r', '&'.
    +        - Validates against self.safe_commands (SAFE_COMMANDS + trusted_commands).
    +        """
    +        if self.trust:
    +            return True
    +
    +        if not isinstance(cmd, str):
    +            cmd = str(cmd)
    +
    +        # Check for shell chaining and redirection injection tokens
    +        injection_tokens = [";", "&&", "||", "|", "`", "$(", ">", "<", "\n", "\r", "&"]
    +        if any(tok in cmd for tok in injection_tokens):
    +            return False
    +
    +        clean_cmd = cmd.strip()
    +        return any(re.match(pattern, clean_cmd, re.IGNORECASE) for pattern in self.safe_commands)
    +
    +    def _mask_secrets(self, val: Any) -> Any:
    +        """Recursively mask passwords, passphrases, secrets, and auth tokens with '***'."""
    +        if isinstance(val, dict):
    +            masked = {}
    +            for k, v in val.items():
    +                k_lower = str(k).lower()
    +                if any(sec in k_lower for sec in ["password", "passphrase", "secret", "token"]):
    +                    masked[k] = "***"
    +                elif isinstance(v, (dict, list)):
    +                    masked[k] = self._mask_secrets(v)
    +                else:
    +                    masked[k] = v
    +            return masked
    +        if isinstance(val, list):
    +            return [self._mask_secrets(item) for item in val]
    +        return val
    +
    +    # -------------------------------------------------------------------------
    +    # Level 1: Read-Only Inventory and Context Tools
    +    # -------------------------------------------------------------------------
    +
    +    def list_nodes(self, filter_pattern: str = "", format_str: str = "") -> list[str]:
    +        """List inventory nodes, optionally filtered by regex pattern and formatted."""
    +        if not self.services or not hasattr(self.services, "nodes"):
    +            return []
    +        f = filter_pattern if filter_pattern else None
    +        fmt = format_str if format_str else None
    +        return self.services.nodes.list_nodes(filter_str=f, format_str=fmt)
    +
    +    def list_folders(self, filter_pattern: str = "") -> list[str]:
    +        """List inventory folders, optionally filtered by regex pattern."""
    +        if not self.services or not hasattr(self.services, "nodes"):
    +            return []
    +        f = filter_pattern if filter_pattern else None
    +        return self.services.nodes.list_folders(filter_str=f)
    +
    +    def get_node_info(self, node_name: str) -> dict:
    +        """Get full configuration metadata for a specific node.
    +
    +        Passwords, passphrases, and secrets are ALWAYS masked with '***'.
    +        """
    +        if not self.services or not hasattr(self.services, "nodes"):
    +            return {"error": "Node service unavailable."}
    +        try:
    +            details = self.services.nodes.get_node_details(node_name)
    +            if hasattr(self.services, "profiles"):
    +                with contextlib.suppress(Exception):
    +                    details = self.services.profiles.resolve_node_data(details)
    +            return self._mask_secrets(details)
    +        except Exception as e:  # noqa: BLE001
    +            return {"error": f"Node '{node_name}' not found: {e}"}
    +
    +    def list_profiles(self, filter_pattern: str = "") -> list[str]:
    +        """List all available node connection profiles."""
    +        if not self.services or not hasattr(self.services, "profiles"):
    +            return []
    +        f = filter_pattern if filter_pattern else None
    +        return self.services.profiles.list_profiles(filter_str=f)
    +
    +    def get_active_context(self) -> dict:
    +        """Get the currently active context name and its matching regex patterns."""
    +        if not self.services or not hasattr(self.services, "context"):
    +            return {"context": "all", "patterns": [".*"]}
    +        try:
    +            ctx_name = self.services.context.current_context
    +            patterns = [p.pattern for p in self.services.context.get_active_regexes()]
    +            return {"context": ctx_name, "patterns": patterns}
    +        except Exception as e:  # noqa: BLE001
    +            return {"context": "unknown", "error": str(e)}
    +
    +    # -------------------------------------------------------------------------
    +    # Level 2: Execution, Testing, and Playbooks Tools
    +    # -------------------------------------------------------------------------
    +
    +    def run_commands(
    +        self,
    +        nodes_filter: str,
    +        commands: list[str] | str,
    +        parallel: bool = True,
    +        timeout: int = 30,
    +    ) -> dict:
    +        """Execute commands on nodes matching the filter pattern.
    +
    +        Unsafe commands are blocked unless trust mode is enabled.
    +        """
    +        if not self.services or not hasattr(self.services, "execution"):
    +            return {"success": False, "error": "Execution service unavailable."}
    +
    +        # Normalize commands list
    +        if isinstance(commands, str):
    +            try:
    +                import json
    +
    +                parsed = json.loads(commands)
    +                commands = parsed if isinstance(parsed, list) else [commands]
    +            except Exception:  # noqa: BLE001
    +                commands = [c.strip() for c in commands.splitlines() if c.strip()]
    +        elif not isinstance(commands, list):
    +            commands = [str(commands)]
    +
    +        # Check safety
    +        if not self.trust:
    +            unsafe = [cmd for cmd in commands if not self.is_safe_command(cmd)]
    +            if unsafe:
    +                return {
    +                    "success": False,
    +                    "error": f"Permission denied: unsafe commands detected: {unsafe}. Requires trust=True.",
    +                }
    +
    +        par_count = 10 if parallel is True else (parallel if isinstance(parallel, int) else 1)
    +        try:
    +            results = self.services.execution.run_commands(
    +                nodes_filter=nodes_filter,
    +                commands=commands,
    +                parallel=par_count,
    +                timeout=timeout,
    +            )
    +            return {"success": True, "results": results}
    +        except Exception as e:  # noqa: BLE001
    +            return {"success": False, "error": str(e)}
    +
    +    def test_commands(
    +        self,
    +        nodes_filter: str,
    +        commands: list[str] | str,
    +        expected: list[str] | str = "",
    +        parallel: bool = True,
    +        timeout: int = 30,
    +    ) -> dict:
    +        """Execute commands and assert expected patterns on nodes matching the filter."""
    +        if not self.services or not hasattr(self.services, "execution"):
    +            return {"success": False, "error": "Execution service unavailable."}
    +
    +        # Normalize commands
    +        if isinstance(commands, str):
    +            try:
    +                import json
    +
    +                parsed = json.loads(commands)
    +                commands = parsed if isinstance(parsed, list) else [commands]
    +            except Exception:  # noqa: BLE001
    +                commands = [c.strip() for c in commands.splitlines() if c.strip()]
    +        elif not isinstance(commands, list):
    +            commands = [str(commands)]
    +
    +        # Normalize expected
    +        if isinstance(expected, str):
    +            try:
    +                import json
    +
    +                parsed = json.loads(expected)
    +                expected = parsed if isinstance(parsed, list) else ([expected] if expected else [])
    +            except Exception:  # noqa: BLE001
    +                expected = [expected] if expected else []
    +        elif not isinstance(expected, list):
    +            expected = [str(expected)] if expected else []
    +
    +        # Check safety
    +        if not self.trust:
    +            unsafe = [cmd for cmd in commands if not self.is_safe_command(cmd)]
    +            if unsafe:
    +                return {
    +                    "success": False,
    +                    "error": f"Permission denied: unsafe commands detected: {unsafe}. Requires trust=True.",
    +                }
    +
    +        par_count = 10 if parallel is True else (parallel if isinstance(parallel, int) else 1)
    +        try:
    +            results = self.services.execution.test_commands(
    +                nodes_filter=nodes_filter,
    +                commands=commands,
    +                expected=expected,
    +                parallel=par_count,
    +                timeout=timeout,
    +            )
    +            return {"success": True, "results": results}
    +        except Exception as e:  # noqa: BLE001
    +            return {"success": False, "error": str(e)}
    +
    +    def validate_playbook(self, playbook_yaml: str) -> dict:
    +        """Validate the syntax, schema, and tasks of a Connpy YAML playbook."""
    +        try:
    +            data = yaml.safe_load(playbook_yaml)
    +        except Exception as e:  # noqa: BLE001
    +            return {"valid": False, "error": f"YAML Syntax Error: {e}"}
    +
    +        if not isinstance(data, dict):
    +            return {"valid": False, "error": "Playbook must be a YAML dictionary."}
    +
    +        if "tasks" not in data:
    +            return {"valid": False, "error": "Playbook missing mandatory root 'tasks' key."}
    +
    +        tasks = data["tasks"]
    +        if not isinstance(tasks, list):
    +            return {"valid": False, "error": "'tasks' must be a list of tasks."}
    +
    +        for idx, task in enumerate(tasks):
    +            if not isinstance(task, dict):
    +                return {"valid": False, "error": f"Task index {idx} must be a dictionary."}
    +
    +            name = task.get("name", f"Task {idx}")
    +            mandatory = ["name", "action", "nodes", "commands", "output"]
    +            missing = [f for f in mandatory if f not in task]
    +            if missing:
    +                return {
    +                    "valid": False,
    +                    "error": f"Task '{name}' (index {idx}) is missing mandatory fields: {missing}",
    +                }
    +
    +            nodes = task["nodes"]
    +            if not isinstance(nodes, (str, list)):
    +                return {
    +                    "valid": False,
    +                    "error": f"Task '{name}' (index {idx}) 'nodes' must be a string or list of strings.",
    +                }
    +
    +            if isinstance(nodes, list):
    +                for n_idx, node_item in enumerate(nodes):
    +                    if not isinstance(node_item, str):
    +                        return {
    +                            "valid": False,
    +                            "error": f"Task '{name}' (index {idx}) 'nodes' contains non-string at index {n_idx}: {node_item}",
    +                        }
    +
    +            action = task["action"]
    +            if action not in ["run", "test"]:
    +                return {
    +                    "valid": False,
    +                    "error": f"Task '{name}' (index {idx}) invalid action '{action}'. Choices: 'run', 'test'.",
    +                }
    +
    +            if action == "test" and "expected" not in task:
    +                return {
    +                    "valid": False,
    +                    "error": f"Task '{name}' (index {idx}) action 'test' requires 'expected' key.",
    +                }
    +
    +            output = task["output"]
    +            if output not in [None, "stdout", "null"] and not str(output).startswith("/"):
    +                return {
    +                    "valid": False,
    +                    "error": f"Task '{name}' (index {idx}) output '{output}' must be 'stdout', 'null' or an absolute path.",
    +                }
    +
    +        return {"valid": True, "message": "Playbook schema and syntax is valid."}
    +
    +    def run_playbook(self, playbook_yaml: str) -> dict:
    +        """Validate and execute a playbook, verifying commands beforehand if trust=False."""
    +        val = self.validate_playbook(playbook_yaml)
    +        if not val.get("valid"):
    +            return {"success": False, "error": f"Invalid playbook: {val.get('error')}"}
    +
    +        data = yaml.safe_load(playbook_yaml)
    +        tasks = data.get("tasks", [])
    +
    +        # Pre-verify commands if not trusted
    +        if not self.trust:
    +            for idx, task in enumerate(tasks):
    +                name = task.get("name", f"Task {idx}")
    +                commands = task.get("commands", [])
    +                if isinstance(commands, str):
    +                    commands = [commands]
    +                unsafe = [cmd for cmd in commands if not self.is_safe_command(cmd)]
    +                if unsafe:
    +                    return {
    +                        "success": False,
    +                        "error": f"Permission denied: unsafe commands detected in task '{name}': {unsafe}. Requires trust=True.",
    +                    }
    +
    +        # Execute tasks
    +        results = {}
    +        for idx, task in enumerate(tasks):
    +            name = task.get("name", f"task_{idx}")
    +            action = task.get("action")
    +            nodes = task.get("nodes")
    +            commands = task.get("commands")
    +            if isinstance(commands, str):
    +                commands = [commands]
    +
    +            try:
    +                if action == "run":
    +                    res = self.services.execution.run_commands(nodes_filter=nodes, commands=commands)
    +                elif action == "test":
    +                    expected = task.get("expected", [])
    +                    if isinstance(expected, str):
    +                        expected = [expected]
    +                    res = self.services.execution.test_commands(
    +                        nodes_filter=nodes, commands=commands, expected=expected
    +                    )
    +                else:
    +                    res = f"Unsupported action: {action}"
    +                results[name] = res
    +            except Exception as e:  # noqa: BLE001
    +                return {
    +                    "success": False,
    +                    "error": f"Execution failed at task '{name}': {e}",
    +                    "partial_results": results,
    +                }
    +
    +        return {"success": True, "results": results}
    +
    +    # -------------------------------------------------------------------------
    +    # Level 3: Inventory Mutation Tools (CRUD - Requires trust=True)
    +    # -------------------------------------------------------------------------
    +
    +    def add_node(
    +        self, unique_id: str, data: dict | None = None, is_folder: bool = False, **kwargs
    +    ) -> dict:
    +        """Add a new node or folder to the inventory (requires trust=True)."""
    +        if not self.trust:
    +            return {
    +                "success": False,
    +                "error": "Permission denied: CRUD operations require trust mode (--trust).",
    +            }
    +
    +        if not self.services or not hasattr(self.services, "nodes"):
    +            return {"success": False, "error": "Node service unavailable."}
    +
    +        node_data = (data or {}).copy()
    +        node_data.update(kwargs)
    +
    +        try:
    +            self.services.nodes.add_node(unique_id, node_data, is_folder=is_folder)
    +            return {
    +                "success": True,
    +                "message": f"{'Folder' if is_folder else 'Node'} '{unique_id}' created successfully.",
    +            }
    +        except Exception as e:  # noqa: BLE001
    +            return {"success": False, "error": str(e)}
    +
    +    def update_node(self, unique_id: str, updates: dict | None = None, **kwargs) -> dict:
    +        """Update an existing node configuration (requires trust=True)."""
    +        if not self.trust:
    +            return {
    +                "success": False,
    +                "error": "Permission denied: CRUD operations require trust mode (--trust).",
    +            }
    +
    +        if not self.services or not hasattr(self.services, "nodes"):
    +            return {"success": False, "error": "Node service unavailable."}
    +
    +        node_updates = (updates or {}).copy()
    +        node_updates.update(kwargs)
    +
    +        try:
    +            self.services.nodes.update_node(unique_id, node_updates)
    +            return {"success": True, "message": f"Node '{unique_id}' updated successfully."}
    +        except Exception as e:  # noqa: BLE001
    +            return {"success": False, "error": str(e)}
    +
    +    def delete_node(self, unique_id: str, is_folder: bool = False) -> dict:
    +        """Delete a node or folder from the inventory (requires trust=True)."""
    +        if not self.trust:
    +            return {
    +                "success": False,
    +                "error": "Permission denied: CRUD operations require trust mode (--trust).",
    +            }
    +
    +        if not self.services or not hasattr(self.services, "nodes"):
    +            return {"success": False, "error": "Node service unavailable."}
    +
    +        try:
    +            self.services.nodes.delete_node(unique_id, is_folder=is_folder)
    +            return {
    +                "success": True,
    +                "message": f"{'Folder' if is_folder else 'Node'} '{unique_id}' deleted successfully.",
    +            }
    +        except Exception as e:  # noqa: BLE001
    +            return {"success": False, "error": str(e)}
    +
    +    # -------------------------------------------------------------------------
    +    # Server Execution and Async Helper
    +    # -------------------------------------------------------------------------
    +
    +    async def call_tool(self, name: str, arguments: dict | None = None) -> Any:
    +        """Call an MCP tool asynchronously via the underlying MCP server."""
    +        if not self.server:
    +            raise RuntimeError("MCP SDK is not initialized.")
    +        return await self.server.call_tool(name, arguments or {})
    +
    +    def run(self, transport: str = "stdio", host: str = "127.0.0.1", port: int = 8000, **kwargs):
    +        """Run the MCP server using either stdio or sse transport."""
    +        if not self.server:
    +            raise RuntimeError("MCP server cannot start: 'mcp' package is not installed.")
    +
    +        if transport == "stdio":
    +            # Redirect logs and printer outputs to sys.stderr for JSON-RPC
    +            with contextlib.suppress(Exception):
    +                from . import printer
    +
    +                printer.set_thread_stream(sys.stderr)
    +
    +            for handler in logging.root.handlers:
    +                if hasattr(handler, "stream") and handler.stream == sys.stdout:
    +                    handler.stream = sys.stderr
    +            logging.basicConfig(stream=sys.stderr, level=logging.INFO)
    +
    +            return self.server.run(transport="stdio", **kwargs)
    +
    +        if transport == "sse":
    +            if hasattr(self.server, "settings"):
    +                if hasattr(self.server.settings, "host"):
    +                    self.server.settings.host = host
    +                if hasattr(self.server.settings, "port"):
    +                    self.server.settings.port = port
    +            try:
    +                return self.server.run(transport="sse", host=host, port=port, **kwargs)
    +            except TypeError:
    +                return self.server.run(transport="sse", **kwargs)
    +
    +        msg = f"Unknown transport: {transport}. Supported transports: 'stdio', 'sse'"
    +        raise ValueError(msg)
    +
    +

    Native Model Context Protocol (MCP) Server for connpy.

    +

    Class variables

    +
    +
    var SAFE_COMMANDS : ClassVar[list[str]]
    +
    +
    +
    +
    +

    Methods

    +
    +
    +def add_node(self, unique_id: str, data: dict | None = None, is_folder: bool = False, **kwargs) ‑> dict +
    +
    +
    + +Expand source code + +
    def add_node(
    +    self, unique_id: str, data: dict | None = None, is_folder: bool = False, **kwargs
    +) -> dict:
    +    """Add a new node or folder to the inventory (requires trust=True)."""
    +    if not self.trust:
    +        return {
    +            "success": False,
    +            "error": "Permission denied: CRUD operations require trust mode (--trust).",
    +        }
    +
    +    if not self.services or not hasattr(self.services, "nodes"):
    +        return {"success": False, "error": "Node service unavailable."}
    +
    +    node_data = (data or {}).copy()
    +    node_data.update(kwargs)
    +
    +    try:
    +        self.services.nodes.add_node(unique_id, node_data, is_folder=is_folder)
    +        return {
    +            "success": True,
    +            "message": f"{'Folder' if is_folder else 'Node'} '{unique_id}' created successfully.",
    +        }
    +    except Exception as e:  # noqa: BLE001
    +        return {"success": False, "error": str(e)}
    +
    +

    Add a new node or folder to the inventory (requires trust=True).

    +
    +
    +async def call_tool(self, name: str, arguments: dict | None = None) ‑> Any +
    +
    +
    + +Expand source code + +
    async def call_tool(self, name: str, arguments: dict | None = None) -> Any:
    +    """Call an MCP tool asynchronously via the underlying MCP server."""
    +    if not self.server:
    +        raise RuntimeError("MCP SDK is not initialized.")
    +    return await self.server.call_tool(name, arguments or {})
    +
    +

    Call an MCP tool asynchronously via the underlying MCP server.

    +
    +
    +def delete_node(self, unique_id: str, is_folder: bool = False) ‑> dict +
    +
    +
    + +Expand source code + +
    def delete_node(self, unique_id: str, is_folder: bool = False) -> dict:
    +    """Delete a node or folder from the inventory (requires trust=True)."""
    +    if not self.trust:
    +        return {
    +            "success": False,
    +            "error": "Permission denied: CRUD operations require trust mode (--trust).",
    +        }
    +
    +    if not self.services or not hasattr(self.services, "nodes"):
    +        return {"success": False, "error": "Node service unavailable."}
    +
    +    try:
    +        self.services.nodes.delete_node(unique_id, is_folder=is_folder)
    +        return {
    +            "success": True,
    +            "message": f"{'Folder' if is_folder else 'Node'} '{unique_id}' deleted successfully.",
    +        }
    +    except Exception as e:  # noqa: BLE001
    +        return {"success": False, "error": str(e)}
    +
    +

    Delete a node or folder from the inventory (requires trust=True).

    +
    +
    +def get_active_context(self) ‑> dict +
    +
    +
    + +Expand source code + +
    def get_active_context(self) -> dict:
    +    """Get the currently active context name and its matching regex patterns."""
    +    if not self.services or not hasattr(self.services, "context"):
    +        return {"context": "all", "patterns": [".*"]}
    +    try:
    +        ctx_name = self.services.context.current_context
    +        patterns = [p.pattern for p in self.services.context.get_active_regexes()]
    +        return {"context": ctx_name, "patterns": patterns}
    +    except Exception as e:  # noqa: BLE001
    +        return {"context": "unknown", "error": str(e)}
    +
    +

    Get the currently active context name and its matching regex patterns.

    +
    +
    +def get_node_info(self, node_name: str) ‑> dict +
    +
    +
    + +Expand source code + +
    def get_node_info(self, node_name: str) -> dict:
    +    """Get full configuration metadata for a specific node.
    +
    +    Passwords, passphrases, and secrets are ALWAYS masked with '***'.
    +    """
    +    if not self.services or not hasattr(self.services, "nodes"):
    +        return {"error": "Node service unavailable."}
    +    try:
    +        details = self.services.nodes.get_node_details(node_name)
    +        if hasattr(self.services, "profiles"):
    +            with contextlib.suppress(Exception):
    +                details = self.services.profiles.resolve_node_data(details)
    +        return self._mask_secrets(details)
    +    except Exception as e:  # noqa: BLE001
    +        return {"error": f"Node '{node_name}' not found: {e}"}
    +
    +

    Get full configuration metadata for a specific node.

    +

    Passwords, passphrases, and secrets are ALWAYS masked with '***'.

    +
    +
    +def is_safe_command(self, cmd: str) ‑> bool +
    +
    +
    + +Expand source code + +
    def is_safe_command(self, cmd: str) -> bool:
    +    """Validate if a command is considered safe under current trust settings.
    +
    +    - If trust is True, all commands are allowed.
    +    - Block chaining/injection characters: ';', '&&', '||', '|', '`', '$(', '>', '<', '\\n', '\\r', '&'.
    +    - Validates against self.safe_commands (SAFE_COMMANDS + trusted_commands).
    +    """
    +    if self.trust:
    +        return True
    +
    +    if not isinstance(cmd, str):
    +        cmd = str(cmd)
    +
    +    # Check for shell chaining and redirection injection tokens
    +    injection_tokens = [";", "&&", "||", "|", "`", "$(", ">", "<", "\n", "\r", "&"]
    +    if any(tok in cmd for tok in injection_tokens):
    +        return False
    +
    +    clean_cmd = cmd.strip()
    +    return any(re.match(pattern, clean_cmd, re.IGNORECASE) for pattern in self.safe_commands)
    +
    +

    Validate if a command is considered safe under current trust settings.

    +
      +
    • If trust is True, all commands are allowed.
    • +
    • Block chaining/injection characters: ';', '&&', '||', '|', '`', '$(', '>', '<', '\n', '\r', '&'.
    • +
    • Validates against self.safe_commands (SAFE_COMMANDS + trusted_commands).
    • +
    +
    +
    +def list_folders(self, filter_pattern: str = '') ‑> list[str] +
    +
    +
    + +Expand source code + +
    def list_folders(self, filter_pattern: str = "") -> list[str]:
    +    """List inventory folders, optionally filtered by regex pattern."""
    +    if not self.services or not hasattr(self.services, "nodes"):
    +        return []
    +    f = filter_pattern if filter_pattern else None
    +    return self.services.nodes.list_folders(filter_str=f)
    +
    +

    List inventory folders, optionally filtered by regex pattern.

    +
    +
    +def list_nodes(self, filter_pattern: str = '', format_str: str = '') ‑> list[str] +
    +
    +
    + +Expand source code + +
    def list_nodes(self, filter_pattern: str = "", format_str: str = "") -> list[str]:
    +    """List inventory nodes, optionally filtered by regex pattern and formatted."""
    +    if not self.services or not hasattr(self.services, "nodes"):
    +        return []
    +    f = filter_pattern if filter_pattern else None
    +    fmt = format_str if format_str else None
    +    return self.services.nodes.list_nodes(filter_str=f, format_str=fmt)
    +
    +

    List inventory nodes, optionally filtered by regex pattern and formatted.

    +
    +
    +def list_profiles(self, filter_pattern: str = '') ‑> list[str] +
    +
    +
    + +Expand source code + +
    def list_profiles(self, filter_pattern: str = "") -> list[str]:
    +    """List all available node connection profiles."""
    +    if not self.services or not hasattr(self.services, "profiles"):
    +        return []
    +    f = filter_pattern if filter_pattern else None
    +    return self.services.profiles.list_profiles(filter_str=f)
    +
    +

    List all available node connection profiles.

    +
    +
    +def run(self, transport: str = 'stdio', host: str = '127.0.0.1', port: int = 8000, **kwargs) +
    +
    +
    + +Expand source code + +
    def run(self, transport: str = "stdio", host: str = "127.0.0.1", port: int = 8000, **kwargs):
    +    """Run the MCP server using either stdio or sse transport."""
    +    if not self.server:
    +        raise RuntimeError("MCP server cannot start: 'mcp' package is not installed.")
    +
    +    if transport == "stdio":
    +        # Redirect logs and printer outputs to sys.stderr for JSON-RPC
    +        with contextlib.suppress(Exception):
    +            from . import printer
    +
    +            printer.set_thread_stream(sys.stderr)
    +
    +        for handler in logging.root.handlers:
    +            if hasattr(handler, "stream") and handler.stream == sys.stdout:
    +                handler.stream = sys.stderr
    +        logging.basicConfig(stream=sys.stderr, level=logging.INFO)
    +
    +        return self.server.run(transport="stdio", **kwargs)
    +
    +    if transport == "sse":
    +        if hasattr(self.server, "settings"):
    +            if hasattr(self.server.settings, "host"):
    +                self.server.settings.host = host
    +            if hasattr(self.server.settings, "port"):
    +                self.server.settings.port = port
    +        try:
    +            return self.server.run(transport="sse", host=host, port=port, **kwargs)
    +        except TypeError:
    +            return self.server.run(transport="sse", **kwargs)
    +
    +    msg = f"Unknown transport: {transport}. Supported transports: 'stdio', 'sse'"
    +    raise ValueError(msg)
    +
    +

    Run the MCP server using either stdio or sse transport.

    +
    +
    +def run_commands(self,
    nodes_filter: str,
    commands: list[str] | str,
    parallel: bool = True,
    timeout: int = 30) ‑> dict
    +
    +
    +
    + +Expand source code + +
    def run_commands(
    +    self,
    +    nodes_filter: str,
    +    commands: list[str] | str,
    +    parallel: bool = True,
    +    timeout: int = 30,
    +) -> dict:
    +    """Execute commands on nodes matching the filter pattern.
    +
    +    Unsafe commands are blocked unless trust mode is enabled.
    +    """
    +    if not self.services or not hasattr(self.services, "execution"):
    +        return {"success": False, "error": "Execution service unavailable."}
    +
    +    # Normalize commands list
    +    if isinstance(commands, str):
    +        try:
    +            import json
    +
    +            parsed = json.loads(commands)
    +            commands = parsed if isinstance(parsed, list) else [commands]
    +        except Exception:  # noqa: BLE001
    +            commands = [c.strip() for c in commands.splitlines() if c.strip()]
    +    elif not isinstance(commands, list):
    +        commands = [str(commands)]
    +
    +    # Check safety
    +    if not self.trust:
    +        unsafe = [cmd for cmd in commands if not self.is_safe_command(cmd)]
    +        if unsafe:
    +            return {
    +                "success": False,
    +                "error": f"Permission denied: unsafe commands detected: {unsafe}. Requires trust=True.",
    +            }
    +
    +    par_count = 10 if parallel is True else (parallel if isinstance(parallel, int) else 1)
    +    try:
    +        results = self.services.execution.run_commands(
    +            nodes_filter=nodes_filter,
    +            commands=commands,
    +            parallel=par_count,
    +            timeout=timeout,
    +        )
    +        return {"success": True, "results": results}
    +    except Exception as e:  # noqa: BLE001
    +        return {"success": False, "error": str(e)}
    +
    +

    Execute commands on nodes matching the filter pattern.

    +

    Unsafe commands are blocked unless trust mode is enabled.

    +
    +
    +def run_playbook(self, playbook_yaml: str) ‑> dict +
    +
    +
    + +Expand source code + +
    def run_playbook(self, playbook_yaml: str) -> dict:
    +    """Validate and execute a playbook, verifying commands beforehand if trust=False."""
    +    val = self.validate_playbook(playbook_yaml)
    +    if not val.get("valid"):
    +        return {"success": False, "error": f"Invalid playbook: {val.get('error')}"}
    +
    +    data = yaml.safe_load(playbook_yaml)
    +    tasks = data.get("tasks", [])
    +
    +    # Pre-verify commands if not trusted
    +    if not self.trust:
    +        for idx, task in enumerate(tasks):
    +            name = task.get("name", f"Task {idx}")
    +            commands = task.get("commands", [])
    +            if isinstance(commands, str):
    +                commands = [commands]
    +            unsafe = [cmd for cmd in commands if not self.is_safe_command(cmd)]
    +            if unsafe:
    +                return {
    +                    "success": False,
    +                    "error": f"Permission denied: unsafe commands detected in task '{name}': {unsafe}. Requires trust=True.",
    +                }
    +
    +    # Execute tasks
    +    results = {}
    +    for idx, task in enumerate(tasks):
    +        name = task.get("name", f"task_{idx}")
    +        action = task.get("action")
    +        nodes = task.get("nodes")
    +        commands = task.get("commands")
    +        if isinstance(commands, str):
    +            commands = [commands]
    +
    +        try:
    +            if action == "run":
    +                res = self.services.execution.run_commands(nodes_filter=nodes, commands=commands)
    +            elif action == "test":
    +                expected = task.get("expected", [])
    +                if isinstance(expected, str):
    +                    expected = [expected]
    +                res = self.services.execution.test_commands(
    +                    nodes_filter=nodes, commands=commands, expected=expected
    +                )
    +            else:
    +                res = f"Unsupported action: {action}"
    +            results[name] = res
    +        except Exception as e:  # noqa: BLE001
    +            return {
    +                "success": False,
    +                "error": f"Execution failed at task '{name}': {e}",
    +                "partial_results": results,
    +            }
    +
    +    return {"success": True, "results": results}
    +
    +

    Validate and execute a playbook, verifying commands beforehand if trust=False.

    +
    +
    +def test_commands(self,
    nodes_filter: str,
    commands: list[str] | str,
    expected: list[str] | str = '',
    parallel: bool = True,
    timeout: int = 30) ‑> dict
    +
    +
    +
    + +Expand source code + +
    def test_commands(
    +    self,
    +    nodes_filter: str,
    +    commands: list[str] | str,
    +    expected: list[str] | str = "",
    +    parallel: bool = True,
    +    timeout: int = 30,
    +) -> dict:
    +    """Execute commands and assert expected patterns on nodes matching the filter."""
    +    if not self.services or not hasattr(self.services, "execution"):
    +        return {"success": False, "error": "Execution service unavailable."}
    +
    +    # Normalize commands
    +    if isinstance(commands, str):
    +        try:
    +            import json
    +
    +            parsed = json.loads(commands)
    +            commands = parsed if isinstance(parsed, list) else [commands]
    +        except Exception:  # noqa: BLE001
    +            commands = [c.strip() for c in commands.splitlines() if c.strip()]
    +    elif not isinstance(commands, list):
    +        commands = [str(commands)]
    +
    +    # Normalize expected
    +    if isinstance(expected, str):
    +        try:
    +            import json
    +
    +            parsed = json.loads(expected)
    +            expected = parsed if isinstance(parsed, list) else ([expected] if expected else [])
    +        except Exception:  # noqa: BLE001
    +            expected = [expected] if expected else []
    +    elif not isinstance(expected, list):
    +        expected = [str(expected)] if expected else []
    +
    +    # Check safety
    +    if not self.trust:
    +        unsafe = [cmd for cmd in commands if not self.is_safe_command(cmd)]
    +        if unsafe:
    +            return {
    +                "success": False,
    +                "error": f"Permission denied: unsafe commands detected: {unsafe}. Requires trust=True.",
    +            }
    +
    +    par_count = 10 if parallel is True else (parallel if isinstance(parallel, int) else 1)
    +    try:
    +        results = self.services.execution.test_commands(
    +            nodes_filter=nodes_filter,
    +            commands=commands,
    +            expected=expected,
    +            parallel=par_count,
    +            timeout=timeout,
    +        )
    +        return {"success": True, "results": results}
    +    except Exception as e:  # noqa: BLE001
    +        return {"success": False, "error": str(e)}
    +
    +

    Execute commands and assert expected patterns on nodes matching the filter.

    +
    +
    +def update_node(self, unique_id: str, updates: dict | None = None, **kwargs) ‑> dict +
    +
    +
    + +Expand source code + +
    def update_node(self, unique_id: str, updates: dict | None = None, **kwargs) -> dict:
    +    """Update an existing node configuration (requires trust=True)."""
    +    if not self.trust:
    +        return {
    +            "success": False,
    +            "error": "Permission denied: CRUD operations require trust mode (--trust).",
    +        }
    +
    +    if not self.services or not hasattr(self.services, "nodes"):
    +        return {"success": False, "error": "Node service unavailable."}
    +
    +    node_updates = (updates or {}).copy()
    +    node_updates.update(kwargs)
    +
    +    try:
    +        self.services.nodes.update_node(unique_id, node_updates)
    +        return {"success": True, "message": f"Node '{unique_id}' updated successfully."}
    +    except Exception as e:  # noqa: BLE001
    +        return {"success": False, "error": str(e)}
    +
    +

    Update an existing node configuration (requires trust=True).

    +
    +
    +def validate_playbook(self, playbook_yaml: str) ‑> dict +
    +
    +
    + +Expand source code + +
    def validate_playbook(self, playbook_yaml: str) -> dict:
    +    """Validate the syntax, schema, and tasks of a Connpy YAML playbook."""
    +    try:
    +        data = yaml.safe_load(playbook_yaml)
    +    except Exception as e:  # noqa: BLE001
    +        return {"valid": False, "error": f"YAML Syntax Error: {e}"}
    +
    +    if not isinstance(data, dict):
    +        return {"valid": False, "error": "Playbook must be a YAML dictionary."}
    +
    +    if "tasks" not in data:
    +        return {"valid": False, "error": "Playbook missing mandatory root 'tasks' key."}
    +
    +    tasks = data["tasks"]
    +    if not isinstance(tasks, list):
    +        return {"valid": False, "error": "'tasks' must be a list of tasks."}
    +
    +    for idx, task in enumerate(tasks):
    +        if not isinstance(task, dict):
    +            return {"valid": False, "error": f"Task index {idx} must be a dictionary."}
    +
    +        name = task.get("name", f"Task {idx}")
    +        mandatory = ["name", "action", "nodes", "commands", "output"]
    +        missing = [f for f in mandatory if f not in task]
    +        if missing:
    +            return {
    +                "valid": False,
    +                "error": f"Task '{name}' (index {idx}) is missing mandatory fields: {missing}",
    +            }
    +
    +        nodes = task["nodes"]
    +        if not isinstance(nodes, (str, list)):
    +            return {
    +                "valid": False,
    +                "error": f"Task '{name}' (index {idx}) 'nodes' must be a string or list of strings.",
    +            }
    +
    +        if isinstance(nodes, list):
    +            for n_idx, node_item in enumerate(nodes):
    +                if not isinstance(node_item, str):
    +                    return {
    +                        "valid": False,
    +                        "error": f"Task '{name}' (index {idx}) 'nodes' contains non-string at index {n_idx}: {node_item}",
    +                    }
    +
    +        action = task["action"]
    +        if action not in ["run", "test"]:
    +            return {
    +                "valid": False,
    +                "error": f"Task '{name}' (index {idx}) invalid action '{action}'. Choices: 'run', 'test'.",
    +            }
    +
    +        if action == "test" and "expected" not in task:
    +            return {
    +                "valid": False,
    +                "error": f"Task '{name}' (index {idx}) action 'test' requires 'expected' key.",
    +            }
    +
    +        output = task["output"]
    +        if output not in [None, "stdout", "null"] and not str(output).startswith("/"):
    +            return {
    +                "valid": False,
    +                "error": f"Task '{name}' (index {idx}) output '{output}' must be 'stdout', 'null' or an absolute path.",
    +            }
    +
    +    return {"valid": True, "message": "Playbook schema and syntax is valid."}
    +
    +

    Validate the syntax, schema, and tasks of a Connpy YAML playbook.

    +
    +
    +
    +
    +
    +
    + +
    + + + diff --git a/docs/connpy/services/ai_service.html b/docs/connpy/services/ai_service.html index d774054..f262174 100644 --- a/docs/connpy/services/ai_service.html +++ b/docs/connpy/services/ai_service.html @@ -427,8 +427,9 @@ el.replaceWith(d);

    Business logic for interacting with AI agents and LLM configurations.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/base.html b/docs/connpy/services/base.html index e72b7ab..6fe1813 100644 --- a/docs/connpy/services/base.html +++ b/docs/connpy/services/base.html @@ -89,8 +89,9 @@ el.replaceWith(d);

    Base class for all connpy services, providing common configuration access.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/config_service.html b/docs/connpy/services/config_service.html index ad87411..640b8eb 100644 --- a/docs/connpy/services/config_service.html +++ b/docs/connpy/services/config_service.html @@ -133,8 +133,9 @@ el.replaceWith(d);

    Business logic for general application settings and state configuration.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/context_service.html b/docs/connpy/services/context_service.html index 0a772f7..3d70841 100644 --- a/docs/connpy/services/context_service.html +++ b/docs/connpy/services/context_service.html @@ -139,8 +139,9 @@ el.replaceWith(d);

    Business logic for managing and applying regex-based contexts locally.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/execution_service.html b/docs/connpy/services/execution_service.html index 73aaa95..36ef9cf 100644 --- a/docs/connpy/services/execution_service.html +++ b/docs/connpy/services/execution_service.html @@ -160,8 +160,9 @@ el.replaceWith(d);

    Business logic for executing commands on nodes and running automation scripts.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/import_export_service.html b/docs/connpy/services/import_export_service.html index 58e0736..090869b 100644 --- a/docs/connpy/services/import_export_service.html +++ b/docs/connpy/services/import_export_service.html @@ -120,7 +120,7 @@ el.replaceWith(d); try: with open(file_path, "r") as f: - data = yaml.load(f, Loader=yaml.FullLoader) + data = yaml.safe_load(f) self.import_from_dict(data) except Exception as e: raise InvalidConfigurationError(f"Failed to read/parse import file: {e}") @@ -165,8 +165,9 @@ el.replaceWith(d);

    Business logic for YAML/JSON inventory import and export.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    @@ -314,7 +315,7 @@ el.replaceWith(d); try: with open(file_path, "r") as f: - data = yaml.load(f, Loader=yaml.FullLoader) + data = yaml.safe_load(f) self.import_from_dict(data) except Exception as e: raise InvalidConfigurationError(f"Failed to read/parse import file: {e}") diff --git a/docs/connpy/services/index.html b/docs/connpy/services/index.html index d71b754..61d9385 100644 --- a/docs/connpy/services/index.html +++ b/docs/connpy/services/index.html @@ -486,8 +486,9 @@ el.replaceWith(d);

    Business logic for interacting with AI agents and LLM configurations.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    @@ -1078,8 +1079,9 @@ el.replaceWith(d);

    Business logic for general application settings and state configuration.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    @@ -1397,8 +1399,9 @@ el.replaceWith(d);

    Business logic for executing commands on nodes and running automation scripts.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    @@ -1622,7 +1625,7 @@ el.replaceWith(d); try: with open(file_path, "r") as f: - data = yaml.load(f, Loader=yaml.FullLoader) + data = yaml.safe_load(f) self.import_from_dict(data) except Exception as e: raise InvalidConfigurationError(f"Failed to read/parse import file: {e}") @@ -1667,8 +1670,9 @@ el.replaceWith(d);

    Business logic for YAML/JSON inventory import and export.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    @@ -1816,7 +1820,7 @@ el.replaceWith(d); try: with open(file_path, "r") as f: - data = yaml.load(f, Loader=yaml.FullLoader) + data = yaml.safe_load(f) self.import_from_dict(data) except Exception as e: raise InvalidConfigurationError(f"Failed to read/parse import file: {e}") @@ -2176,8 +2180,9 @@ el.replaceWith(d);

    Base class for all connpy services, providing common configuration access.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    @@ -2965,8 +2970,9 @@ el.replaceWith(d);

    Business logic for enabling, disabling, and listing plugins.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    @@ -3542,8 +3548,9 @@ el.replaceWith(d);

    Business logic for node profiles management.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    @@ -4140,8 +4147,9 @@ el.replaceWith(d);

    Business logic for Google Drive synchronization.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    @@ -4740,8 +4748,9 @@ el.replaceWith(d);

    Business logic for application lifecycle (API, processes).

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/node_service.html b/docs/connpy/services/node_service.html index dc1092d..13c94ad 100644 --- a/docs/connpy/services/node_service.html +++ b/docs/connpy/services/node_service.html @@ -326,8 +326,9 @@ el.replaceWith(d);

    Base class for all connpy services, providing common configuration access.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/plugin_service.html b/docs/connpy/services/plugin_service.html index 06f0497..6a168ff 100644 --- a/docs/connpy/services/plugin_service.html +++ b/docs/connpy/services/plugin_service.html @@ -411,8 +411,9 @@ el.replaceWith(d);

    Business logic for enabling, disabling, and listing plugins.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/profile_service.html b/docs/connpy/services/profile_service.html index 568aec0..148d624 100644 --- a/docs/connpy/services/profile_service.html +++ b/docs/connpy/services/profile_service.html @@ -188,8 +188,9 @@ el.replaceWith(d);

    Business logic for node profiles management.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/sync_service.html b/docs/connpy/services/sync_service.html index f69ec6c..6074f75 100644 --- a/docs/connpy/services/sync_service.html +++ b/docs/connpy/services/sync_service.html @@ -435,8 +435,9 @@ el.replaceWith(d);

    Business logic for Google Drive synchronization.

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).
    diff --git a/docs/connpy/services/system_service.html b/docs/connpy/services/system_service.html index ded62e1..90b5a7c 100644 --- a/docs/connpy/services/system_service.html +++ b/docs/connpy/services/system_service.html @@ -142,8 +142,9 @@ el.replaceWith(d);

    Business logic for application lifecycle (API, processes).

    Initialize the service.

    -

    Args

    +
    Args
    +
    -----=
    config
    An instance of configfile (or None to instantiate a new one/use global context).