diff --git a/README.md b/README.md index fbe6f6e..c2d6af5 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@

-# Connpy (v6.0.3) +# Connpy (v6.1.0) [![](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/) @@ -44,6 +44,21 @@ Connect to external data sources and tools dynamically via the Model Context Pro conn ai --mcp ``` +### 1d. Local Interactive Shell (conn shell) +Launch a local interactive shell with AI Copilot support enabled directly on your host machine: +```bash +conn shell # Start local shell (default: $SHELL or /bin/bash) +conn shell -c /bin/zsh # Override shell executable +conn shell --capture session.log # Log session output to file +``` +* **Nested Sessions & Passthrough**: Supports running nested `conn` / `connpy` connections inside `conn shell`. Automatically detects foreground `conn` processes and forwards `Ctrl+Space` down to the active device connection instead of triggering the local Copilot. +* **Shell Configuration**: Configure default shell command, prompt regex, or OS type via `conn config`: +```bash +conn config --shell-command /bin/zsh +conn config --shell-prompt "\$\s*$" +conn config --shell-os ubuntu +``` + --- @@ -179,14 +194,19 @@ conn config --service-mode remote conn config --remote localhost:50051 ``` -### 8c. User Management -Manage server-side user credentials for distributed setups: +### 8c. User Management & API Tokens +Manage server-side user credentials and Personal Access Tokens (PAT) for automated setups: ```bash conn user --add username conn user --list conn user --regen-password username + +# Personal Access Tokens (PAT) for non-interactive API access +conn user --create-token "CI/CD Token" --expires-in 30 +conn user --list-tokens +conn user --revoke-token ``` -Use `--path` to specify custom configuration folders in server Mode B. +Use `--path` to specify custom configuration folders in server Mode B. Pass API tokens via `CONNPY_TOKEN` environment variable. ### 8d. SSO / OIDC Configure identity providers (e.g. Authelia, Keycloak) for SSO gRPC authentication using the interactive wizard: diff --git a/connpy/__init__.py b/connpy/__init__.py index 15532f4..d520eee 100644 --- a/connpy/__init__.py +++ b/connpy/__init__.py @@ -5,7 +5,7 @@

-# Connpy (v6.0.3) +# Connpy (v6.1.0) [![](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/) @@ -46,6 +46,21 @@ Connect to external data sources and tools dynamically via the Model Context Pro conn ai --mcp ``` +### 1d. Local Interactive Shell (conn shell) +Launch a local interactive shell with AI Copilot support enabled directly on your host machine: +```bash +conn shell # Start local shell (default: $SHELL or /bin/bash) +conn shell -c /bin/zsh # Override shell executable +conn shell --capture session.log # Log session output to file +``` +* **Nested Sessions & Passthrough**: Supports running nested `conn` / `connpy` connections inside `conn shell`. Automatically detects foreground `conn` processes and forwards `Ctrl+Space` down to the active device connection instead of triggering the local Copilot. +* **Shell Configuration**: Configure default shell command, prompt regex, or OS type via `conn config`: +```bash +conn config --shell-command /bin/zsh +conn config --shell-prompt "\$\s*$" +conn config --shell-os ubuntu +``` + --- @@ -181,14 +196,19 @@ conn config --service-mode remote conn config --remote localhost:50051 ``` -### 8c. User Management -Manage server-side user credentials for distributed setups: +### 8c. User Management & API Tokens +Manage server-side user credentials and Personal Access Tokens (PAT) for automated setups: ```bash conn user --add username conn user --list conn user --regen-password username + +# Personal Access Tokens (PAT) for non-interactive API access +conn user --create-token "CI/CD Token" --expires-in 30 +conn user --list-tokens +conn user --revoke-token ``` -Use `--path` to specify custom configuration folders in server Mode B. +Use `--path` to specify custom configuration folders in server Mode B. Pass API tokens via `CONNPY_TOKEN` environment variable. ### 8d. SSO / OIDC Configure identity providers (e.g. Authelia, Keycloak) for SSO gRPC authentication using the interactive wizard: diff --git a/connpy/_version.py b/connpy/_version.py index 35504ed..7856d12 100644 --- a/connpy/_version.py +++ b/connpy/_version.py @@ -1 +1 @@ -__version__ = "6.0.5" +__version__ = "6.1.0" diff --git a/connpy/cli/config_handler.py b/connpy/cli/config_handler.py index 13d7904..eeb0fea 100644 --- a/connpy/cli/config_handler.py +++ b/connpy/cli/config_handler.py @@ -26,7 +26,10 @@ class ConfigHandler: "trusted_commands": self.set_ai_config, "service_mode": self.set_service_mode, "remote_host": self.set_remote_host, - "sync_remote": self.set_sync_remote + "sync_remote": self.set_sync_remote, + "shell_command": self.set_shell_config, + "shell_prompt": self.set_shell_config, + "shell_os": self.set_shell_config } handler = actions.get(getattr(args, "command", None)) if handler: @@ -183,3 +186,19 @@ class ConfigHandler: except Exception: raise InvalidConfigurationError("Auth parameter must be a valid JSON/YAML string, or a path to a JSON/YAML file.") + def set_shell_config(self, args): + key = args.command.replace("shell_", "") + val = args.data[0] if isinstance(args.data, list) else args.data + try: + settings = self.app.services.config_svc.get_settings() + shell_cfg = settings.get("shell", {}) if isinstance(settings.get("shell"), dict) else {} + if str(val).lower() in ["none", "clear", ""]: + if key in shell_cfg: + del shell_cfg[key] + else: + shell_cfg[key] = val + self.app.services.config_svc.update_setting("shell", shell_cfg) + printer.success("Config saved") + except (ConnpyError, InvalidConfigurationError) as e: + printer.error(str(e)) + diff --git a/connpy/cli/shell_handler.py b/connpy/cli/shell_handler.py new file mode 100644 index 0000000..20f8de2 --- /dev/null +++ b/connpy/cli/shell_handler.py @@ -0,0 +1,55 @@ +import os +import sys +import shutil +import shlex +import socket +from .. import printer +from ..core import node + +class ShellHandler: + def __init__(self, app): + self.app = app + + def dispatch(self, args): + shell_config = self.app.config.config.get("shell", {}) if hasattr(self.app.config, "config") else {} + command = getattr(args, 'command_override', None) or shell_config.get("command") or os.environ.get("SHELL", "/bin/bash") + + try: + exe = shlex.split(command)[0] + except Exception: + exe = command + + if not shutil.which(exe): + printer.error(f"Shell command executable not found: {exe}") + sys.exit(1) + + node_info = self._build_local_identity(shell_config) + + tags = { + "os": node_info["os"], + "prompt": node_info["prompt"] + } + + n = node( + unique=node_info["name"], + host=command, + protocol="local", + config=self.app.config, + tags=tags + ) + + capture_file = getattr(args, 'capture_file', None) + if capture_file: + n.logs = capture_file + elif shell_config.get("logging"): + n.logs = shell_config.get("log_path", os.path.expanduser("~/.config/conn/shell_logs/session.log")) + + n.interact(debug=getattr(args, 'debug', False)) + + def _build_local_identity(self, shell_config): + return { + "name": "local-shell", + "host": socket.gethostname(), + "os": shell_config.get("os", "linux"), + "prompt": shell_config.get("prompt", r'\$\s*$|#\s*$') + } diff --git a/connpy/completion.py b/connpy/completion.py index d7900b0..2860b35 100755 --- a/connpy/completion.py +++ b/connpy/completion.py @@ -238,12 +238,22 @@ def _build_tree(nodes, folders, profiles, plugins, configdir): "--sync-remote": ["true", "false"], "--help": None, "-h": None, } - for opt in ["--keepalive", "--engineer-model", "--engineer-api-key", "--architect-model", "--architect-api-key", "--theme", "--remote", "--trusted-commands"]: + for opt in ["--keepalive", "--engineer-model", "--engineer-api-key", "--architect-model", "--architect-api-key", "--theme", "--remote", "--trusted-commands", "--shell-command", "--shell-prompt", "--shell-os"]: config_dict[opt] = {"*": config_dict} config_dict["--configfolder"] = {"__extra__": lambda w: get_cwd(w, "--configfolder", True), "*": config_dict} config_dict["--engineer-auth"] = {"__extra__": lambda w: get_cwd(w, "--engineer-auth"), "*": config_dict} config_dict["--architect-auth"] = {"__extra__": lambda w: get_cwd(w, "--architect-auth"), "*": config_dict} + shell_dict = { + "--command": {"*": None}, + "-c": {"*": None}, + "--capture": {"__extra__": lambda w: get_cwd(w, "--capture")}, + "--debug": None, + "-d": None, + "--help": None, + "-h": None + } + _users = lambda w=None: _get_users(configdir) user_dict = { @@ -376,6 +386,7 @@ def _build_tree(nodes, folders, profiles, plugins, configdir): }, "logout": {"--help": None, "-h": None}, "config": config_dict, + "shell": shell_dict, "sync": { "--login": None, "--logout": None, "--status": None, "--list": None, diff --git a/connpy/connapp.py b/connpy/connapp.py index a582f04..ba4f058 100755 --- a/connpy/connapp.py +++ b/connpy/connapp.py @@ -162,6 +162,7 @@ class connapp: from .cli.user_handler import UserHandler from .cli.login_handler import LoginHandler from .cli.sso_handler import SSOHandler + from .cli.shell_handler import ShellHandler # Instantiate Handlers self._node = NodeHandler(self) @@ -173,6 +174,7 @@ class connapp: self._plugin = PluginHandler(self) self._context = ContextHandler(self) self._import_export = ImportExportHandler(self) + self._shell = ShellHandler(self) self._sync = SyncHandler(self) self._user = UserHandler(self) self._login = LoginHandler(self) @@ -384,10 +386,19 @@ class connapp: configcrud.add_argument("--architect-api-key", dest="architect_api_key", nargs=1, action=self._store_type, help="Set architect api_key", metavar="API_KEY") configcrud.add_argument("--architect-auth", dest="architect_auth", nargs=1, action=self._store_type, help="Set architect auth (inline JSON/YAML or file path)", metavar="AUTH") configcrud.add_argument("--sync-remote", dest="sync_remote", nargs=1, action=self._store_type, help="Sync remote nodes to Google Drive", choices=["true","false"]) + configcrud.add_argument("--shell-command", dest="shell_command", nargs=1, action=self._store_type, help="Set default shell command", metavar="COMMAND") + configcrud.add_argument("--shell-prompt", dest="shell_prompt", nargs=1, action=self._store_type, help="Set shell prompt regex for AI", metavar="REGEX") + configcrud.add_argument("--shell-os", dest="shell_os", nargs=1, action=self._store_type, help="Set shell OS hint for AI", metavar="OS") configparser.add_argument("--trusted-commands", dest="trusted_commands", nargs=1, action=self._store_type, help="Set custom trusted commands regexes (comma separated)", metavar="REGEX,REGEX") configparser.set_defaults(func=self._config.dispatch) - #USERPARSER + #SHELLPARSER + shellparser = subparsers.add_parser("shell", help="Start local interactive shell with copilot", formatter_class=RichHelpFormatter) + shellparser.error = self._custom_error + shellparser.add_argument("--command", "-c", dest="command_override", help="Override shell command") + shellparser.add_argument("--capture", dest="capture_file", help="Capture session to file") + shellparser.add_argument("-d", "--debug", action="store_true", help="Debug mode") + shellparser.set_defaults(func=self._shell.dispatch) userparser = subparsers.add_parser("user", help="Manage server users", description="Manage server users", formatter_class=RichHelpFormatter) userparser.error = self._custom_error usercrud = userparser.add_mutually_exclusive_group(required=True) diff --git a/connpy/core.py b/connpy/core.py index 0024643..5f30e50 100755 --- a/connpy/core.py +++ b/connpy/core.py @@ -374,7 +374,7 @@ class node: self.child.setwinsize(int(size.group(2)),int(size.group(1))) except OSError: pass - if logger: + if logger and self.protocol != "local": port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else "" logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}") @@ -408,6 +408,34 @@ class node: with open(self.logfile, "w") as f: f.write(self._logclean(self.mylog.getvalue().decode(), True)) + def _is_child_connpy_active(self, child_fd: int) -> bool: + if self.protocol != "local": + return False + try: + fg_pgid = os.tcgetpgrp(child_fd) + if fg_pgid <= 0: + return False + cmdline_path = f"/proc/{fg_pgid}/cmdline" + if os.path.exists(cmdline_path): + with open(cmdline_path, "rb") as f: + raw_args = f.read().split(b"\x00") + cmdline_str = " ".join([arg.decode(errors="ignore") for arg in raw_args if arg]) + + is_active = False + for raw_arg in raw_args: + arg_str = raw_arg.decode(errors="ignore") + if not arg_str: + continue + base_name = os.path.basename(arg_str) + if base_name in ["conn", "connpy", "connapp"] or "connpy" in arg_str or "connapp" in arg_str: + is_active = True + break + + return is_active + except Exception: + pass + return False + async def _async_interact_loop(self, local_stream, resize_callback, copilot_handler=None): local_stream.setup(resize_callback=resize_callback) self.current_local_stream = local_stream @@ -472,6 +500,14 @@ class node: # Copilot interception if copilot_handler and b'\x00' in data: + if self._is_child_connpy_active(child_fd): + try: + os.write(child_fd, data) + except OSError: + break + self.lastinput = time() + continue + # Build node info from available metadata and ensure values are strings (not bytes) def to_str(val): if isinstance(val, bytes): @@ -579,12 +615,39 @@ class node: except Exception: pass + async def pwd_tracker_task(): + import socket + hostname = socket.gethostname() + last_cwd = None + while True: + await asyncio.sleep(0.3) + try: + child_pid = getattr(self.child, 'pid', None) + if child_pid: + new_cwd = os.readlink(f"/proc/{child_pid}/cwd") + if new_cwd != last_cwd: + last_cwd = new_cwd + try: + os.chdir(new_cwd) + except Exception: + pass + try: + await local_stream.write(f"\033]7;file://{hostname}{new_cwd}\007".encode()) + except Exception: + pass + if isinstance(self.tags, dict): + self.tags["cwd"] = new_cwd + except Exception: + pass + try: # We wait for either the user (ingress) or the child (egress) to finish tasks = [ asyncio.create_task(ingress_task()), asyncio.create_task(egress_task()) ] + if self.protocol == "local": + tasks.append(asyncio.create_task(pwd_tracker_task())) if self.idletime > 0: tasks.append(asyncio.create_task(keepalive_task())) if hasattr(self, 'logfile') and hasattr(self, 'mylog'): @@ -1106,12 +1169,23 @@ class node: return self._generate_docker_cmd() elif self.protocol == "ssm": return self._generate_ssm_cmd() + elif self.protocol == "local": + return self.host else: printer.error(f"Invalid protocol: {self.protocol}") sys.exit(1) @MethodHook def _connect(self, debug=False, timeout=10, max_attempts=3, logger=None): + if self.protocol == "local": + cmd = self._get_cmd() + args = shlex.split(cmd) + self.child = pexpect.spawn(args[0], args[1:], env=os.environ.copy()) + from pexpect import fdpexpect + self.raw_child = fdpexpect.fdspawn(self.child.child_fd) + if self.logs != '': + self.logfile = self._logfile() + return True cmd = self._get_cmd() passwords = self._passtx(self.password) if self.password and any(self.password) else [] diff --git a/connpy/tests/test_completion.py b/connpy/tests/test_completion.py index 8b2a6b8..2d4694b 100644 --- a/connpy/tests/test_completion.py +++ b/connpy/tests/test_completion.py @@ -77,6 +77,9 @@ class TestTreeCompletions: config_completions = resolve_completion(["config", ""], tree) assert "--engineer-auth" in config_completions assert "--architect-auth" in config_completions + assert "--shell-command" in config_completions + assert "--shell-prompt" in config_completions + assert "--shell-os" in config_completions # Resolve when --engineer-auth is chosen in config auth_comp = resolve_completion(["config", "--engineer-auth", ""], tree) @@ -88,6 +91,20 @@ class TestTreeCompletions: loop_back_comp = resolve_completion(["config", "--engineer-auth", "some_val", ""], tree) assert "--architect-auth" in loop_back_comp assert "--engineer-auth" in loop_back_comp + assert "--shell-command" in loop_back_comp + + def test_shell_completions(self): + from connpy.completion import _build_tree, resolve_completion + tree = _build_tree([], [], [], {}, "/tmp") + shell_completions = resolve_completion(["shell", ""], tree) + assert "--command" in shell_completions + assert "--capture" in shell_completions + assert "--debug" in shell_completions + assert "--help" in shell_completions + # Short flags must NOT be recommended + assert "-c" not in shell_completions + assert "-d" not in shell_completions + assert "-h" not in shell_completions def test_ai_auth_completions(self): from connpy.completion import _build_tree, resolve_completion diff --git a/connpy/tests/test_local_shell.py b/connpy/tests/test_local_shell.py new file mode 100644 index 0000000..f11b7c5 --- /dev/null +++ b/connpy/tests/test_local_shell.py @@ -0,0 +1,80 @@ +import os +import sys +import pytest +from unittest.mock import patch, MagicMock +from connpy.core import node +from connpy.cli.shell_handler import ShellHandler +from connpy.cli.validators import Validators + +def test_local_protocol_get_cmd_and_connect(): + """Test protocol=local in node returns command string and spawns process.""" + n = node(unique="test_local", host="echo hello", protocol="local") + assert n._get_cmd() == "echo hello" + + with patch("pexpect.spawn") as mock_spawn: + mock_child = MagicMock() + mock_child.child_fd = 10 + mock_spawn.return_value = mock_child + with patch("pexpect.fdpexpect.fdspawn") as mock_fdspawn: + res = n._connect() + assert res is True + mock_spawn.assert_called_once() + +def test_shell_handler_dispatch(tmp_path): + """Test ShellHandler builds transient node and calls interact.""" + app_mock = MagicMock() + app_mock.config.config = {"shell": {"os": "ubuntu", "prompt": r"\$\s*$"}} + + handler = ShellHandler(app_mock) + args = MagicMock() + args.command_override = None + args.capture_file = str(tmp_path / "session.log") + args.debug = False + + with patch("connpy.cli.shell_handler.node") as mock_node_cls: + mock_node = MagicMock() + mock_node_cls.return_value = mock_node + handler.dispatch(args) + + mock_node_cls.assert_called_once() + kwargs = mock_node_cls.call_args.kwargs + assert kwargs["protocol"] == "local" + assert kwargs["unique"] == "local-shell" + assert mock_node.interact.called + +def test_validator_excludes_local_protocol(): + """Ensure protocol_validation does NOT accept 'local' for inventory forms.""" + validators = Validators(MagicMock()) + with pytest.raises(Exception): + validators.protocol_validation({}, "local") + +def test_is_child_connpy_active_non_local_protocol(): + """Ensure non-local protocols (e.g. ssh) never check for sub-child processes.""" + n = node(unique="ssh_node", host="10.0.0.1", protocol="ssh") + with patch("os.tcgetpgrp") as mock_tcgetpgrp: + assert n._is_child_connpy_active(10) is False + mock_tcgetpgrp.assert_not_called() + +def test_is_child_connpy_active_local_protocol(): + """Test detection of child connpy process when protocol=local.""" + n = node(unique="local_node", host="/bin/bash", protocol="local") + + # Case 1: child is connpy + with patch("os.tcgetpgrp", return_value=1234), \ + patch("os.path.exists", return_value=True), \ + patch("builtins.open", MagicMock(return_value=MagicMock(__enter__=lambda s: MagicMock(read=lambda: b"python3\x00/usr/local/bin/connpy\x00connect\x00r1")))): + assert n._is_child_connpy_active(10) is True + + # Case 2: child is regular bash + with patch("os.tcgetpgrp", return_value=1234), \ + patch("os.path.exists", return_value=True), \ + patch("builtins.open", MagicMock(return_value=MagicMock(__enter__=lambda s: MagicMock(read=lambda: b"/bin/bash\x00")))): + assert n._is_child_connpy_active(10) is False + + # Case 3: child is conn entry point (e.g. /home/fluzzi32/.local/bin/conn xr) + with patch("os.tcgetpgrp", return_value=1234), \ + patch("os.path.exists", return_value=True), \ + patch("builtins.open", MagicMock(return_value=MagicMock(__enter__=lambda s: MagicMock(read=lambda: b"/usr/bin/python3\x00/home/fluzzi32/.local/bin/conn\x00xr")))): + assert n._is_child_connpy_active(10) is True + + diff --git a/docs/connpy/ai.html b/docs/connpy/ai.html new file mode 100644 index 0000000..7785f77 --- /dev/null +++ b/docs/connpy/ai.html @@ -0,0 +1,3190 @@ + + + + + + +connpy.ai API documentation + + + + + + + + + + + +
+
+
+

Module connpy.ai

+
+
+
+
+
+
+
+
+

Functions

+
+
+def cleanup() +
+
+
+ +Expand source code + +
def cleanup():
+    """Safely close any global litellm sessions in the dedicated AI loop."""
+    global _ai_loop
+    if _ai_loop:
+        try:
+            future = asyncio.run_coroutine_threadsafe(_async_cleanup(), _ai_loop)
+            future.result(timeout=5)
+        except:
+            pass
+
+

Safely close any global litellm sessions in the dedicated AI loop.

+
+
+def completion(*args, **kwargs) +
+
+
+ +Expand source code + +
def completion(*args, **kwargs):
+    _init_litellm()
+    from litellm import completion as _completion
+    return _completion(*args, **kwargs)
+
+
+
+
+def run_ai_async(coro) +
+
+
+ +Expand source code + +
def run_ai_async(coro):
+    """Run a coroutine in the dedicated AI background loop."""
+    loop = _get_ai_loop()
+    return asyncio.run_coroutine_threadsafe(coro, loop)
+
+

Run a coroutine in the dedicated AI background loop.

+
+
+def stream_chunk_builder(*args, **kwargs) +
+
+
+ +Expand source code + +
def stream_chunk_builder(*args, **kwargs):
+    _init_litellm()
+    from litellm import stream_chunk_builder as _stream_chunk_builder
+    return _stream_chunk_builder(*args, **kwargs)
+
+
+
+
+
+
+

Classes

+
+
+class PlaybookBuilderAgent +(config, console=None, confirm_handler=None, trust=False, **kwargs) +
+
+
+ +Expand source code + +
class PlaybookBuilderAgent:
+    """Specialized AI agent for building, validating, and generating Connpy YAML playbooks."""
+
+    def __init__(self, config, console=None, confirm_handler=None, trust=False, **kwargs):
+        self.config = config
+        self.console = console or printer.console
+        self.interrupted = False
+        
+        # Load AI configuration
+        if hasattr(self.config, "get_effective_setting"):
+            aiconfig = self.config.get_effective_setting("ai", {})
+        else:
+            aiconfig = self.config.config.get("ai", {}) if hasattr(self.config, "config") else {}
+
+        # Default model for technical tasks
+        self.model = kwargs.get("engineer_model") or aiconfig.get("engineer_model") or "gemini/gemini-3.1-flash-lite"
+        self.key = kwargs.get("engineer_api_key") or aiconfig.get("engineer_api_key")
+        self.auth = kwargs.get("engineer_auth") or aiconfig.get("engineer_auth") or {}
+        if self.key and "api_key" not in self.auth:
+            self.auth = self.auth.copy()
+            self.auth["api_key"] = self.key
+
+    def validate_playbook(self, playbook_yaml: str) -> dict:
+        """Sintactical and schema validation of Connpy Playbook YAML."""
+        import yaml
+        try:
+            # 1. Parse YAML
+            data = yaml.load(playbook_yaml, Loader=yaml.FullLoader)
+        except Exception as e:
+            return {"valid": False, "error": f"YAML Syntax Error: {e}"}
+
+        # 2. Check structure
+        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."}
+
+        # 3. Check individual 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 fields
+            mandatory = ["name", "action", "nodes", "commands", "output"]
+            missing = [field for field in mandatory if field not in task]
+            if missing:
+                return {"valid": False, "error": f"Task '{name}' (index {idx}) is missing mandatory fields: {missing}"}
+
+            # Validate nodes field type (supports string regexes or array of string regexes)
+            nodes = task["nodes"]
+            if not isinstance(nodes, (str, list)):
+                return {"valid": False, "error": f"Task '{name}' (index {idx}) 'nodes' must be a string (regex) or a list of strings (regexes)."}
+            
+            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' list contains a non-string value at index {n_idx}: {node_item}"}
+
+            action = task["action"]
+            if action not in ["run", "test"]:
+                return {"valid": False, "error": f"Task '{name}' (index {idx}) has invalid action '{action}'. Choices are: 'run', 'test'."}
+
+            if action == "test" and "expected" not in task:
+                return {"valid": False, "error": f"Task '{name}' (index {idx}) has action 'test' but is missing the mandatory 'expected' key."}
+
+            output = task["output"]
+            if output not in [None, "stdout"] and not output.startswith("/"):
+                return {"valid": False, "error": f"Task '{name}' (index {idx}) output '{output}' is invalid. Must be 'stdout', 'null' or an absolute path."}
+
+        return {"valid": True, "message": "Playbook schema and syntax is valid."}
+
+    def ask(self, user_input, chat_history=None, status=None, debug=False, chunk_callback=None):
+        """Standard conversation step with tool loop for PlaybookBuilderAgent."""
+        if chat_history is None:
+            chat_history = []
+
+        # System prompt and tool definition
+        system_prompt = PLAYBOOK_BUILDER_SYSTEM_PROMPT
+        tools = PLAYBOOK_BUILDER_TOOLS
+        messages = [{"role": "system", "content": system_prompt}]
+
+        for msg in chat_history:
+            m = msg if isinstance(msg, dict) else msg.copy()
+            if m.get('role') == 'assistant' and m.get('tool_calls') and m.get('content') == "":
+                m['content'] = None
+            messages.append(m)
+
+        messages.append({"role": "user", "content": user_input})
+
+        final_playbook_yaml = None
+        iteration = 0
+        max_iterations = 10
+
+        while iteration < max_iterations:
+            iteration += 1
+
+            if status:
+                status.update(f"Playbook Agent is thinking... (step {iteration})")
+
+            # Call LiteLLM completion
+            from connpy.ai import completion
+            try:
+                response = completion(
+                    model=self.model,
+                    messages=messages,
+                    tools=tools,
+                    num_retries=3,
+                    **self.auth
+                )
+            except Exception as e:
+                return {"response": f"Playbook Agent failed: {str(e)}", "chat_history": messages[1:]}
+
+            resp_msg = response.choices[0].message
+            msg_dict = resp_msg.model_dump(exclude_none=True)
+            if msg_dict.get("tool_calls") and msg_dict.get("content") == "":
+                msg_dict["content"] = None
+            
+            messages.append(msg_dict)
+
+            # If the model sends content, stream or yield it
+            if resp_msg.content:
+                if chunk_callback:
+                    chunk_callback(resp_msg.content)
+                elif not resp_msg.tool_calls:
+                    # In direct non-streaming output, print markdown
+                    self.console.print(Markdown(resp_msg.content))
+
+            if not resp_msg.tool_calls:
+                break
+
+            for tc in resp_msg.tool_calls:
+                fn = tc.function.name
+                args = json.loads(tc.function.arguments)
+
+                if fn == "list_nodes":
+                    filter_pattern = args.get("filter_pattern", ".*")
+                    try:
+                        matched_names = self.config._getallnodes(filter_pattern)
+                        if not matched_names:
+                            obs = "No nodes found matching the filter."
+                        else:
+                            if len(matched_names) <= 5:
+                                matched_data = self.config.getitems(matched_names, extract=True)
+                                res = {}
+                                for name, data in matched_data.items():
+                                    os_tag = "unknown"
+                                    if isinstance(data, dict):
+                                        ts = data.get("tags")
+                                        if isinstance(ts, dict): os_tag = ts.get("os", "unknown")
+                                    res[name] = {"os": os_tag}
+                                obs = json.dumps(res)
+                            else:
+                                obs = json.dumps({
+                                    "matched_count": len(matched_names),
+                                    "message": "Too many nodes matched. Showing names only.",
+                                    "node_names": matched_names
+                                })
+                    except Exception as e:
+                        obs = f"Error listing nodes: {e}"
+                    messages.append({
+                        "tool_call_id": tc.id,
+                        "role": "tool",
+                        "name": fn,
+                        "content": obs
+                    })
+                elif fn == "validate_playbook":
+                    playbook_yaml = args.get("playbook_yaml", "")
+                    validation_res = self.validate_playbook(playbook_yaml)
+                    messages.append({
+                        "tool_call_id": tc.id,
+                        "role": "tool",
+                        "name": fn,
+                        "content": json.dumps(validation_res)
+                    })
+                elif fn == "return_playbook":
+                    final_playbook_yaml = args.get("playbook_yaml", "")
+                    messages.append({
+                        "tool_call_id": tc.id,
+                        "role": "tool",
+                        "name": fn,
+                        "content": json.dumps({"success": True, "message": "Playbook returned successfully."})
+                    })
+
+            # If return_playbook was called, we can terminate early
+            if final_playbook_yaml is not None:
+                break
+
+        return {
+            "response": resp_msg.content or "",
+            "chat_history": messages[1:],
+            "playbook_yaml": final_playbook_yaml
+        }
+
+

Specialized AI agent for building, validating, and generating Connpy YAML playbooks.

+

Methods

+
+
+def ask(self, user_input, chat_history=None, status=None, debug=False, chunk_callback=None) +
+
+
+ +Expand source code + +
def ask(self, user_input, chat_history=None, status=None, debug=False, chunk_callback=None):
+    """Standard conversation step with tool loop for PlaybookBuilderAgent."""
+    if chat_history is None:
+        chat_history = []
+
+    # System prompt and tool definition
+    system_prompt = PLAYBOOK_BUILDER_SYSTEM_PROMPT
+    tools = PLAYBOOK_BUILDER_TOOLS
+    messages = [{"role": "system", "content": system_prompt}]
+
+    for msg in chat_history:
+        m = msg if isinstance(msg, dict) else msg.copy()
+        if m.get('role') == 'assistant' and m.get('tool_calls') and m.get('content') == "":
+            m['content'] = None
+        messages.append(m)
+
+    messages.append({"role": "user", "content": user_input})
+
+    final_playbook_yaml = None
+    iteration = 0
+    max_iterations = 10
+
+    while iteration < max_iterations:
+        iteration += 1
+
+        if status:
+            status.update(f"Playbook Agent is thinking... (step {iteration})")
+
+        # Call LiteLLM completion
+        from connpy.ai import completion
+        try:
+            response = completion(
+                model=self.model,
+                messages=messages,
+                tools=tools,
+                num_retries=3,
+                **self.auth
+            )
+        except Exception as e:
+            return {"response": f"Playbook Agent failed: {str(e)}", "chat_history": messages[1:]}
+
+        resp_msg = response.choices[0].message
+        msg_dict = resp_msg.model_dump(exclude_none=True)
+        if msg_dict.get("tool_calls") and msg_dict.get("content") == "":
+            msg_dict["content"] = None
+        
+        messages.append(msg_dict)
+
+        # If the model sends content, stream or yield it
+        if resp_msg.content:
+            if chunk_callback:
+                chunk_callback(resp_msg.content)
+            elif not resp_msg.tool_calls:
+                # In direct non-streaming output, print markdown
+                self.console.print(Markdown(resp_msg.content))
+
+        if not resp_msg.tool_calls:
+            break
+
+        for tc in resp_msg.tool_calls:
+            fn = tc.function.name
+            args = json.loads(tc.function.arguments)
+
+            if fn == "list_nodes":
+                filter_pattern = args.get("filter_pattern", ".*")
+                try:
+                    matched_names = self.config._getallnodes(filter_pattern)
+                    if not matched_names:
+                        obs = "No nodes found matching the filter."
+                    else:
+                        if len(matched_names) <= 5:
+                            matched_data = self.config.getitems(matched_names, extract=True)
+                            res = {}
+                            for name, data in matched_data.items():
+                                os_tag = "unknown"
+                                if isinstance(data, dict):
+                                    ts = data.get("tags")
+                                    if isinstance(ts, dict): os_tag = ts.get("os", "unknown")
+                                res[name] = {"os": os_tag}
+                            obs = json.dumps(res)
+                        else:
+                            obs = json.dumps({
+                                "matched_count": len(matched_names),
+                                "message": "Too many nodes matched. Showing names only.",
+                                "node_names": matched_names
+                            })
+                except Exception as e:
+                    obs = f"Error listing nodes: {e}"
+                messages.append({
+                    "tool_call_id": tc.id,
+                    "role": "tool",
+                    "name": fn,
+                    "content": obs
+                })
+            elif fn == "validate_playbook":
+                playbook_yaml = args.get("playbook_yaml", "")
+                validation_res = self.validate_playbook(playbook_yaml)
+                messages.append({
+                    "tool_call_id": tc.id,
+                    "role": "tool",
+                    "name": fn,
+                    "content": json.dumps(validation_res)
+                })
+            elif fn == "return_playbook":
+                final_playbook_yaml = args.get("playbook_yaml", "")
+                messages.append({
+                    "tool_call_id": tc.id,
+                    "role": "tool",
+                    "name": fn,
+                    "content": json.dumps({"success": True, "message": "Playbook returned successfully."})
+                })
+
+        # If return_playbook was called, we can terminate early
+        if final_playbook_yaml is not None:
+            break
+
+    return {
+        "response": resp_msg.content or "",
+        "chat_history": messages[1:],
+        "playbook_yaml": final_playbook_yaml
+    }
+
+

Standard conversation step with tool loop for PlaybookBuilderAgent.

+
+
+def validate_playbook(self, playbook_yaml: str) ‑> dict +
+
+
+ +Expand source code + +
def validate_playbook(self, playbook_yaml: str) -> dict:
+    """Sintactical and schema validation of Connpy Playbook YAML."""
+    import yaml
+    try:
+        # 1. Parse YAML
+        data = yaml.load(playbook_yaml, Loader=yaml.FullLoader)
+    except Exception as e:
+        return {"valid": False, "error": f"YAML Syntax Error: {e}"}
+
+    # 2. Check structure
+    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."}
+
+    # 3. Check individual 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 fields
+        mandatory = ["name", "action", "nodes", "commands", "output"]
+        missing = [field for field in mandatory if field not in task]
+        if missing:
+            return {"valid": False, "error": f"Task '{name}' (index {idx}) is missing mandatory fields: {missing}"}
+
+        # Validate nodes field type (supports string regexes or array of string regexes)
+        nodes = task["nodes"]
+        if not isinstance(nodes, (str, list)):
+            return {"valid": False, "error": f"Task '{name}' (index {idx}) 'nodes' must be a string (regex) or a list of strings (regexes)."}
+        
+        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' list contains a non-string value at index {n_idx}: {node_item}"}
+
+        action = task["action"]
+        if action not in ["run", "test"]:
+            return {"valid": False, "error": f"Task '{name}' (index {idx}) has invalid action '{action}'. Choices are: 'run', 'test'."}
+
+        if action == "test" and "expected" not in task:
+            return {"valid": False, "error": f"Task '{name}' (index {idx}) has action 'test' but is missing the mandatory 'expected' key."}
+
+        output = task["output"]
+        if output not in [None, "stdout"] and not output.startswith("/"):
+            return {"valid": False, "error": f"Task '{name}' (index {idx}) output '{output}' is invalid. Must be 'stdout', 'null' or an absolute path."}
+
+    return {"valid": True, "message": "Playbook schema and syntax is valid."}
+
+

Sintactical and schema validation of Connpy Playbook YAML.

+
+
+
+
+class ai +(config,
org=None,
api_key=None,
engineer_model=None,
architect_model=None,
engineer_api_key=None,
architect_api_key=None,
console=None,
confirm_handler=None,
trust=False,
engineer_auth=None,
architect_auth=None,
**kwargs)
+
+
+
+ +Expand source code + +
@ClassHook
+class ai:
+    """Hybrid Multi-Agent System: Selective Escalation with Role Persistence."""
+
+    SAFE_COMMANDS = [
+        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, org=None, api_key=None, engineer_model=None, architect_model=None, engineer_api_key=None, architect_api_key=None, console=None, confirm_handler=None, trust=False, engineer_auth=None, architect_auth=None, **kwargs):
+        self.config = config
+        self.console = console or printer.console
+        self.confirm_handler = confirm_handler or self._local_confirm_handler
+        self.trusted_session = trust  # Trust mode for the entire session
+        self.interrupted = False
+        self.one_shot = kwargs.get("one_shot", False)
+
+        
+        # 1. Load generic configuration with global inheritance/merge
+        if hasattr(self.config, "get_effective_setting"):
+            aiconfig = self.config.get_effective_setting("ai", {})
+        else:
+            aiconfig = self.config.config.get("ai", {}) if hasattr(self.config, "config") else {}
+        
+        # Modelos (Prioridad: Argumento -> Config -> Default)
+        self.engineer_model = engineer_model or aiconfig.get("engineer_model") or "gemini/gemini-3.1-flash-lite"
+        self.architect_model = architect_model or aiconfig.get("architect_model") or "anthropic/claude-sonnet-4-6"
+        
+        # API Keys (Prioridad: Argumento -> Config)
+        self.engineer_key = engineer_api_key or aiconfig.get("engineer_api_key")
+        self.architect_key = architect_api_key or aiconfig.get("architect_api_key")
+
+        # Auth configurations (Prioridad: Argumento -> Config)
+        self.engineer_auth = engineer_auth if engineer_auth is not None else aiconfig.get("engineer_auth")
+        if self.engineer_auth is None:
+            self.engineer_auth = {}
+        elif not isinstance(self.engineer_auth, dict):
+            self.engineer_auth = {}
+
+        self.architect_auth = architect_auth if architect_auth is not None else aiconfig.get("architect_auth")
+        if self.architect_auth is None:
+            self.architect_auth = {}
+        elif not isinstance(self.architect_auth, dict):
+            self.architect_auth = {}
+
+        # Backward compatibility fallbacks: only inject api_key if the auth dict is empty/not configured
+        if self.engineer_key and not self.engineer_auth:
+            self.engineer_auth["api_key"] = self.engineer_key
+        if self.architect_key and not self.architect_auth:
+            self.architect_auth["api_key"] = self.architect_key
+
+        # Strategic Reasoning Engine (Architect) availability
+        is_architect_keyless = "vertex" in self.architect_model.lower() or "ollama" in self.architect_model.lower() or "local" in self.architect_model.lower()
+        self.has_architect = bool(self.architect_key or self.architect_auth or is_architect_keyless)
+
+        # Custom Trusted Commands Regexes
+        custom_trusted = aiconfig.get("trusted_commands", [])
+        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 [])
+        
+        # Limits
+        self.max_history = 30
+        self.max_truncate = 50000
+        self.soft_limit_iterations = 20  # Show warning and suggest Ctrl+C
+        self.hard_limit_iterations = 50  # Force stop
+
+        # External tool registry (populated by plugins via ClassHook.modify)
+        self.external_engineer_tools = []     # Tool defs for Engineer LLM
+        self.external_architect_tools = []    # Tool defs for Architect LLM
+        self.external_tool_handlers = {}      # {"tool_name": handler_callable}
+        self.tool_status_formatters = {}      # {"tool_name": formatter_callable}
+        self.engineer_prompt_extensions = []  # Extra text for engineer prompt
+        self.architect_prompt_extensions = [] # Extra text for architect prompt
+        
+        # MCP Manager
+        self.mcp_manager = MCPClientManager(self.config)
+
+        # Long-term memory
+        self.memory_path = os.path.join(self.config.defaultdir, "ai_memory.md")
+        self.long_term_memory = ""
+        if os.path.exists(self.memory_path):
+            try:
+                with open(self.memory_path, "r") as f:
+                    self.long_term_memory = f.read()
+            except FileNotFoundError:
+                self.long_term_memory = ""
+            except PermissionError as e:
+                self.console.print(f"[warning]Warning: Cannot read AI memory file: {e}[/warning]")
+            except Exception as e:
+                self.console.print(f"[warning]Warning: Failed to load AI memory: {e}[/warning]")
+
+        # Session Management
+        self.sessions_dir = os.path.join(self.config.defaultdir, "ai_sessions")
+        os.makedirs(self.sessions_dir, exist_ok=True)
+        self.session_id = getattr(self.config, "session_id", None)
+        self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json") if self.session_id else None
+
+        # Agnostic base prompts
+        architect_instructions = ""
+        if self.has_architect:
+            architect_instructions = """
+            CRITICAL - CONSULT vs ESCALATE:
+            - ALWAYS use 'consult_architect' for: Configuration planning, design decisions, complex troubleshooting.
+              Examples: "consultalo con el arquitecto", "preguntale al arquitecto", "que opina el arquitecto"
+              You stay in control and present the advice to the user.
+            
+            - ONLY use 'escalate_to_architect' when user EXPLICITLY asks to TALK to the Architect:
+              Examples: "quiero hablar con el arquitecto", "pasame con el arquitecto", "que me atienda el arquitecto"
+              After escalation, you hand over control completely.
+            
+            - DEFAULT: When in doubt, use 'consult_architect'. Escalation is rare.
+"""
+        else:
+            architect_instructions = """
+            CRITICAL - ARCHITECT UNAVAILABLE:
+            - The Strategic Reasoning Engine (Architect) is currently UNAVAILABLE because its API key or authentication is not configured.
+            - DO NOT attempt to consult or escalate to the architect.
+            - If the user asks to consult the architect, inform them that the Architect is offline and offer to help them directly to the best of your abilities.
+"""
+
+        self._engineer_base_prompt = dedent(f"""
+            Role: TECHNICAL EXECUTION ENGINE.
+            Expertise: Universal Networking (Cisco, Nokia, Juniper, 6wind, etc.).
+            
+            Rules:
+            - BE FAST AND EXTREMELY CONCISE: Provide direct answers. No filler words, no decorative language, no polite pleasantries. Save output tokens at all costs.
+            - KNOWLEDGE FIRST: For general networking questions (AS numbers, protocol details, standards, generic commands), use your internal knowledge. ONLY use tools when the user's specific infrastructure data is required.
+            - INVENTORY ONLY: 'run_commands', 'list_nodes', and 'get_node_info' are ONLY for interacting with the user's inventory.
+            - BROADCAST RESTRICTION: Avoid using filter '.*' in 'run_commands' unless the user explicitly requests a global action. Try to target specific nodes or groups based on the conversation.
+            - AUTONOMY: Proactively use iterative tool calls to find the root cause of infrastructure issues.
+            - BATCH OPERATIONS: When working on multiple devices, call tools in parallel.
+            - COMPLETE MISSIONS: Execute ALL steps of a mission before reporting back.
+            - DIAGRAM: Use ASCII art or Unicode box-drawing characters directly in your responses to visualize topologies or paths when helpful.
+            - EVIDENCE: Include 'Key Snippets' from tool outputs. Be token-efficient.
+            - LANGUAGE: You MUST respond in the same language used by the user in their question or instruction.
+            - 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."}}
+        """).strip()
+
+        self._architect_base_prompt = dedent(f"""
+            Role: STRATEGIC REASONING ENGINE.
+            Expertise: Network Architecture, Complex Troubleshooting, and Design Validation.
+            
+            Rules:
+            - CONCISENESS IS MANDATORY: Strip out fluff, decorative language, and filler words. Provide direct, tactical instructions and analysis to save output tokens.
+            - STRATEGY: Define technical missions for the Engineer. 
+            - DIAGRAM: Use ASCII art or Unicode box-drawing characters in your responses to visualize topologies, traffic paths, or logic flows.
+            - ENGINEER CAPABILITIES: Your Engineer can:
+                * Filter nodes (list_nodes), Run CLI commands (run_commands), Get metadata (get_node_info).
+            - ANALYSIS: Review technical findings to identify patterns or design failures.
+            - LANGUAGE: You MUST respond in the same language used by the user in their question or instruction.
+            - MEMORY: Update long-term facts ONLY when the user explicitly requests it.
+            
+            CRITICAL - EFFICIENT DELEGATION:
+            - Plan ALL tasks upfront before delegating.
+            - Delegate ONCE with a complete, detailed mission including ALL steps.
+            - Example: "List all routers matching 'border.*', then run 'show ip bgp summary' and 'show ip route' on each, then analyze the outputs."
+            - DO NOT delegate multiple times for the same goal. Batch everything into ONE mission.
+            - Wait for Engineer's complete report before responding to user.
+            
+            CRITICAL - RETURNING CONTROL:
+            - When your strategic analysis is complete and no further architectural decisions are needed, use 'return_to_engineer' to hand control back.
+            - The Engineer is better suited for ongoing technical execution and troubleshooting.
+            - Only stay in control if the user explicitly needs strategic oversight for multiple interactions.
+            
+            Network Context: {self.long_term_memory if self.long_term_memory else "Empty."}
+        """).strip()
+
+    def _local_confirm_handler(self, prompt, default="n"):
+        """Default confirmation handler using rich.prompt."""
+        from rich.prompt import Prompt
+        return Prompt.ask(prompt, default=default)
+
+    @property
+    def engineer_system_prompt(self):
+        """Build engineer system prompt with plugin extensions."""
+        if self.engineer_prompt_extensions:
+            extensions = "\n".join(self.engineer_prompt_extensions)
+            return self._engineer_base_prompt + f"\n\nPlugin Capabilities:\n{extensions}"
+        return self._engineer_base_prompt
+
+    @property
+    def architect_system_prompt(self):
+        """Build architect system prompt with plugin extensions."""
+        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."
+        if self.architect_prompt_extensions:
+            extensions = "\n".join(self.architect_prompt_extensions)
+            return prompt + f"\n\nPlugin Capabilities:\n{extensions}"
+        return prompt
+
+    def register_ai_tool(self, tool_definition, handler, target="engineer", engineer_prompt=None, architect_prompt=None, status_formatter=None):
+        """Register an external tool for the AI system.
+
+        Args:
+            tool_definition (dict): OpenAI-compatible tool definition.
+            handler (callable): Function(ai_instance, **tool_args) -> str.
+            target (str): 'engineer', 'architect', or 'both'.
+            engineer_prompt (str): Extra text for engineer system prompt.
+            architect_prompt (str): Extra text for architect system prompt.
+            status_formatter (callable): Function(args_dict) -> status string.
+        """
+        name = tool_definition["function"]["name"]
+        
+        # Check if already registered to prevent duplicates
+        if target in ("engineer", "both"):
+            if not any(t["function"]["name"] == name for t in self.external_engineer_tools):
+                self.external_engineer_tools.append(tool_definition)
+        if target in ("architect", "both"):
+            if not any(t["function"]["name"] == name for t in self.external_architect_tools):
+                self.external_architect_tools.append(tool_definition)
+        
+        self.external_tool_handlers[name] = handler
+        
+        if engineer_prompt and engineer_prompt not in self.engineer_prompt_extensions:
+            self.engineer_prompt_extensions.append(engineer_prompt)
+        if architect_prompt and architect_prompt not in self.architect_prompt_extensions:
+            self.architect_prompt_extensions.append(architect_prompt)
+        if status_formatter:
+            self.tool_status_formatters[name] = status_formatter
+
+    def _stream_completion(self, model, messages, tools, api_key=None, status=None, label="", debug=False, chunk_callback=None, auth=None, **kwargs):
+        """Stream a completion call, rendering styled Markdown in real-time.
+
+        Returns (response, streamed) where:
+        - response: reconstructed ModelResponse (same as non-streaming)
+        - streamed: True if text was rendered to console during streaming
+        """
+        auth_dict = auth if auth is not None else {}
+        if api_key and "api_key" not in auth_dict:
+            auth_dict = auth_dict.copy()
+            auth_dict["api_key"] = api_key
+
+        stream_resp = completion(model=model, messages=messages, tools=tools, stream=True, **auth_dict, **kwargs)
+
+        chunks = []
+        full_content = ""
+        is_streaming_text = False
+        has_tool_calls = False
+        header_printed = False
+
+        # Determine styling based on current brain
+        role_label = "Network Architect" if "architect" in label.lower() else "Network Engineer"
+        alias = "architect" if "architect" in label.lower() else "engineer"
+        title = f"[bold {alias}]{role_label}[/bold {alias}]"
+        border = alias
+
+        try:
+            for chunk in stream_resp:
+                chunks.append(chunk)
+                delta = chunk.choices[0].delta
+
+                # Detect tool calls
+                if hasattr(delta, 'tool_calls') and delta.tool_calls:
+                    has_tool_calls = True
+
+                # Stream text content with styled rendering
+                if hasattr(delta, 'content') and delta.content:
+                    full_content += delta.content
+
+                    if chunk and chunk_callback:
+                        # Check for remote interruption during streaming
+                        if hasattr(self, "interrupted") and self.interrupted:
+                            raise KeyboardInterrupt
+                        chunk_callback(delta.content)
+
+                    if not chunk_callback:
+                        if not is_streaming_text:
+                            if status:
+                                try:
+                                    status.stop()
+                                except Exception:
+                                    pass
+                            
+                            # Create a stable, direct Console to bypass _ConsoleProxy recreation bugs
+                            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())
+                            
+                            stable_console.print(Rule(f"[bold {border}]{title}[/bold {border}]", style=border))
+                            header_printed = True
+                            md_parser = IncrementalMarkdownParser(console=stable_console)
+                            is_streaming_text = True
+                        
+                        md_parser.feed(delta.content)
+        except Exception as e:
+            if not chunks:
+                raise
+        finally:
+            if header_printed:
+                try:
+                    md_parser.flush()
+                    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=border))
+                except Exception:
+                    pass
+        
+        # Rebuild complete response from chunks
+        try:
+            response = stream_chunk_builder(chunks, messages=messages)
+        except Exception:
+            # Fallback: manual reconstruction if stream_chunk_builder fails
+            full_content_rebuilt = ""
+            tool_calls_map = {}
+            for c in chunks:
+                d = c.choices[0].delta
+                if hasattr(d, 'content') and d.content:
+                    full_content_rebuilt += d.content
+                if hasattr(d, 'tool_calls') and d.tool_calls:
+                    for tc in d.tool_calls:
+                        idx = tc.index
+                        if idx not in tool_calls_map:
+                            tool_calls_map[idx] = {"id": tc.id or "", "type": "function", "function": {"name": getattr(tc.function, 'name', '') or '', "arguments": getattr(tc.function, 'arguments', '') or ''}}
+                        else:
+                            if tc.id: tool_calls_map[idx]["id"] = tc.id
+                            if tc.function:
+                                if tc.function.name: tool_calls_map[idx]["function"]["name"] = tc.function.name
+                                if tc.function.arguments: tool_calls_map[idx]["function"]["arguments"] += tc.function.arguments
+            
+            # Build a minimal response-like object
+            class FakeFunc:
+                def __init__(self, name, arguments): self.name = name; self.arguments = arguments
+            class FakeTC:
+                def __init__(self, d): self.id = d["id"]; self.function = FakeFunc(d["function"]["name"], d["function"]["arguments"])
+                def model_dump(self, **kw): return {"id": self.id, "type": "function", "function": {"name": self.function.name, "arguments": self.function.arguments}}
+            class FakeMsg:
+                def __init__(self, content, tcs): self.content = content or None; self.tool_calls = tcs if tcs else None; self.role = "assistant"
+                def model_dump(self, **kw):
+                    d = {"role": "assistant", "content": self.content}
+                    if self.tool_calls: d["tool_calls"] = [tc.model_dump() for tc in self.tool_calls]
+                    return d
+            class FakeChoice:
+                def __init__(self, msg): self.message = msg
+            class FakeResp:
+                def __init__(self, choice): self.choices = [choice]; self.usage = None
+            
+            tcs = [FakeTC(tool_calls_map[i]) for i in sorted(tool_calls_map)] if tool_calls_map else None
+            response = FakeResp(FakeChoice(FakeMsg(full_content_rebuilt or full_content, tcs)))
+        
+        # Only count as "streamed" if we rendered text AND it was the final response (no tool calls)
+        streamed = is_streaming_text and not has_tool_calls
+        return response, streamed
+
+    def _sanitize_messages(self, messages):
+        """Sanitize message list for strict providers like Gemini.
+        
+        Ensures that:
+        1. Every assistant message with tool_calls is followed by ALL its tool responses
+        2. No user/system messages appear between tool_calls and tool responses
+        3. Orphaned tool_calls at the end are removed
+        4. Orphaned tool responses without a preceding tool_call are removed
+        5. Incompatible metadata like cache_control is stripped for non-Anthropic models
+        6. Enforces strict alternating history to prevent BadRequestError on Gemini.
+        """
+        if not messages:
+            return messages
+        
+        # Pre-process messages to pull text from list contents (Anthropic cache format) 
+        # and remove explicit cache keys.
+        pre_sanitized = []
+        for msg in messages:
+            m = msg.copy() if isinstance(msg, dict) else msg.model_dump(exclude_none=True)
+            
+            # Convert content list to plain string if it's a system message with caching metadata
+            if m.get('role') == 'system' and isinstance(m.get('content'), list):
+                if m['content'] and isinstance(m['content'][0], dict) and m['content'][0].get('text'):
+                    m['content'] = m['content'][0]['text']
+                else:
+                    m['content'] = ""
+
+            # Remove any explicit cache_control key anywhere
+            if 'cache_control' in m: del m['cache_control']
+            if isinstance(m.get('content'), list):
+                for item in m['content']:
+                    if isinstance(item, dict) and 'cache_control' in item: del item['cache_control']
+            
+            pre_sanitized.append(m)
+
+        sanitized = []
+        last_role = None
+        
+        i = 0
+        while i < len(pre_sanitized):
+            msg = pre_sanitized[i]
+            role = msg.get('role', '')
+            
+            if role == 'system':
+                sanitized.append(msg)
+                last_role = 'system'
+                i += 1
+                
+            elif role == 'user':
+                if last_role == 'user' and sanitized:
+                    # Combine consecutive user messages
+                    sanitized[-1]['content'] = str(sanitized[-1].get('content', '') or '') + '\n' + str(msg.get('content', '') or '')
+                else:
+                    sanitized.append(msg)
+                    last_role = 'user'
+                i += 1
+                
+            elif role == 'assistant':
+                has_tools = bool(msg.get('tool_calls'))
+                
+                # Gemini strict sequence: Assistant MUST be preceded by user or tool.
+                # If preceded by system, assistant, or if it's the very first message...
+                if last_role not in ('user', 'tool'):
+                    sanitized.append({"role": "user", "content": "[System sequence separator: History Truncated/Merged]"})
+                    last_role = 'user'
+                
+                if has_tools:
+                    # Look ahead for matching tool responses
+                    tool_responses = []
+                    j = i + 1
+                    while j < len(pre_sanitized):
+                        next_msg = pre_sanitized[j]
+                        if next_msg.get('role') == 'tool':
+                            tool_responses.append(next_msg)
+                            j += 1
+                        else:
+                            break
+                    
+                    if tool_responses:
+                        sanitized.append(msg)
+                        sanitized.extend(tool_responses)
+                        last_role = 'tool'
+                        i = j
+                    else:
+                        # Orphaned tool_calls with no responses - skip the assistant message
+                        # If we just added a dummy user message for this assistant, remove it too
+                        if sanitized and sanitized[-1].get('content') == "[System sequence separator: History Truncated/Merged]":
+                            sanitized.pop()
+                            last_role = sanitized[-1].get('role', '') if sanitized else None
+                        i += 1
+                else:
+                    sanitized.append(msg)
+                    last_role = 'assistant'
+                    i += 1
+                    
+            elif role == 'tool':
+                # Orphaned tool response (no preceding assistant with tool_calls) - skip
+                i += 1
+                
+            else:
+                sanitized.append(msg)
+                last_role = role
+                i += 1
+        
+        return sanitized
+
+    def _truncate(self, text, limit=None):
+        """Truncate text to specified limit, keeping head (60%) and tail (40%)."""
+        if not isinstance(text, str): return str(text)
+        final_limit = limit or self.max_truncate
+        if len(text) <= final_limit: return text
+        head_limit = int(final_limit * 0.6)
+        tail_limit = int(final_limit * 0.4)
+        return (text[:head_limit] + f"\n\n[... OUTPUT TRUNCATED ...]\n\n" + text[-tail_limit:])
+
+    def _print_debug_observation(self, fn, obs, status=None):
+        """Prints a tool observation in a readable way during debug mode."""
+        # Try to parse as JSON if it's a string
+        if isinstance(obs, str):
+            try:
+                obs_data = json.loads(obs)
+            except Exception:
+                obs_data = obs
+        else:
+            obs_data = obs
+        
+        if isinstance(obs_data, dict):
+            elements = []
+            for k, v in obs_data.items():
+                elements.append(Text(f"• {k}:", style="key"))
+                # Use Text for values to ensure newlines are rendered
+                val = str(v)
+                # If it's a multiline string from a delegation task, keep it clean
+                elements.append(Text(val))
+            
+            if not elements:
+                content = Text("Empty data set")
+            else:
+                # Add a small spacer instead of a Rule for cleaner look
+                from rich.console import Group
+                content = Group(*elements)
+        elif isinstance(obs_data, list):
+            content = Text("\n".join(f"• {item}" for item in obs_data))
+        else:
+            content = Text(str(obs_data))
+            
+        title = f"[bold]{fn}[/bold]"
+        
+        # Stop status before printing panel to avoid ghosting
+        if status:
+            try: status.stop()
+            except: pass
+            
+        self.console.print(Panel(content, title=title, border_style="ai_status"))
+        
+        # Resume status
+        if status:
+            try: status.start()
+            except: pass
+
+    def manage_memory_tool(self, content, action="append"):
+        """Save or update long-term memory. Only use when user explicitly requests it."""
+        if not content or not content.strip():
+            return "Error: Cannot save empty content to memory."
+        
+        try:
+            mode = "a" if action == "append" else "w"
+            os.makedirs(os.path.dirname(self.memory_path), exist_ok=True)
+            with open(self.memory_path, mode) as f:
+                timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
+                f.write(f"\n\n## {timestamp}\n{content.strip()}\n" if action == "append" else content)
+            
+            # Reload memory after update
+            with open(self.memory_path, "r") as f:
+                self.long_term_memory = f.read()
+            
+            return "Memory updated successfully."
+        except PermissionError as e:
+            return f"Error: Permission denied writing to memory file: {e}"
+        except Exception as e:
+            return f"Error updating memory: {str(e)}"
+
+
+    def list_nodes_tool(self, filter_pattern=".*"):
+        """List nodes matching the filter pattern. Returns metadata for <=5 nodes, names only for more."""
+        try:
+            matched_names = self.config._getallnodes(filter_pattern)
+            if not matched_names: return "No nodes found."
+            if len(matched_names) <= 5:
+                matched_data = self.config.getitems(matched_names, extract=True)
+                res = {}
+                for name, data in matched_data.items():
+                    os_tag = "unknown"
+                    if isinstance(data, dict):
+                        ts = data.get("tags")
+                        if isinstance(ts, dict): os_tag = ts.get("os", "unknown")
+                    res[name] = {"os": os_tag}
+                return res
+            return {"count": len(matched_names), "nodes": matched_names, "note": "Use 'get_node_info' for details."}
+        except Exception as e: 
+            return f"Error listing nodes: {str(e)}"
+
+    def _is_safe_command(self, cmd):
+        """Check if a command matches safe patterns."""
+        return any(re.match(pattern, cmd.strip(), re.IGNORECASE) for pattern in self.safe_commands)
+    
+    def run_commands_tool(self, nodes_filter, commands, status=None):
+        """Execute commands on nodes matching the filter. Native interactive confirmation for unsafe commands."""
+        # Handle if commands is a JSON string
+        if isinstance(commands, str):
+            try:
+                commands = json.loads(commands)
+            except ValueError:
+                commands = [c.strip() for c in commands.split('\n') if c.strip()]
+        
+        # Expand multi-line commands within a list (in case the AI packs them)
+        if isinstance(commands, list):
+            expanded_commands = []
+            for cmd in commands:
+                expanded_commands.extend([c.strip() for c in str(cmd).split('\n') if c.strip()])
+            commands = expanded_commands
+        else:
+            commands = [str(commands)]
+        
+        # Check command safety natively
+        if not self.trusted_session:
+            unsafe_commands = [cmd for cmd in commands if not self._is_safe_command(cmd)]
+            if unsafe_commands:
+                # Stop the spinner so prompt doesn't get messed up
+                if status: status.stop()
+                
+                # Show ALL commands with unsafe ones highlighted
+                formatted_cmds = []
+                for cmd in commands:
+                    if cmd in unsafe_commands:
+                        formatted_cmds.append(f"  • [warning]{cmd}[/warning]")
+                    else:
+                        formatted_cmds.append(f"  • {cmd}")
+                
+                panel_content = f"Target: {nodes_filter}\nCommands:\n" + "\n".join(formatted_cmds)
+                # Use print_important if available (for remote bridges) fallback to standard print
+                print_fn = getattr(self.console, "print_important", self.console.print)
+                print_fn(Panel(panel_content, title="[bold warning]⚠️ UNSAFE COMMANDS DETECTED[/bold warning]", border_style="warning"))
+                
+                try:
+                    user_resp = self.confirm_handler("[bold warning]Execute? (y: yes / n: no / a: allow all this session / <text>: feedback)[/bold warning]", default="n")
+                except KeyboardInterrupt:
+                    if status: status.update("[ai_status]Engineer: Resuming...")
+                    self.console.print("[fail]✗ Aborted by user (Ctrl+C).[/fail]")
+                    raise
+                
+                # Resume the spinner
+                if status: status.update("[ai_status]Engineer: Processing user response...")
+                
+                user_resp_lower = user_resp.strip().lower()
+                if user_resp_lower in ['a', 'allow']:
+                    self.trusted_session = True
+                    self.console.print("[pass]✓ Trust Mode Enabled. All future commands in this session will execute without confirmation.[/pass]")
+                elif user_resp_lower in ['y', 'yes']:
+                    self.console.print("[pass]✓ Executing...[/pass]")
+                elif user_resp_lower in ['n', 'no', '', 'cancel']:
+                    self.console.print("[fail]✗ Execution rejected by user.[/fail]")
+                    return "Error: User rejected execution."
+                else:
+                    self.console.print(f"[user_prompt]User feedback: [/user_prompt]{user_resp}")
+                    return f"User requested changes: {user_resp}. Please adjust the commands based on this feedback and try again."
+        
+        try:
+            matched_names = self.config._getallnodes(nodes_filter)
+            if not matched_names: return "No nodes found matching filter."
+            thisnodes_dict = self.config.getitems(matched_names, extract=True)
+            result = nodes(thisnodes_dict, config=self.config).run(commands)
+            return result
+        except Exception as e: 
+            return f"Error executing commands: {str(e)}"
+
+    def get_node_info_tool(self, node_name):
+        """Get detailed metadata for a specific node. Passwords are masked."""
+        try:
+            d = self.config.getitem(node_name, extract=True)
+            if 'password' in d: d['password'] = '***'
+            return d
+        except Exception as e: 
+            return f"Error getting node info: {str(e)}"
+
+    def _engineer_loop(self, task, status=None, debug=False, chat_history=None):
+        """Internal loop where the Engineer executes technical tasks for the Architect."""
+        # Cache optimization for the Engineer (Only for direct Anthropic, Vertex has different rules)
+        if "claude" in self.engineer_model.lower() and "vertex" not in self.engineer_model.lower():
+            messages = [{"role": "system", "content": [{"type": "text", "text": self.engineer_system_prompt, "cache_control": {"type": "ephemeral"}}]}]
+        else:
+            messages = [{"role": "system", "content": self.engineer_system_prompt}]
+            
+        if chat_history:
+            # Clean chat history from caching metadata if engineer is not a compatible Claude model
+            if "claude" not in self.engineer_model.lower() or "vertex" in self.engineer_model.lower():
+                messages.extend(self._sanitize_messages(chat_history[-5:]))
+            else:
+                messages.extend(chat_history[-5:])
+        
+        messages.append({"role": "user", "content": f"MISSION: {task}"})
+        
+        tools = self._get_engineer_tools()
+        usage = {"input": 0, "output": 0, "total": 0}
+        iteration = 0
+        soft_limit_warned = False
+        
+        try:
+            # Set up remote interrupt callback if bridge is provided
+            if status and hasattr(status, "on_interrupt"):
+                status.on_interrupt = lambda: setattr(self, "interrupted", True)
+
+            while iteration < self.hard_limit_iterations:
+                iteration += 1
+                
+                # Check for interruption
+                if self.interrupted:
+                    raise KeyboardInterrupt
+                
+                if status and not chat_history:
+                    status_text = f"[ai_status]Engineer: Analyzing mission... (step {iteration})"
+                    if iteration >= self.soft_limit_iterations:
+                        status_text += " [warning]⚠ Taking longer than expected (Ctrl+C to interrupt)[/warning]"
+                    status.update(status_text)
+                
+                try:
+                    safe_messages = self._sanitize_messages(messages)
+                    response = completion(model=self.engineer_model, messages=safe_messages, tools=tools, **self.engineer_auth)
+                except Exception as e:
+                    if status: status.stop()
+                    raise ValueError(f"Engineer failed to connect: {str(e)}")
+                
+                if hasattr(response, "usage") and response.usage:
+                    usage["input"] += getattr(response.usage, "prompt_tokens", 0)
+                    usage["output"] += getattr(response.usage, "completion_tokens", 0)
+                    usage["total"] += getattr(response.usage, "total_tokens", 0)
+
+                resp_msg = response.choices[0].message
+                msg_dict = resp_msg.model_dump(exclude_none=True)
+                if msg_dict.get("tool_calls") and msg_dict.get("content") == "": msg_dict["content"] = None
+                messages.append(msg_dict)
+
+                if not resp_msg.tool_calls: break
+                for tc in resp_msg.tool_calls:
+                    fn, args = tc.function.name, json.loads(tc.function.arguments)
+                    
+                    # Real-time notification of the technical task (Only if not in Architect loop)
+                    if status and not chat_history:
+                        s_text = ""
+                        if fn == "list_nodes": s_text = f"[ai_status]Engineer: [SEARCH] {args.get('filter_pattern','.*')}"
+                        elif fn == "run_commands": 
+                            cmds = args.get('commands', [])
+                            cmd_str = cmds[0] if cmds else ""
+                            s_text = f"[ai_status]Engineer: [CMD] {cmd_str}"
+                        elif fn == "get_node_info": s_text = f"[ai_status]Engineer: [INSPECT] {args.get('node_name','')}"
+                        elif fn.startswith("mcp_"):
+                            server = fn.split("__")[0].replace("mcp_", "")
+                            tool = fn.split("__")[1] if "__" in fn else fn
+                            s_text = f"[ai_status]Engineer: [MCP:{server}] {tool}"
+                        elif fn in self.tool_status_formatters: s_text = self.tool_status_formatters[fn](args)
+                        
+                        if s_text:
+                            if iteration >= self.soft_limit_iterations:
+                                s_text += " [warning]⚠ Taking longer than expected (Ctrl+C to interrupt)[/warning]"
+                            status.update(s_text)
+
+                    if debug:
+                        self._print_debug_observation(f"Decision: {fn}", args, status=status)
+                    
+                    if fn == "list_nodes": obs = self.list_nodes_tool(**args)
+                    elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
+                    elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
+                    elif fn.startswith("mcp_"):
+                        obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
+                    elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
+                    else: obs = f"Error: Unknown tool '{fn}'."
+                    
+                    if debug:
+                        self._print_debug_observation(f"Observation: {fn}", obs, status=status)
+                    
+                    # Ensure observation is a string and truncated for the LLM
+                    obs_str = obs if isinstance(obs, str) else json.dumps(obs)
+                    messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": self._truncate(obs_str)})
+            
+            if iteration >= self.hard_limit_iterations:
+                self.console.print(f"[error]⛔ Engineer reached hard limit ({self.hard_limit_iterations} steps). Forcing stop.[/error]")
+            
+            if debug and resp_msg.content:
+                self.console.print(Panel(Text(resp_msg.content), title="[bold engineer]Engineer Final Report to Architect[/bold engineer]", border_style="engineer"))
+            
+            return resp_msg.content, usage
+        except Exception as e:
+            return f"Engineer failed: {str(e)}", usage
+
+    def _get_engineer_tools(self, os_filter: str = None):
+        """Define tools available to the Engineer."""
+        base_tools = [
+            {"type": "function", "function": {"name": "list_nodes", "description": "[Universal Platform] Lists available nodes in the inventory.", "parameters": {"type": "object", "properties": {"filter_pattern": {"type": "string", "description": "Regex to filter nodes (e.g. '.*', 'border.*')."}}}}},
+            {"type": "function", "function": {"name": "run_commands", "description": "[Universal Platform] Runs one or more commands on matched nodes. MANDATORY: You MUST call 'list_nodes' first to verify the target list.", "parameters": {"type": "object", "properties": {"nodes_filter": {"type": "string", "description": "Exact node name or verified filter pattern."}, "commands": {"type": "array", "items": {"type": "string"}, "description": "List of commands (e.g. ['show ip route', 'show int desc'])."}}, "required": ["nodes_filter", "commands"]}}},
+            {"type": "function", "function": {"name": "get_node_info", "description": "[Universal Platform] Gets full metadata for a specific node.", "parameters": {"type": "object", "properties": {"node_name": {"type": "string"}}, "required": ["node_name"]}}}
+        ]
+        
+        # Add dynamic tools from MCP
+        try:
+            mcp_tools = run_ai_async(self.mcp_manager.get_tools_for_llm(os_filter=os_filter)).result(timeout=10)
+            base_tools.extend(mcp_tools)
+        except Exception as e:
+            # Silently fail for LLM tools
+            pass
+
+        if self.architect_key:
+            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"]}}}
+            ])
+            
+        # Deduplicate by name to prevent Gemini BadRequestError
+        all_tools = base_tools + self.external_engineer_tools
+        seen_names = set()
+        unique_tools = []
+        for t in all_tools:
+            name = t["function"]["name"]
+            if name not in seen_names:
+                unique_tools.append(t)
+                seen_names.add(name)
+        return unique_tools
+
+    def _get_architect_tools(self):
+        """Define tools available to the Strategic Reasoning Engine."""
+        base_tools = [
+            {"type": "function", "function": {"name": "delegate_to_engineer", "description": "Delegates a technical mission to the Engineer.", "parameters": {"type": "object", "properties": {"task": {"type": "string", "description": "Detailed technical mission or goal."}}, "required": ["task"]}}},
+            {"type": "function", "function": {"name": "return_to_engineer", "description": "Return control to the Engineer. Use this when your strategic analysis is complete and the Engineer should handle the rest of the conversation.", "parameters": {"type": "object", "properties": {"summary": {"type": "string", "description": "Brief summary of your analysis to hand over to the Engineer."}}, "required": ["summary"]}}},
+            {"type": "function", "function": {"name": "manage_memory_tool", "description": "Saves information to long-term memory. MANDATORY: Only use this if the user explicitly asks to remember or save something.", "parameters": {"type": "object", "properties": {"content": {"type": "string"}, "action": {"type": "string", "enum": ["append", "replace"]}}, "required": ["content"]}}}
+        ]
+        if getattr(self, "one_shot", False):
+            base_tools = [t for t in base_tools if t["function"]["name"] not in ("delegate_to_engineer", "return_to_engineer")]
+        
+        all_tools = base_tools + self.external_architect_tools
+        seen_names = set()
+        unique_tools = []
+        for t in all_tools:
+            name = t["function"]["name"]
+            if name not in seen_names:
+                unique_tools.append(t)
+                seen_names.add(name)
+        return unique_tools
+
+    def _get_sessions(self):
+        """Returns a list of session metadata sorted by date."""
+        sessions = []
+        if not os.path.exists(self.sessions_dir):
+            return []
+        for f in os.listdir(self.sessions_dir):
+            if f.endswith(".json"):
+                path = os.path.join(self.sessions_dir, f)
+                try:
+                    with open(path, "r") as fs:
+                        data = json.load(fs)
+                        sessions.append({
+                            "id": f[:-5],
+                            "title": data.get("title", "Untitled Session"),
+                            "created_at": data.get("created_at", "Unknown"),
+                            "model": data.get("model", "Unknown"),
+                            "path": path
+                        })
+                except Exception:
+                    continue
+        return sorted(sessions, key=lambda x: x["created_at"], reverse=True)
+
+    def list_sessions(self, limit=20):
+        """Prints a list of sessions using printer.table."""
+        sessions = self._get_sessions()
+        if not sessions:
+            printer.info("No saved AI sessions found.")
+            return
+        
+        total = len(sessions)
+        if limit and total > limit:
+            sessions = sessions[:limit]
+            
+        columns = ["ID", "Title", "Created At", "Model"]
+        rows = [[s["id"], s["title"], s["created_at"], s["model"]] for s in sessions]
+        
+        title = "AI Persisted Sessions"
+        if limit and total > limit:
+            title += f" (Showing last {limit} of {total})"
+            
+        printer.table(title, columns, rows)
+        if limit and total > limit:
+            printer.info(f"Use '--list --all' (if supported) or check the sessions directory to see all {total} sessions.")
+
+    def load_session_data(self, session_id):
+        """Loads a session's raw data by ID."""
+        path = os.path.join(self.sessions_dir, f"{session_id}.json")
+        if os.path.exists(path):
+            try:
+                with open(path, "r") as f:
+                    data = json.load(f)
+                    self.session_id = session_id
+                    self.session_path = path
+                    return data
+            except Exception as e:
+                printer.error(f"Failed to load session {session_id}: {e}")
+        return None
+
+    def delete_session(self, session_id):
+        """Deletes a session by ID."""
+        path = os.path.join(self.sessions_dir, f"{session_id}.json")
+        if os.path.exists(path):
+            os.remove(path)
+            printer.success(f"Session {session_id} deleted.")
+        else:
+            printer.error(f"Session {session_id} not found.")
+
+    def get_last_session_id(self):
+        """Returns the ID of the most recent session."""
+        sessions = self._get_sessions()
+        return sessions[0]["id"] if sessions else None
+
+    def _generate_session_id(self, query):
+        """Generates a unique session ID based on timestamp and a random suffix."""
+        ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
+        suffix = secrets.token_hex(2)
+        return f"{ts}-{suffix}"
+
+    def save_session(self, history, title=None, model=None):
+        """Saves current history to the session file."""
+        if not self.session_id:
+            # Generate ID from first user query if available
+            first_user_msg = next((m["content"] for m in history if m["role"] == "user"), "new-session")
+            self.session_id = self._generate_session_id(first_user_msg)
+            self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json")
+        elif not self.session_path:
+            self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json")
+
+        # If it's a new file, we might want to set a better title
+        if not os.path.exists(self.session_path) and not title:
+            raw_title = next((m["content"] for m in history if m["role"] == "user"), "New Session")
+            # Clean title: remove newlines, multiple spaces
+            clean_title = " ".join(raw_title.split())
+            if len(clean_title) > 40:
+                title = clean_title[:37].strip() + "..."
+            else:
+                title = clean_title
+
+        try:
+            # Read existing metadata if it exists
+            metadata = {}
+            if os.path.exists(self.session_path):
+                with open(self.session_path, "r") as f:
+                    metadata = json.load(f)
+            
+            metadata.update({
+                "id": self.session_id,
+                "title": title or metadata.get("title", "New Session"),
+                "created_at": metadata.get("created_at", datetime.datetime.now().isoformat()),
+                "updated_at": datetime.datetime.now().isoformat(),
+                "model": model or metadata.get("model", self.engineer_model),
+                "history": history
+            })
+
+            with open(self.session_path, "w") as f:
+                json.dump(metadata, f, indent=4)
+        except Exception as e:
+            printer.error(f"Failed to save session: {e}")
+
+        except Exception as e:
+            printer.error(f"Failed to save session: {e}")
+
+    @MethodHook
+    def ask(self, user_input, dryrun=False, chat_history=None, status=None, debug=False, stream=True, session_id=None, chunk_callback=None):
+        is_engineer_keyless = "vertex" in self.engineer_model.lower() or "ollama" in self.engineer_model.lower() or "local" in self.engineer_model.lower()
+        if not self.engineer_key and not self.engineer_auth and not is_engineer_keyless:
+            raise ValueError("Engineer API key or authentication not configured. Use 'connpy config --engineer-auth <auth>' to set it.")
+
+        def update_status(text):
+            if not status:
+                return
+            if iteration >= self.soft_limit_iterations:
+                warning_suffix = " [warning]⚠ Taking longer than expected (Ctrl+C to interrupt)[/warning]"
+                if warning_suffix not in text:
+                    text += warning_suffix
+            status.update(text)
+            
+        if chat_history is None: chat_history = []
+        
+        # Load session if provided and history is empty
+        if session_id:
+            # Force the session_id even if it doesn't exist yet
+            self.session_id = session_id
+            self.session_path = os.path.join(self.sessions_dir, f"{session_id}.json")
+            
+            if not chat_history:
+                session_data = self.load_session_data(session_id)
+                if session_data:
+                    chat_history = session_data.get("history", [])
+                # If we loaded history, the caller might need it back
+                # But typically ask() is called in a loop with an external history object
+
+        usage = {"input": 0, "output": 0, "total": 0}
+        
+        # 1. Initial Role Selector (Sticky Brain)
+        explicit_architect = re.match(r'^(architect|arquitecto|@architect)[:\s]', user_input, re.I)
+        explicit_engineer = re.match(r'^(engineer|ingeniero|@engineer)[:\s]', user_input, re.I)
+        
+        if explicit_architect:
+            current_brain = "architect"
+        elif explicit_engineer:
+            current_brain = "engineer"
+        else:
+            # Sticky Brain: Detect if the Architect was in control in recent history
+            is_architect_active = False
+            for msg in reversed(chat_history[-5:]):
+                tcs = msg.get('tool_calls') if isinstance(msg, dict) else getattr(msg, 'tool_calls', None)
+                if tcs:
+                    for tc in tcs:
+                        fn = tc.get('function', {}).get('name') if isinstance(tc, dict) else getattr(getattr(tc, 'function', None), 'name', '')
+                        # Architect stays in control if delegating tasks or if Engineer escalated to them
+                        # consult_architect is just Engineer asking for advice - Engineer keeps control
+                        if fn in ['delegate_to_engineer', 'escalate_to_architect']:
+                            is_architect_active = True; break
+                if is_architect_active: break
+            current_brain = "architect" if is_architect_active else "engineer"
+        
+        # 2. Message preparation and cleaning
+        clean_input = re.sub(r'^(architect|arquitecto|engineer|ingeniero|@architect|@engineer)[:\s]+', '', user_input, flags=re.IGNORECASE).strip()
+        
+        system_prompt = self.architect_system_prompt if current_brain == "architect" else self.engineer_system_prompt
+        tools = self._get_architect_tools() if current_brain == "architect" else self._get_engineer_tools()
+        model = self.architect_model if current_brain == "architect" else self.engineer_model
+        key = self.architect_key if current_brain == "architect" else self.engineer_key
+        current_auth = self.architect_auth if current_brain == "architect" else self.engineer_auth
+
+        # Optimized structure for Prompt Caching (Only for direct Anthropic, Vertex has different rules)
+        if "claude" in model.lower() and "vertex" not in model.lower():
+            messages = [{"role": "system", "content": [{"type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}}]}]
+        else:
+            messages = [{"role": "system", "content": system_prompt}]
+        
+        # History interleaving
+        last_role = "system"
+        # Sanitize history if the current target model is not compatible with cache_control
+        history_to_process = chat_history[-self.max_history:]
+        if "claude" not in model.lower() or "vertex" in model.lower():
+            history_to_process = self._sanitize_messages(history_to_process)
+
+        for msg in history_to_process:
+            m = msg if isinstance(msg, dict) else msg.model_dump(exclude_none=True)
+            role = m.get('role')
+            if role == last_role and role == 'user':
+                messages[-1]['content'] += "\n" + (m.get('content') or "")
+                continue
+            if role == 'assistant' and m.get('tool_calls') and m.get('content') == "": m['content'] = None
+            messages.append(m)
+            last_role = role
+
+        if last_role == 'user': messages[-1]['content'] += "\n" + clean_input
+        else: messages.append({"role": "user", "content": clean_input})
+
+        # 3. Execution loop
+        iteration = 0
+        try:
+            # Set up remote interrupt callback if bridge is provided
+            if status and hasattr(status, "on_interrupt"):
+                status.on_interrupt = lambda: setattr(self, "interrupted", True)
+
+            while iteration < self.hard_limit_iterations:
+                iteration += 1
+                
+                # Check for interruption
+                if self.interrupted:
+                    raise KeyboardInterrupt
+                
+                # Soft limit warning - handled inline within update_status
+                
+                label = "[architect][bold]Architect[/bold][/architect]" if current_brain == "architect" else "[engineer][bold]Engineer[/bold][/engineer]"
+                if status: 
+                    # Notify responder identity for web/remote clients
+                    if getattr(status, "is_web", False) or getattr(status, "is_remote", False):
+                        status.update(f"__RESPONDER__:{current_brain}")
+                    update_status(f"{label} is thinking... (step {iteration})")
+                
+                streamed_response = False
+                try:
+                    safe_messages = self._sanitize_messages(messages)
+                    if stream:
+                        response, streamed_response = self._stream_completion(
+                            model=model, messages=safe_messages, tools=tools, auth=current_auth,
+                            status=status, label=label, debug=debug, num_retries=3,
+                            chunk_callback=chunk_callback
+                        )
+                    else:
+                        response = completion(model=model, messages=safe_messages, tools=tools, num_retries=3, **current_auth)
+                except Exception as e:
+                    if current_brain == "architect":
+                        if status: update_status("[unavailable]Architect unavailable! Falling back to Engineer...")
+                        # Preserve context when falling back - use clean_input directly
+                        current_brain = "engineer"
+                        model = self.engineer_model
+                        tools = self._get_engineer_tools()
+                        key = self.engineer_key
+                        current_auth = self.engineer_auth
+                        # Rebuild messages with Engineer system prompt and original user request
+                        messages = [{"role": "system", "content": self.engineer_system_prompt}]
+                        # Add chat history if exists (excluding system prompt)
+                        if chat_history:
+                            for msg in chat_history[-self.max_history:]:
+                                if msg.get('role') != 'system':
+                                    messages.append(msg)
+                        # Add current user request with a system note to prevent infinite escalation loops
+                        fallback_msg = clean_input + "\n\n[SYSTEM NOTE: The Architect is currently unavailable/failed to respond. You must handle the user's request directly as the Network Engineer. Do NOT attempt to escalate to the Architect again.]"
+                        messages.append({"role": "user", "content": fallback_msg})
+                        continue
+                    else: 
+                        return {"response": f"Error: Both engines failed. {str(e)}", "chat_history": messages[1:], "usage": usage}
+                
+                if hasattr(response, "usage") and response.usage:
+                    usage["input"] += getattr(response.usage, "prompt_tokens", 0)
+                    usage["output"] += getattr(response.usage, "completion_tokens", 0)
+                    usage["total"] += getattr(response.usage, "total_tokens", 0)
+
+                resp_msg = response.choices[0].message
+                msg_dict = resp_msg.model_dump(exclude_none=True)
+                if msg_dict.get("tool_calls") and msg_dict.get("content") == "": msg_dict["content"] = None
+                messages.append(msg_dict)
+
+                if debug and resp_msg.content and not streamed_response:
+                    # In CLI debug mode, only print intermediate reasoning if there are tool calls AND it wasn't already streamed.
+                    # If there are no tool calls, this content is the final answer and will be printed by the caller.
+                    if resp_msg.tool_calls:
+                        if status:
+                            try: status.stop()
+                            except: pass
+                        self.console.print(Panel(Markdown(resp_msg.content), title=f"[{current_brain}][bold]{label} Reasoning[/bold][/{current_brain}]", border_style="architect" if current_brain == "architect" else "engineer"))
+                        if status:
+                            try: status.start()
+                            except: pass
+
+                if not resp_msg.tool_calls: break
+                
+                # Track if we need to inject a user message after all tool responses
+                pending_user_message = None
+                
+                for tc in resp_msg.tool_calls:
+                    fn, args = tc.function.name, json.loads(tc.function.arguments)
+                    
+                    # Validate tool access based on current brain
+                    if fn in ['delegate_to_engineer'] and current_brain != "architect":
+                        obs = f"Error: Tool '{fn}' is only available to the Architect (Architect). You are the Engineer (Engineer). Use 'run_commands' directly to execute configuration."
+                        messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": obs})
+                        continue
+                    
+                    if status:
+                        if fn == "delegate_to_engineer": update_status(f"[architect]Architect: [DELEGATING MISSION] {args.get('task','')[:40]}...")
+                        elif fn == "manage_memory_tool": update_status(f"[architect]Architect: [UPDATING MEMORY]")
+
+                    if debug:
+                        self._print_debug_observation(f"Decision: {fn}", args, status=status)
+
+                    if fn == "delegate_to_engineer":
+                        obs, eng_usage = self._engineer_loop(args["task"], status=status, debug=debug, chat_history=messages[:-1])
+                        usage["input"] += eng_usage["input"]; usage["output"] += eng_usage["output"]; usage["total"] += eng_usage["total"]
+                    elif fn == "consult_architect":
+                        if status: update_status("[architect]Engineer consulting Architect...")
+                        try:
+                            # Consultation only - Engineer stays in control
+                            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
+                            )
+                            obs = claude_resp.choices[0].message.content
+                            if debug:
+                                if status:
+                                    try: status.stop()
+                                    except: pass
+                                self.console.print(Panel(Markdown(obs), title="[architect]Architect Consultation[/architect]", border_style="architect"))
+                                if status:
+                                    try: status.start()
+                                    except: pass
+                        except Exception as e:
+                            if status: update_status("[unavailable]Architect unavailable! Engineer continuing alone...")
+                            obs = f"Architect unavailable ({str(e)}). Proceeding with your best technical judgment."
+                    
+                    elif fn == "escalate_to_architect":
+                        if status: update_status("[architect]Transferring control to Architect...")
+                        # Full escalation - Architect takes over
+                        current_brain = "architect"
+                        model = self.architect_model
+                        tools = self._get_architect_tools()
+                        key = self.architect_key
+                        current_auth = self.architect_auth
+                        messages[0] = {"role": "system", "content": self.architect_system_prompt}
+                        # Prepare handover context to inject AFTER all tool responses
+                        handover_msg = f"HANDOVER FROM EXECUTION ENGINE\n\nReason: {args['reason']}\n\nContext: {args['context']}\n\nYou are now in control of this conversation."
+                        pending_user_message = handover_msg
+                        obs = "Control transferred to Architect. Handover context will be provided."
+                        if debug:
+                            if status:
+                                try: status.stop()
+                                except: pass
+                            self.console.print(Panel(Text(handover_msg), title="[architect]Escalation to Architect[/architect]", border_style="architect"))
+                            if status:
+                                try: status.start()
+                                except: pass
+                    
+                    elif fn == "return_to_engineer":
+                        if status: update_status("[engineer]Transferring control back to Engineer...")
+                        # Architect returns control to Engineer
+                        current_brain = "engineer"
+                        model = self.engineer_model
+                        tools = self._get_engineer_tools()
+                        key = self.engineer_key
+                        current_auth = self.engineer_auth
+                        messages[0] = {"role": "system", "content": self.engineer_system_prompt}
+                        # Prepare handover context to inject AFTER all tool responses
+                        handover_msg = f"HANDOVER FROM ARCHITECT\n\nSummary: {args['summary']}\n\nYou are now back in control. Continue handling the user's requests."
+                        pending_user_message = handover_msg
+                        obs = "Control returned to Engineer. Handover summary will be provided."
+                        if debug:
+                            if status:
+                                try: status.stop()
+                                except: pass
+                            self.console.print(Panel(Text(handover_msg), title="[engineer]Return to Engineer[/engineer]", border_style="engineer"))
+                            if status:
+                                try: status.start()
+                                except: pass
+                    
+                    elif fn == "list_nodes": obs = self.list_nodes_tool(**args)
+                    elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
+                    elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
+                    elif fn == "manage_memory_tool": obs = self.manage_memory_tool(**args)
+                    elif fn.startswith("mcp_"):
+                        obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
+                    elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
+                    else: obs = f"Error: {fn} unknown."
+
+                    if debug and fn not in ["delegate_to_engineer", "consult_architect", "escalate_to_architect", "return_to_engineer"]:
+                        self._print_debug_observation(f"Observation: {fn}", obs, status=status)
+
+                    # Ensure observation is a string and truncated for the LLM
+                    obs_str = obs if isinstance(obs, str) else json.dumps(obs)
+                    messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": self._truncate(obs_str)})                
+                # Inject pending user message AFTER all tool responses are added
+                if pending_user_message:
+                    messages.append({"role": "user", "content": pending_user_message})
+            
+            if iteration >= self.hard_limit_iterations:
+                self.console.print(f"[error]⛔ Agent reached hard limit ({self.hard_limit_iterations} steps). Forcing stop to prevent infinite loop.[/error]")
+                # Only inject user message if we're not in the middle of tool calls
+                last_msg = messages[-1] if messages else {}
+                if last_msg.get("role") != "assistant" or not last_msg.get("tool_calls"):
+                    messages.append({"role": "user", "content": "Hard iteration limit reached. Please provide a summary of your findings so far."})
+                    try:
+                        safe_messages = self._sanitize_messages(messages)
+                        response = completion(model=model, messages=safe_messages, tools=[], **current_auth)
+                        resp_msg = response.choices[0].message
+                        messages.append(resp_msg.model_dump(exclude_none=True))
+                    except Exception as e:
+                        if status:
+                            update_status(f"[error]Error fetching summary: {e}[/error]")
+                        printer.warning(f"Failed to fetch final summary from LLM: {e}")
+        except KeyboardInterrupt:
+            if status: status.update("[error]Interrupted! Closing pending tasks...")
+            last_msg = messages[-1]
+            if last_msg.get("tool_calls"):
+                for tc in last_msg["tool_calls"]:
+                    messages.append({"tool_call_id": tc.get("id"), "role": "tool", "name": tc.get("function", {}).get("name"), "content": "Operation cancelled by user."})
+            
+            # Use a fresh list for the summary call to avoid history corruption
+            summary_messages = list(messages)
+            summary_messages.append({"role": "user", "content": "USER INTERRUPTED. Briefly summarize what you were doing and stop."})
+            try:
+                safe_messages = self._sanitize_messages(summary_messages)
+                # Use tools=None to force a text summary during interruption
+                response = completion(model=model, messages=safe_messages, tools=None, **current_auth)
+                resp_msg = response.choices[0].message
+                messages.append(resp_msg.model_dump(exclude_none=True))
+                
+                # IMPORTANT: Manually trigger callback for the summary so Web UI sees it
+                if chunk_callback and resp_msg.content:
+                    chunk_callback(resp_msg.content)
+            except Exception:
+                error_msg = "Operation interrupted by user. Summary unavailable."
+                messages.append({"role": "assistant", "content": error_msg})
+                if chunk_callback:
+                    chunk_callback(error_msg)
+        finally:
+            # Auto-save session
+            self.save_session(messages, model=model)
+
+        return {
+            "response": messages[-1].get("content"), 
+            "chat_history": messages[1:], 
+            "app_related": True, 
+            "usage": usage,
+            "responder": current_brain,  # "architect" or "engineer"
+            "streamed": streamed_response
+        }
+
+    @MethodHook
+    async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
+        import json
+        import re
+        from litellm import acompletion
+        import asyncio
+        import warnings
+        import aiohttp
+        
+        # Suppress unawaited coroutine warnings from LiteLLM's internal streaming logic during sudden cancellation
+        warnings.filterwarnings("ignore", message="coroutine '.*async_streaming.*' was never awaited", category=RuntimeWarning)
+        
+        node_info = node_info or {}
+        os_info = node_info.get("os", "unknown")
+        node_name = node_info.get("name", "unknown")
+        persona = node_info.get("persona", "engineer")
+        memories = node_info.get("memories", [])
+        
+        vendor_reference = ""
+        if os_info and os_info != "unknown":
+            try:
+                os_filename = os_info.lower().replace(" ", "_")
+                ref_path = os.path.join(self.config.defaultdir, "ai_references", f"{os_filename}.md")
+                if os.path.exists(ref_path):
+                    with open(ref_path, "r") as f:
+                        vendor_reference = f.read().strip()
+            except Exception:
+                pass
+        
+        if persona == "architect":
+            system_prompt = f"""Role: NETWORK ARCHITECT. You act as a senior strategic advisor during a live SSH session.
+Rules:
+1. MANDATORY: You MUST respond in the same language used by the user in their question.
+2. Answer the user's question directly and EXCLUSIVELY based on the Terminal Context. 
+3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information.
+4. Focus on the "why" and "how". Analyze topologies, design patterns, and validate configurations.
+5. Do NOT provide commands to execute unless specifically requested. Instead, explain the consequences and best practices.
+6. Keep your guide concise and authoritative.
+7. You MUST output your response in the following strict format:
+<guide>
+Your brief tactical guide in markdown.
+</guide>
+<commands>
+</commands>
+<risk>
+low
+</risk>
+8. Risk level is usually "low" for read-only/no commands.
+
+Terminal Context:
+{terminal_buffer}
+
+Device OS: {os_info}
+Node: {node_name}"""
+        else:
+            system_prompt = f"""Role: TERMINAL COPILOT. You assist a network engineer during a live SSH session.
+Rules:
+1. MANDATORY: You MUST respond in the same language used by the user in their question.
+2. EXTREMELY IMPORTANT: Answer EXCLUSIVELY based on the provided Terminal Context. 
+3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information. Instead, explicitly state that you don't see the data and offer the correct CLI commands to retrieve it.
+4. If the user asks you to analyze, parse, or extract data from the Terminal Context, DO IT directly in the <guide> section (you can use markdown tables or lists). Do NOT just give them a command to do it themselves.
+5. If the user wants to execute an action, provide the required CLI commands inside a <commands> block, one command per line. If no commands are needed, leave it empty or omit the block.
+6. ULTRA-CONCISE. Keep your guide to the point.
+7. You MUST output your response in the following strict format:
+<guide>
+Your brief tactical guide in markdown. 3-4 sentences max.
+</guide>
+<commands>
+command 1
+command 2
+</commands>
+<risk>
+low, high, or destructive
+</risk>
+8. Risk level: "low" for read-only/no commands, "high" for config changes, "destructive" for potentially dangerous ops.
+
+Terminal Context:
+{terminal_buffer}
+
+Device OS: {os_info}
+Node: {node_name}"""
+        
+        if vendor_reference:
+            system_prompt += f"\n\nVendor Command Reference:\n{vendor_reference}"
+
+        if memories:
+            system_prompt += "\n\nSession Memory (Important Facts):\n"
+            for m in memories:
+                system_prompt += f"- {m}\n"
+
+        # Fetch MCP tools for the current OS
+        mcp_tools = []
+        try:
+            mcp_tools = await self.mcp_manager.get_tools_for_llm(os_filter=os_info)
+        except Exception:
+            pass
+            
+        if mcp_tools:
+            system_prompt += f"\n\nAvailable MCP Tools: {', '.join([t['function']['name'] for t in mcp_tools])}"
+            system_prompt += "\nUse these tools to validate syntax or find exact commands if needed before providing the final guide."
+
+        messages = [
+            {"role": "system", "content": system_prompt},
+            {"role": "user", "content": user_question}
+        ]
+
+        iteration = 0
+        max_iterations = 5 # Allow up to 5 iterations for tool usage
+        
+        # Use models based on persona
+        current_model = self.architect_model if persona == "architect" else self.engineer_model
+        current_key = self.architect_key if persona == "architect" else self.engineer_key
+        current_auth = self.architect_auth if persona == "architect" else self.engineer_auth
+
+        try:
+            while iteration < max_iterations:
+                iteration += 1
+
+                response = await acompletion(
+                    model=current_model,
+                    messages=messages,
+                    tools=mcp_tools if mcp_tools else None,
+                    stream=True,
+                    **current_auth
+                )
+                
+                full_content = ""
+                streamed_guide = ""
+                tool_calls = []
+                
+                async for chunk in response:
+                    delta = chunk.choices[0].delta
+                    
+                    # Accumulate tool calls
+                    if hasattr(delta, 'tool_calls') and delta.tool_calls:
+                        for tc in delta.tool_calls:
+                            idx = tc.index
+                            if idx >= len(tool_calls):
+                                tool_calls.append({"id": tc.id, "type": "function", "function": {"name": tc.function.name or "", "arguments": tc.function.arguments or ""}})
+                            else:
+                                if tc.id: tool_calls[idx]["id"] = tc.id
+                                if tc.function.name: tool_calls[idx]["function"]["name"] = tc.function.name
+                                if tc.function.arguments: tool_calls[idx]["function"]["arguments"] += tc.function.arguments
+
+                    if hasattr(delta, 'content') and delta.content:
+                        full_content += delta.content
+                        
+                        if chunk_callback and not tool_calls: # Only stream if not using tools
+                            start_idx = full_content.find("<guide>")
+                            if start_idx != -1:
+                                after_start = full_content[start_idx + 7:]
+                                end_idx = after_start.find("</guide>")
+                                
+                                if end_idx != -1:
+                                    current_guide = after_start[:end_idx]
+                                else:
+                                    current_guide = after_start
+                                    if current_guide.endswith("<"): current_guide = current_guide[:-1]
+                                    elif current_guide.endswith("</"): current_guide = current_guide[:-2]
+                                    elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
+                                    elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
+                                    elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
+                                    elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
+                                    elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
+                                
+                                new_text = current_guide[len(streamed_guide):]
+                                if new_text:
+                                    chunk_callback(new_text)
+                                    streamed_guide += new_text
+
+                if not tool_calls:
+                    break
+                    
+                # Execute tool calls
+                messages.append({"role": "assistant", "content": full_content or None, "tool_calls": tool_calls})
+                for tc in tool_calls:
+                    fn = tc["function"]["name"]
+                    args = json.loads(tc["function"]["arguments"])
+                    
+                    if "mcp_" in fn:
+                        try:
+                            obs = await asyncio.wait_for(self.mcp_manager.call_tool(fn, args), timeout=30.0)
+                        except Exception as e:
+                            obs = f"Error calling MCP tool: {e}"
+                    else:
+                        obs = f"Error: Tool {fn} not allowed in Copilot."
+                        
+                    messages.append({"tool_call_id": tc["id"], "role": "tool", "name": fn, "content": self._truncate(str(obs))})
+
+            # If we hit the limit and it was still using tools, force a final answer
+            if tool_calls and iteration >= max_iterations:
+                messages.append({"role": "user", "content": "Tool limit reached. Provide your final tactical guide now based on the findings."})
+                response = await acompletion(
+                    model=self.engineer_model,
+                    messages=messages,
+                    tools=None,
+                    stream=True,
+                    **self.engineer_auth
+                )
+                
+                full_content = ""
+                streamed_guide = ""
+                async for chunk in response:
+                    delta = chunk.choices[0].delta
+                    if hasattr(delta, 'content') and delta.content:
+                        full_content += delta.content
+                        if chunk_callback:
+                            start_idx = full_content.find("<guide>")
+                            if start_idx != -1:
+                                after_start = full_content[start_idx + 7:]
+                                end_idx = after_start.find("</guide>")
+                                if end_idx != -1:
+                                    current_guide = after_start[:end_idx]
+                                else:
+                                    current_guide = after_start
+                                    if current_guide.endswith("<"): current_guide = current_guide[:-1]
+                                    elif current_guide.endswith("</"): current_guide = current_guide[:-2]
+                                    elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
+                                    elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
+                                    elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
+                                    elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
+                                    elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
+                                new_text = current_guide[len(streamed_guide):]
+                                if new_text:
+                                    chunk_callback(new_text)
+                                    streamed_guide += new_text
+
+            guide = ""
+            commands = []
+            risk_level = "low"
+            
+            guide_match = re.search(r"<guide>(.*?)</guide>", full_content, re.DOTALL)
+            if guide_match:
+                guide = guide_match.group(1).strip()
+                
+            cmd_match = re.search(r"<commands>(.*?)</commands>", full_content, re.DOTALL)
+            if cmd_match:
+                cmds_raw = cmd_match.group(1).strip()
+                if cmds_raw:
+                    commands = [c.strip() for c in cmds_raw.split('\n') if c.strip()]
+                    
+            risk_match = re.search(r"<risk>(.*?)</risk>", full_content, re.DOTALL)
+            if risk_match:
+                risk_level = risk_match.group(1).strip().lower()
+
+            if not guide and full_content and not ("<guide>" in full_content):
+                guide = full_content.strip()
+
+            return {
+                "commands": commands,
+                "guide": guide,
+                "risk_level": risk_level,
+                "error": None
+            }
+            
+        except asyncio.CancelledError:
+            # Client cancelled the request via gRPC or local interrupt
+            if 'response' in locals():
+                try:
+                    if hasattr(response, 'aclose'):
+                        # Fire and forget the close to avoid blocking the cancel
+                        asyncio.create_task(response.aclose())
+                    elif hasattr(response, 'close'):
+                        response.close()
+                except Exception:
+                    pass
+            return None
+        except Exception as e:
+            return {
+                "commands": [],
+                "guide": "",
+                "risk_level": "low",
+                "error": str(e)
+            }
+
+    @MethodHook
+    def confirm(self, user_input): return True
+
+

Hybrid Multi-Agent System: Selective Escalation with Role Persistence.

+

Class variables

+
+
var SAFE_COMMANDS
+
+
+
+
var deferred_class_hooks
+
+
+
+
+

Instance variables

+
+
prop architect_system_prompt
+
+
+ +Expand source code + +
@property
+def architect_system_prompt(self):
+    """Build architect system prompt with plugin extensions."""
+    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."
+    if self.architect_prompt_extensions:
+        extensions = "\n".join(self.architect_prompt_extensions)
+        return prompt + f"\n\nPlugin Capabilities:\n{extensions}"
+    return prompt
+
+

Build architect system prompt with plugin extensions.

+
+
prop engineer_system_prompt
+
+
+ +Expand source code + +
@property
+def engineer_system_prompt(self):
+    """Build engineer system prompt with plugin extensions."""
+    if self.engineer_prompt_extensions:
+        extensions = "\n".join(self.engineer_prompt_extensions)
+        return self._engineer_base_prompt + f"\n\nPlugin Capabilities:\n{extensions}"
+    return self._engineer_base_prompt
+
+

Build engineer system prompt with plugin extensions.

+
+
+

Methods

+
+
+async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None) +
+
+
+ +Expand source code + +
    @MethodHook
+    async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
+        import json
+        import re
+        from litellm import acompletion
+        import asyncio
+        import warnings
+        import aiohttp
+        
+        # Suppress unawaited coroutine warnings from LiteLLM's internal streaming logic during sudden cancellation
+        warnings.filterwarnings("ignore", message="coroutine '.*async_streaming.*' was never awaited", category=RuntimeWarning)
+        
+        node_info = node_info or {}
+        os_info = node_info.get("os", "unknown")
+        node_name = node_info.get("name", "unknown")
+        persona = node_info.get("persona", "engineer")
+        memories = node_info.get("memories", [])
+        
+        vendor_reference = ""
+        if os_info and os_info != "unknown":
+            try:
+                os_filename = os_info.lower().replace(" ", "_")
+                ref_path = os.path.join(self.config.defaultdir, "ai_references", f"{os_filename}.md")
+                if os.path.exists(ref_path):
+                    with open(ref_path, "r") as f:
+                        vendor_reference = f.read().strip()
+            except Exception:
+                pass
+        
+        if persona == "architect":
+            system_prompt = f"""Role: NETWORK ARCHITECT. You act as a senior strategic advisor during a live SSH session.
+Rules:
+1. MANDATORY: You MUST respond in the same language used by the user in their question.
+2. Answer the user's question directly and EXCLUSIVELY based on the Terminal Context. 
+3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information.
+4. Focus on the "why" and "how". Analyze topologies, design patterns, and validate configurations.
+5. Do NOT provide commands to execute unless specifically requested. Instead, explain the consequences and best practices.
+6. Keep your guide concise and authoritative.
+7. You MUST output your response in the following strict format:
+<guide>
+Your brief tactical guide in markdown.
+</guide>
+<commands>
+</commands>
+<risk>
+low
+</risk>
+8. Risk level is usually "low" for read-only/no commands.
+
+Terminal Context:
+{terminal_buffer}
+
+Device OS: {os_info}
+Node: {node_name}"""
+        else:
+            system_prompt = f"""Role: TERMINAL COPILOT. You assist a network engineer during a live SSH session.
+Rules:
+1. MANDATORY: You MUST respond in the same language used by the user in their question.
+2. EXTREMELY IMPORTANT: Answer EXCLUSIVELY based on the provided Terminal Context. 
+3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information. Instead, explicitly state that you don't see the data and offer the correct CLI commands to retrieve it.
+4. If the user asks you to analyze, parse, or extract data from the Terminal Context, DO IT directly in the <guide> section (you can use markdown tables or lists). Do NOT just give them a command to do it themselves.
+5. If the user wants to execute an action, provide the required CLI commands inside a <commands> block, one command per line. If no commands are needed, leave it empty or omit the block.
+6. ULTRA-CONCISE. Keep your guide to the point.
+7. You MUST output your response in the following strict format:
+<guide>
+Your brief tactical guide in markdown. 3-4 sentences max.
+</guide>
+<commands>
+command 1
+command 2
+</commands>
+<risk>
+low, high, or destructive
+</risk>
+8. Risk level: "low" for read-only/no commands, "high" for config changes, "destructive" for potentially dangerous ops.
+
+Terminal Context:
+{terminal_buffer}
+
+Device OS: {os_info}
+Node: {node_name}"""
+        
+        if vendor_reference:
+            system_prompt += f"\n\nVendor Command Reference:\n{vendor_reference}"
+
+        if memories:
+            system_prompt += "\n\nSession Memory (Important Facts):\n"
+            for m in memories:
+                system_prompt += f"- {m}\n"
+
+        # Fetch MCP tools for the current OS
+        mcp_tools = []
+        try:
+            mcp_tools = await self.mcp_manager.get_tools_for_llm(os_filter=os_info)
+        except Exception:
+            pass
+            
+        if mcp_tools:
+            system_prompt += f"\n\nAvailable MCP Tools: {', '.join([t['function']['name'] for t in mcp_tools])}"
+            system_prompt += "\nUse these tools to validate syntax or find exact commands if needed before providing the final guide."
+
+        messages = [
+            {"role": "system", "content": system_prompt},
+            {"role": "user", "content": user_question}
+        ]
+
+        iteration = 0
+        max_iterations = 5 # Allow up to 5 iterations for tool usage
+        
+        # Use models based on persona
+        current_model = self.architect_model if persona == "architect" else self.engineer_model
+        current_key = self.architect_key if persona == "architect" else self.engineer_key
+        current_auth = self.architect_auth if persona == "architect" else self.engineer_auth
+
+        try:
+            while iteration < max_iterations:
+                iteration += 1
+
+                response = await acompletion(
+                    model=current_model,
+                    messages=messages,
+                    tools=mcp_tools if mcp_tools else None,
+                    stream=True,
+                    **current_auth
+                )
+                
+                full_content = ""
+                streamed_guide = ""
+                tool_calls = []
+                
+                async for chunk in response:
+                    delta = chunk.choices[0].delta
+                    
+                    # Accumulate tool calls
+                    if hasattr(delta, 'tool_calls') and delta.tool_calls:
+                        for tc in delta.tool_calls:
+                            idx = tc.index
+                            if idx >= len(tool_calls):
+                                tool_calls.append({"id": tc.id, "type": "function", "function": {"name": tc.function.name or "", "arguments": tc.function.arguments or ""}})
+                            else:
+                                if tc.id: tool_calls[idx]["id"] = tc.id
+                                if tc.function.name: tool_calls[idx]["function"]["name"] = tc.function.name
+                                if tc.function.arguments: tool_calls[idx]["function"]["arguments"] += tc.function.arguments
+
+                    if hasattr(delta, 'content') and delta.content:
+                        full_content += delta.content
+                        
+                        if chunk_callback and not tool_calls: # Only stream if not using tools
+                            start_idx = full_content.find("<guide>")
+                            if start_idx != -1:
+                                after_start = full_content[start_idx + 7:]
+                                end_idx = after_start.find("</guide>")
+                                
+                                if end_idx != -1:
+                                    current_guide = after_start[:end_idx]
+                                else:
+                                    current_guide = after_start
+                                    if current_guide.endswith("<"): current_guide = current_guide[:-1]
+                                    elif current_guide.endswith("</"): current_guide = current_guide[:-2]
+                                    elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
+                                    elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
+                                    elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
+                                    elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
+                                    elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
+                                
+                                new_text = current_guide[len(streamed_guide):]
+                                if new_text:
+                                    chunk_callback(new_text)
+                                    streamed_guide += new_text
+
+                if not tool_calls:
+                    break
+                    
+                # Execute tool calls
+                messages.append({"role": "assistant", "content": full_content or None, "tool_calls": tool_calls})
+                for tc in tool_calls:
+                    fn = tc["function"]["name"]
+                    args = json.loads(tc["function"]["arguments"])
+                    
+                    if "mcp_" in fn:
+                        try:
+                            obs = await asyncio.wait_for(self.mcp_manager.call_tool(fn, args), timeout=30.0)
+                        except Exception as e:
+                            obs = f"Error calling MCP tool: {e}"
+                    else:
+                        obs = f"Error: Tool {fn} not allowed in Copilot."
+                        
+                    messages.append({"tool_call_id": tc["id"], "role": "tool", "name": fn, "content": self._truncate(str(obs))})
+
+            # If we hit the limit and it was still using tools, force a final answer
+            if tool_calls and iteration >= max_iterations:
+                messages.append({"role": "user", "content": "Tool limit reached. Provide your final tactical guide now based on the findings."})
+                response = await acompletion(
+                    model=self.engineer_model,
+                    messages=messages,
+                    tools=None,
+                    stream=True,
+                    **self.engineer_auth
+                )
+                
+                full_content = ""
+                streamed_guide = ""
+                async for chunk in response:
+                    delta = chunk.choices[0].delta
+                    if hasattr(delta, 'content') and delta.content:
+                        full_content += delta.content
+                        if chunk_callback:
+                            start_idx = full_content.find("<guide>")
+                            if start_idx != -1:
+                                after_start = full_content[start_idx + 7:]
+                                end_idx = after_start.find("</guide>")
+                                if end_idx != -1:
+                                    current_guide = after_start[:end_idx]
+                                else:
+                                    current_guide = after_start
+                                    if current_guide.endswith("<"): current_guide = current_guide[:-1]
+                                    elif current_guide.endswith("</"): current_guide = current_guide[:-2]
+                                    elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
+                                    elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
+                                    elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
+                                    elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
+                                    elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
+                                new_text = current_guide[len(streamed_guide):]
+                                if new_text:
+                                    chunk_callback(new_text)
+                                    streamed_guide += new_text
+
+            guide = ""
+            commands = []
+            risk_level = "low"
+            
+            guide_match = re.search(r"<guide>(.*?)</guide>", full_content, re.DOTALL)
+            if guide_match:
+                guide = guide_match.group(1).strip()
+                
+            cmd_match = re.search(r"<commands>(.*?)</commands>", full_content, re.DOTALL)
+            if cmd_match:
+                cmds_raw = cmd_match.group(1).strip()
+                if cmds_raw:
+                    commands = [c.strip() for c in cmds_raw.split('\n') if c.strip()]
+                    
+            risk_match = re.search(r"<risk>(.*?)</risk>", full_content, re.DOTALL)
+            if risk_match:
+                risk_level = risk_match.group(1).strip().lower()
+
+            if not guide and full_content and not ("<guide>" in full_content):
+                guide = full_content.strip()
+
+            return {
+                "commands": commands,
+                "guide": guide,
+                "risk_level": risk_level,
+                "error": None
+            }
+            
+        except asyncio.CancelledError:
+            # Client cancelled the request via gRPC or local interrupt
+            if 'response' in locals():
+                try:
+                    if hasattr(response, 'aclose'):
+                        # Fire and forget the close to avoid blocking the cancel
+                        asyncio.create_task(response.aclose())
+                    elif hasattr(response, 'close'):
+                        response.close()
+                except Exception:
+                    pass
+            return None
+        except Exception as e:
+            return {
+                "commands": [],
+                "guide": "",
+                "risk_level": "low",
+                "error": str(e)
+            }
+
+
+
+
+def ask(self,
user_input,
dryrun=False,
chat_history=None,
status=None,
debug=False,
stream=True,
session_id=None,
chunk_callback=None)
+
+
+
+ +Expand source code + +
@MethodHook
+def ask(self, user_input, dryrun=False, chat_history=None, status=None, debug=False, stream=True, session_id=None, chunk_callback=None):
+    is_engineer_keyless = "vertex" in self.engineer_model.lower() or "ollama" in self.engineer_model.lower() or "local" in self.engineer_model.lower()
+    if not self.engineer_key and not self.engineer_auth and not is_engineer_keyless:
+        raise ValueError("Engineer API key or authentication not configured. Use 'connpy config --engineer-auth <auth>' to set it.")
+
+    def update_status(text):
+        if not status:
+            return
+        if iteration >= self.soft_limit_iterations:
+            warning_suffix = " [warning]⚠ Taking longer than expected (Ctrl+C to interrupt)[/warning]"
+            if warning_suffix not in text:
+                text += warning_suffix
+        status.update(text)
+        
+    if chat_history is None: chat_history = []
+    
+    # Load session if provided and history is empty
+    if session_id:
+        # Force the session_id even if it doesn't exist yet
+        self.session_id = session_id
+        self.session_path = os.path.join(self.sessions_dir, f"{session_id}.json")
+        
+        if not chat_history:
+            session_data = self.load_session_data(session_id)
+            if session_data:
+                chat_history = session_data.get("history", [])
+            # If we loaded history, the caller might need it back
+            # But typically ask() is called in a loop with an external history object
+
+    usage = {"input": 0, "output": 0, "total": 0}
+    
+    # 1. Initial Role Selector (Sticky Brain)
+    explicit_architect = re.match(r'^(architect|arquitecto|@architect)[:\s]', user_input, re.I)
+    explicit_engineer = re.match(r'^(engineer|ingeniero|@engineer)[:\s]', user_input, re.I)
+    
+    if explicit_architect:
+        current_brain = "architect"
+    elif explicit_engineer:
+        current_brain = "engineer"
+    else:
+        # Sticky Brain: Detect if the Architect was in control in recent history
+        is_architect_active = False
+        for msg in reversed(chat_history[-5:]):
+            tcs = msg.get('tool_calls') if isinstance(msg, dict) else getattr(msg, 'tool_calls', None)
+            if tcs:
+                for tc in tcs:
+                    fn = tc.get('function', {}).get('name') if isinstance(tc, dict) else getattr(getattr(tc, 'function', None), 'name', '')
+                    # Architect stays in control if delegating tasks or if Engineer escalated to them
+                    # consult_architect is just Engineer asking for advice - Engineer keeps control
+                    if fn in ['delegate_to_engineer', 'escalate_to_architect']:
+                        is_architect_active = True; break
+            if is_architect_active: break
+        current_brain = "architect" if is_architect_active else "engineer"
+    
+    # 2. Message preparation and cleaning
+    clean_input = re.sub(r'^(architect|arquitecto|engineer|ingeniero|@architect|@engineer)[:\s]+', '', user_input, flags=re.IGNORECASE).strip()
+    
+    system_prompt = self.architect_system_prompt if current_brain == "architect" else self.engineer_system_prompt
+    tools = self._get_architect_tools() if current_brain == "architect" else self._get_engineer_tools()
+    model = self.architect_model if current_brain == "architect" else self.engineer_model
+    key = self.architect_key if current_brain == "architect" else self.engineer_key
+    current_auth = self.architect_auth if current_brain == "architect" else self.engineer_auth
+
+    # Optimized structure for Prompt Caching (Only for direct Anthropic, Vertex has different rules)
+    if "claude" in model.lower() and "vertex" not in model.lower():
+        messages = [{"role": "system", "content": [{"type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}}]}]
+    else:
+        messages = [{"role": "system", "content": system_prompt}]
+    
+    # History interleaving
+    last_role = "system"
+    # Sanitize history if the current target model is not compatible with cache_control
+    history_to_process = chat_history[-self.max_history:]
+    if "claude" not in model.lower() or "vertex" in model.lower():
+        history_to_process = self._sanitize_messages(history_to_process)
+
+    for msg in history_to_process:
+        m = msg if isinstance(msg, dict) else msg.model_dump(exclude_none=True)
+        role = m.get('role')
+        if role == last_role and role == 'user':
+            messages[-1]['content'] += "\n" + (m.get('content') or "")
+            continue
+        if role == 'assistant' and m.get('tool_calls') and m.get('content') == "": m['content'] = None
+        messages.append(m)
+        last_role = role
+
+    if last_role == 'user': messages[-1]['content'] += "\n" + clean_input
+    else: messages.append({"role": "user", "content": clean_input})
+
+    # 3. Execution loop
+    iteration = 0
+    try:
+        # Set up remote interrupt callback if bridge is provided
+        if status and hasattr(status, "on_interrupt"):
+            status.on_interrupt = lambda: setattr(self, "interrupted", True)
+
+        while iteration < self.hard_limit_iterations:
+            iteration += 1
+            
+            # Check for interruption
+            if self.interrupted:
+                raise KeyboardInterrupt
+            
+            # Soft limit warning - handled inline within update_status
+            
+            label = "[architect][bold]Architect[/bold][/architect]" if current_brain == "architect" else "[engineer][bold]Engineer[/bold][/engineer]"
+            if status: 
+                # Notify responder identity for web/remote clients
+                if getattr(status, "is_web", False) or getattr(status, "is_remote", False):
+                    status.update(f"__RESPONDER__:{current_brain}")
+                update_status(f"{label} is thinking... (step {iteration})")
+            
+            streamed_response = False
+            try:
+                safe_messages = self._sanitize_messages(messages)
+                if stream:
+                    response, streamed_response = self._stream_completion(
+                        model=model, messages=safe_messages, tools=tools, auth=current_auth,
+                        status=status, label=label, debug=debug, num_retries=3,
+                        chunk_callback=chunk_callback
+                    )
+                else:
+                    response = completion(model=model, messages=safe_messages, tools=tools, num_retries=3, **current_auth)
+            except Exception as e:
+                if current_brain == "architect":
+                    if status: update_status("[unavailable]Architect unavailable! Falling back to Engineer...")
+                    # Preserve context when falling back - use clean_input directly
+                    current_brain = "engineer"
+                    model = self.engineer_model
+                    tools = self._get_engineer_tools()
+                    key = self.engineer_key
+                    current_auth = self.engineer_auth
+                    # Rebuild messages with Engineer system prompt and original user request
+                    messages = [{"role": "system", "content": self.engineer_system_prompt}]
+                    # Add chat history if exists (excluding system prompt)
+                    if chat_history:
+                        for msg in chat_history[-self.max_history:]:
+                            if msg.get('role') != 'system':
+                                messages.append(msg)
+                    # Add current user request with a system note to prevent infinite escalation loops
+                    fallback_msg = clean_input + "\n\n[SYSTEM NOTE: The Architect is currently unavailable/failed to respond. You must handle the user's request directly as the Network Engineer. Do NOT attempt to escalate to the Architect again.]"
+                    messages.append({"role": "user", "content": fallback_msg})
+                    continue
+                else: 
+                    return {"response": f"Error: Both engines failed. {str(e)}", "chat_history": messages[1:], "usage": usage}
+            
+            if hasattr(response, "usage") and response.usage:
+                usage["input"] += getattr(response.usage, "prompt_tokens", 0)
+                usage["output"] += getattr(response.usage, "completion_tokens", 0)
+                usage["total"] += getattr(response.usage, "total_tokens", 0)
+
+            resp_msg = response.choices[0].message
+            msg_dict = resp_msg.model_dump(exclude_none=True)
+            if msg_dict.get("tool_calls") and msg_dict.get("content") == "": msg_dict["content"] = None
+            messages.append(msg_dict)
+
+            if debug and resp_msg.content and not streamed_response:
+                # In CLI debug mode, only print intermediate reasoning if there are tool calls AND it wasn't already streamed.
+                # If there are no tool calls, this content is the final answer and will be printed by the caller.
+                if resp_msg.tool_calls:
+                    if status:
+                        try: status.stop()
+                        except: pass
+                    self.console.print(Panel(Markdown(resp_msg.content), title=f"[{current_brain}][bold]{label} Reasoning[/bold][/{current_brain}]", border_style="architect" if current_brain == "architect" else "engineer"))
+                    if status:
+                        try: status.start()
+                        except: pass
+
+            if not resp_msg.tool_calls: break
+            
+            # Track if we need to inject a user message after all tool responses
+            pending_user_message = None
+            
+            for tc in resp_msg.tool_calls:
+                fn, args = tc.function.name, json.loads(tc.function.arguments)
+                
+                # Validate tool access based on current brain
+                if fn in ['delegate_to_engineer'] and current_brain != "architect":
+                    obs = f"Error: Tool '{fn}' is only available to the Architect (Architect). You are the Engineer (Engineer). Use 'run_commands' directly to execute configuration."
+                    messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": obs})
+                    continue
+                
+                if status:
+                    if fn == "delegate_to_engineer": update_status(f"[architect]Architect: [DELEGATING MISSION] {args.get('task','')[:40]}...")
+                    elif fn == "manage_memory_tool": update_status(f"[architect]Architect: [UPDATING MEMORY]")
+
+                if debug:
+                    self._print_debug_observation(f"Decision: {fn}", args, status=status)
+
+                if fn == "delegate_to_engineer":
+                    obs, eng_usage = self._engineer_loop(args["task"], status=status, debug=debug, chat_history=messages[:-1])
+                    usage["input"] += eng_usage["input"]; usage["output"] += eng_usage["output"]; usage["total"] += eng_usage["total"]
+                elif fn == "consult_architect":
+                    if status: update_status("[architect]Engineer consulting Architect...")
+                    try:
+                        # Consultation only - Engineer stays in control
+                        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
+                        )
+                        obs = claude_resp.choices[0].message.content
+                        if debug:
+                            if status:
+                                try: status.stop()
+                                except: pass
+                            self.console.print(Panel(Markdown(obs), title="[architect]Architect Consultation[/architect]", border_style="architect"))
+                            if status:
+                                try: status.start()
+                                except: pass
+                    except Exception as e:
+                        if status: update_status("[unavailable]Architect unavailable! Engineer continuing alone...")
+                        obs = f"Architect unavailable ({str(e)}). Proceeding with your best technical judgment."
+                
+                elif fn == "escalate_to_architect":
+                    if status: update_status("[architect]Transferring control to Architect...")
+                    # Full escalation - Architect takes over
+                    current_brain = "architect"
+                    model = self.architect_model
+                    tools = self._get_architect_tools()
+                    key = self.architect_key
+                    current_auth = self.architect_auth
+                    messages[0] = {"role": "system", "content": self.architect_system_prompt}
+                    # Prepare handover context to inject AFTER all tool responses
+                    handover_msg = f"HANDOVER FROM EXECUTION ENGINE\n\nReason: {args['reason']}\n\nContext: {args['context']}\n\nYou are now in control of this conversation."
+                    pending_user_message = handover_msg
+                    obs = "Control transferred to Architect. Handover context will be provided."
+                    if debug:
+                        if status:
+                            try: status.stop()
+                            except: pass
+                        self.console.print(Panel(Text(handover_msg), title="[architect]Escalation to Architect[/architect]", border_style="architect"))
+                        if status:
+                            try: status.start()
+                            except: pass
+                
+                elif fn == "return_to_engineer":
+                    if status: update_status("[engineer]Transferring control back to Engineer...")
+                    # Architect returns control to Engineer
+                    current_brain = "engineer"
+                    model = self.engineer_model
+                    tools = self._get_engineer_tools()
+                    key = self.engineer_key
+                    current_auth = self.engineer_auth
+                    messages[0] = {"role": "system", "content": self.engineer_system_prompt}
+                    # Prepare handover context to inject AFTER all tool responses
+                    handover_msg = f"HANDOVER FROM ARCHITECT\n\nSummary: {args['summary']}\n\nYou are now back in control. Continue handling the user's requests."
+                    pending_user_message = handover_msg
+                    obs = "Control returned to Engineer. Handover summary will be provided."
+                    if debug:
+                        if status:
+                            try: status.stop()
+                            except: pass
+                        self.console.print(Panel(Text(handover_msg), title="[engineer]Return to Engineer[/engineer]", border_style="engineer"))
+                        if status:
+                            try: status.start()
+                            except: pass
+                
+                elif fn == "list_nodes": obs = self.list_nodes_tool(**args)
+                elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
+                elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
+                elif fn == "manage_memory_tool": obs = self.manage_memory_tool(**args)
+                elif fn.startswith("mcp_"):
+                    obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
+                elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
+                else: obs = f"Error: {fn} unknown."
+
+                if debug and fn not in ["delegate_to_engineer", "consult_architect", "escalate_to_architect", "return_to_engineer"]:
+                    self._print_debug_observation(f"Observation: {fn}", obs, status=status)
+
+                # Ensure observation is a string and truncated for the LLM
+                obs_str = obs if isinstance(obs, str) else json.dumps(obs)
+                messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": self._truncate(obs_str)})                
+            # Inject pending user message AFTER all tool responses are added
+            if pending_user_message:
+                messages.append({"role": "user", "content": pending_user_message})
+        
+        if iteration >= self.hard_limit_iterations:
+            self.console.print(f"[error]⛔ Agent reached hard limit ({self.hard_limit_iterations} steps). Forcing stop to prevent infinite loop.[/error]")
+            # Only inject user message if we're not in the middle of tool calls
+            last_msg = messages[-1] if messages else {}
+            if last_msg.get("role") != "assistant" or not last_msg.get("tool_calls"):
+                messages.append({"role": "user", "content": "Hard iteration limit reached. Please provide a summary of your findings so far."})
+                try:
+                    safe_messages = self._sanitize_messages(messages)
+                    response = completion(model=model, messages=safe_messages, tools=[], **current_auth)
+                    resp_msg = response.choices[0].message
+                    messages.append(resp_msg.model_dump(exclude_none=True))
+                except Exception as e:
+                    if status:
+                        update_status(f"[error]Error fetching summary: {e}[/error]")
+                    printer.warning(f"Failed to fetch final summary from LLM: {e}")
+    except KeyboardInterrupt:
+        if status: status.update("[error]Interrupted! Closing pending tasks...")
+        last_msg = messages[-1]
+        if last_msg.get("tool_calls"):
+            for tc in last_msg["tool_calls"]:
+                messages.append({"tool_call_id": tc.get("id"), "role": "tool", "name": tc.get("function", {}).get("name"), "content": "Operation cancelled by user."})
+        
+        # Use a fresh list for the summary call to avoid history corruption
+        summary_messages = list(messages)
+        summary_messages.append({"role": "user", "content": "USER INTERRUPTED. Briefly summarize what you were doing and stop."})
+        try:
+            safe_messages = self._sanitize_messages(summary_messages)
+            # Use tools=None to force a text summary during interruption
+            response = completion(model=model, messages=safe_messages, tools=None, **current_auth)
+            resp_msg = response.choices[0].message
+            messages.append(resp_msg.model_dump(exclude_none=True))
+            
+            # IMPORTANT: Manually trigger callback for the summary so Web UI sees it
+            if chunk_callback and resp_msg.content:
+                chunk_callback(resp_msg.content)
+        except Exception:
+            error_msg = "Operation interrupted by user. Summary unavailable."
+            messages.append({"role": "assistant", "content": error_msg})
+            if chunk_callback:
+                chunk_callback(error_msg)
+    finally:
+        # Auto-save session
+        self.save_session(messages, model=model)
+
+    return {
+        "response": messages[-1].get("content"), 
+        "chat_history": messages[1:], 
+        "app_related": True, 
+        "usage": usage,
+        "responder": current_brain,  # "architect" or "engineer"
+        "streamed": streamed_response
+    }
+
+
+
+
+def confirm(self, user_input) +
+
+
+ +Expand source code + +
@MethodHook
+def confirm(self, user_input): return True
+
+
+
+
+def delete_session(self, session_id) +
+
+
+ +Expand source code + +
def delete_session(self, session_id):
+    """Deletes a session by ID."""
+    path = os.path.join(self.sessions_dir, f"{session_id}.json")
+    if os.path.exists(path):
+        os.remove(path)
+        printer.success(f"Session {session_id} deleted.")
+    else:
+        printer.error(f"Session {session_id} not found.")
+
+

Deletes a session by ID.

+
+
+def get_last_session_id(self) +
+
+
+ +Expand source code + +
def get_last_session_id(self):
+    """Returns the ID of the most recent session."""
+    sessions = self._get_sessions()
+    return sessions[0]["id"] if sessions else None
+
+

Returns the ID of the most recent session.

+
+
+def get_node_info_tool(self, node_name) +
+
+
+ +Expand source code + +
def get_node_info_tool(self, node_name):
+    """Get detailed metadata for a specific node. Passwords are masked."""
+    try:
+        d = self.config.getitem(node_name, extract=True)
+        if 'password' in d: d['password'] = '***'
+        return d
+    except Exception as e: 
+        return f"Error getting node info: {str(e)}"
+
+

Get detailed metadata for a specific node. Passwords are masked.

+
+
+def list_nodes_tool(self, filter_pattern='.*') +
+
+
+ +Expand source code + +
def list_nodes_tool(self, filter_pattern=".*"):
+    """List nodes matching the filter pattern. Returns metadata for <=5 nodes, names only for more."""
+    try:
+        matched_names = self.config._getallnodes(filter_pattern)
+        if not matched_names: return "No nodes found."
+        if len(matched_names) <= 5:
+            matched_data = self.config.getitems(matched_names, extract=True)
+            res = {}
+            for name, data in matched_data.items():
+                os_tag = "unknown"
+                if isinstance(data, dict):
+                    ts = data.get("tags")
+                    if isinstance(ts, dict): os_tag = ts.get("os", "unknown")
+                res[name] = {"os": os_tag}
+            return res
+        return {"count": len(matched_names), "nodes": matched_names, "note": "Use 'get_node_info' for details."}
+    except Exception as e: 
+        return f"Error listing nodes: {str(e)}"
+
+

List nodes matching the filter pattern. Returns metadata for <=5 nodes, names only for more.

+
+
+def list_sessions(self, limit=20) +
+
+
+ +Expand source code + +
def list_sessions(self, limit=20):
+    """Prints a list of sessions using printer.table."""
+    sessions = self._get_sessions()
+    if not sessions:
+        printer.info("No saved AI sessions found.")
+        return
+    
+    total = len(sessions)
+    if limit and total > limit:
+        sessions = sessions[:limit]
+        
+    columns = ["ID", "Title", "Created At", "Model"]
+    rows = [[s["id"], s["title"], s["created_at"], s["model"]] for s in sessions]
+    
+    title = "AI Persisted Sessions"
+    if limit and total > limit:
+        title += f" (Showing last {limit} of {total})"
+        
+    printer.table(title, columns, rows)
+    if limit and total > limit:
+        printer.info(f"Use '--list --all' (if supported) or check the sessions directory to see all {total} sessions.")
+
+

Prints a list of sessions using printer.table.

+
+
+def load_session_data(self, session_id) +
+
+
+ +Expand source code + +
def load_session_data(self, session_id):
+    """Loads a session's raw data by ID."""
+    path = os.path.join(self.sessions_dir, f"{session_id}.json")
+    if os.path.exists(path):
+        try:
+            with open(path, "r") as f:
+                data = json.load(f)
+                self.session_id = session_id
+                self.session_path = path
+                return data
+        except Exception as e:
+            printer.error(f"Failed to load session {session_id}: {e}")
+    return None
+
+

Loads a session's raw data by ID.

+
+
+def manage_memory_tool(self, content, action='append') +
+
+
+ +Expand source code + +
def manage_memory_tool(self, content, action="append"):
+    """Save or update long-term memory. Only use when user explicitly requests it."""
+    if not content or not content.strip():
+        return "Error: Cannot save empty content to memory."
+    
+    try:
+        mode = "a" if action == "append" else "w"
+        os.makedirs(os.path.dirname(self.memory_path), exist_ok=True)
+        with open(self.memory_path, mode) as f:
+            timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
+            f.write(f"\n\n## {timestamp}\n{content.strip()}\n" if action == "append" else content)
+        
+        # Reload memory after update
+        with open(self.memory_path, "r") as f:
+            self.long_term_memory = f.read()
+        
+        return "Memory updated successfully."
+    except PermissionError as e:
+        return f"Error: Permission denied writing to memory file: {e}"
+    except Exception as e:
+        return f"Error updating memory: {str(e)}"
+
+

Save or update long-term memory. Only use when user explicitly requests it.

+
+
+def register_ai_tool(self,
tool_definition,
handler,
target='engineer',
engineer_prompt=None,
architect_prompt=None,
status_formatter=None)
+
+
+
+ +Expand source code + +
def register_ai_tool(self, tool_definition, handler, target="engineer", engineer_prompt=None, architect_prompt=None, status_formatter=None):
+    """Register an external tool for the AI system.
+
+    Args:
+        tool_definition (dict): OpenAI-compatible tool definition.
+        handler (callable): Function(ai_instance, **tool_args) -> str.
+        target (str): 'engineer', 'architect', or 'both'.
+        engineer_prompt (str): Extra text for engineer system prompt.
+        architect_prompt (str): Extra text for architect system prompt.
+        status_formatter (callable): Function(args_dict) -> status string.
+    """
+    name = tool_definition["function"]["name"]
+    
+    # Check if already registered to prevent duplicates
+    if target in ("engineer", "both"):
+        if not any(t["function"]["name"] == name for t in self.external_engineer_tools):
+            self.external_engineer_tools.append(tool_definition)
+    if target in ("architect", "both"):
+        if not any(t["function"]["name"] == name for t in self.external_architect_tools):
+            self.external_architect_tools.append(tool_definition)
+    
+    self.external_tool_handlers[name] = handler
+    
+    if engineer_prompt and engineer_prompt not in self.engineer_prompt_extensions:
+        self.engineer_prompt_extensions.append(engineer_prompt)
+    if architect_prompt and architect_prompt not in self.architect_prompt_extensions:
+        self.architect_prompt_extensions.append(architect_prompt)
+    if status_formatter:
+        self.tool_status_formatters[name] = status_formatter
+
+

Register an external tool for the AI system.

+

Args

+
+
tool_definition : dict
+
OpenAI-compatible tool definition.
+
handler : callable
+
Function(ai_instance, **tool_args) -> str.
+
target : str
+
'engineer', 'architect', or 'both'.
+
engineer_prompt : str
+
Extra text for engineer system prompt.
+
architect_prompt : str
+
Extra text for architect system prompt.
+
status_formatter : callable
+
Function(args_dict) -> status string.
+
+
+
+def run_commands_tool(self, nodes_filter, commands, status=None) +
+
+
+ +Expand source code + +
def run_commands_tool(self, nodes_filter, commands, status=None):
+    """Execute commands on nodes matching the filter. Native interactive confirmation for unsafe commands."""
+    # Handle if commands is a JSON string
+    if isinstance(commands, str):
+        try:
+            commands = json.loads(commands)
+        except ValueError:
+            commands = [c.strip() for c in commands.split('\n') if c.strip()]
+    
+    # Expand multi-line commands within a list (in case the AI packs them)
+    if isinstance(commands, list):
+        expanded_commands = []
+        for cmd in commands:
+            expanded_commands.extend([c.strip() for c in str(cmd).split('\n') if c.strip()])
+        commands = expanded_commands
+    else:
+        commands = [str(commands)]
+    
+    # Check command safety natively
+    if not self.trusted_session:
+        unsafe_commands = [cmd for cmd in commands if not self._is_safe_command(cmd)]
+        if unsafe_commands:
+            # Stop the spinner so prompt doesn't get messed up
+            if status: status.stop()
+            
+            # Show ALL commands with unsafe ones highlighted
+            formatted_cmds = []
+            for cmd in commands:
+                if cmd in unsafe_commands:
+                    formatted_cmds.append(f"  • [warning]{cmd}[/warning]")
+                else:
+                    formatted_cmds.append(f"  • {cmd}")
+            
+            panel_content = f"Target: {nodes_filter}\nCommands:\n" + "\n".join(formatted_cmds)
+            # Use print_important if available (for remote bridges) fallback to standard print
+            print_fn = getattr(self.console, "print_important", self.console.print)
+            print_fn(Panel(panel_content, title="[bold warning]⚠️ UNSAFE COMMANDS DETECTED[/bold warning]", border_style="warning"))
+            
+            try:
+                user_resp = self.confirm_handler("[bold warning]Execute? (y: yes / n: no / a: allow all this session / <text>: feedback)[/bold warning]", default="n")
+            except KeyboardInterrupt:
+                if status: status.update("[ai_status]Engineer: Resuming...")
+                self.console.print("[fail]✗ Aborted by user (Ctrl+C).[/fail]")
+                raise
+            
+            # Resume the spinner
+            if status: status.update("[ai_status]Engineer: Processing user response...")
+            
+            user_resp_lower = user_resp.strip().lower()
+            if user_resp_lower in ['a', 'allow']:
+                self.trusted_session = True
+                self.console.print("[pass]✓ Trust Mode Enabled. All future commands in this session will execute without confirmation.[/pass]")
+            elif user_resp_lower in ['y', 'yes']:
+                self.console.print("[pass]✓ Executing...[/pass]")
+            elif user_resp_lower in ['n', 'no', '', 'cancel']:
+                self.console.print("[fail]✗ Execution rejected by user.[/fail]")
+                return "Error: User rejected execution."
+            else:
+                self.console.print(f"[user_prompt]User feedback: [/user_prompt]{user_resp}")
+                return f"User requested changes: {user_resp}. Please adjust the commands based on this feedback and try again."
+    
+    try:
+        matched_names = self.config._getallnodes(nodes_filter)
+        if not matched_names: return "No nodes found matching filter."
+        thisnodes_dict = self.config.getitems(matched_names, extract=True)
+        result = nodes(thisnodes_dict, config=self.config).run(commands)
+        return result
+    except Exception as e: 
+        return f"Error executing commands: {str(e)}"
+
+

Execute commands on nodes matching the filter. Native interactive confirmation for unsafe commands.

+
+
+def save_session(self, history, title=None, model=None) +
+
+
+ +Expand source code + +
def save_session(self, history, title=None, model=None):
+    """Saves current history to the session file."""
+    if not self.session_id:
+        # Generate ID from first user query if available
+        first_user_msg = next((m["content"] for m in history if m["role"] == "user"), "new-session")
+        self.session_id = self._generate_session_id(first_user_msg)
+        self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json")
+    elif not self.session_path:
+        self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json")
+
+    # If it's a new file, we might want to set a better title
+    if not os.path.exists(self.session_path) and not title:
+        raw_title = next((m["content"] for m in history if m["role"] == "user"), "New Session")
+        # Clean title: remove newlines, multiple spaces
+        clean_title = " ".join(raw_title.split())
+        if len(clean_title) > 40:
+            title = clean_title[:37].strip() + "..."
+        else:
+            title = clean_title
+
+    try:
+        # Read existing metadata if it exists
+        metadata = {}
+        if os.path.exists(self.session_path):
+            with open(self.session_path, "r") as f:
+                metadata = json.load(f)
+        
+        metadata.update({
+            "id": self.session_id,
+            "title": title or metadata.get("title", "New Session"),
+            "created_at": metadata.get("created_at", datetime.datetime.now().isoformat()),
+            "updated_at": datetime.datetime.now().isoformat(),
+            "model": model or metadata.get("model", self.engineer_model),
+            "history": history
+        })
+
+        with open(self.session_path, "w") as f:
+            json.dump(metadata, f, indent=4)
+    except Exception as e:
+        printer.error(f"Failed to save session: {e}")
+
+    except Exception as e:
+        printer.error(f"Failed to save session: {e}")
+
+

Saves current history to the session file.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/connpy/cli/config_handler.html b/docs/connpy/cli/config_handler.html index ec1277b..64bdff7 100644 --- a/docs/connpy/cli/config_handler.html +++ b/docs/connpy/cli/config_handler.html @@ -77,7 +77,10 @@ el.replaceWith(d); "trusted_commands": self.set_ai_config, "service_mode": self.set_service_mode, "remote_host": self.set_remote_host, - "sync_remote": self.set_sync_remote + "sync_remote": self.set_sync_remote, + "shell_command": self.set_shell_config, + "shell_prompt": self.set_shell_config, + "shell_os": self.set_shell_config } handler = actions.get(getattr(args, "command", None)) if handler: @@ -232,7 +235,23 @@ el.replaceWith(d); return parsed raise ValueError() except Exception: - raise InvalidConfigurationError("Auth parameter must be a valid JSON/YAML string, or a path to a JSON/YAML file.") + raise InvalidConfigurationError("Auth parameter must be a valid JSON/YAML string, or a path to a JSON/YAML file.") + + def set_shell_config(self, args): + key = args.command.replace("shell_", "") + val = args.data[0] if isinstance(args.data, list) else args.data + try: + settings = self.app.services.config_svc.get_settings() + shell_cfg = settings.get("shell", {}) if isinstance(settings.get("shell"), dict) else {} + if str(val).lower() in ["none", "clear", ""]: + if key in shell_cfg: + del shell_cfg[key] + else: + shell_cfg[key] = val + self.app.services.config_svc.update_setting("shell", shell_cfg) + printer.success("Config saved") + except (ConnpyError, InvalidConfigurationError) as e: + printer.error(str(e))

Methods

@@ -263,7 +282,10 @@ el.replaceWith(d); "trusted_commands": self.set_ai_config, "service_mode": self.set_service_mode, "remote_host": self.set_remote_host, - "sync_remote": self.set_sync_remote + "sync_remote": self.set_sync_remote, + "shell_command": self.set_shell_config, + "shell_prompt": self.set_shell_config, + "shell_os": self.set_shell_config } handler = actions.get(getattr(args, "command", None)) if handler: @@ -434,6 +456,32 @@ el.replaceWith(d);
+
+def set_shell_config(self, args) +
+
+
+ +Expand source code + +
def set_shell_config(self, args):
+    key = args.command.replace("shell_", "")
+    val = args.data[0] if isinstance(args.data, list) else args.data
+    try:
+        settings = self.app.services.config_svc.get_settings()
+        shell_cfg = settings.get("shell", {}) if isinstance(settings.get("shell"), dict) else {}
+        if str(val).lower() in ["none", "clear", ""]:
+            if key in shell_cfg:
+                del shell_cfg[key]
+        else:
+            shell_cfg[key] = val
+        self.app.services.config_svc.update_setting("shell", shell_cfg)
+        printer.success("Config saved")
+    except (ConnpyError, InvalidConfigurationError) as e:
+        printer.error(str(e))
+
+
+
def set_sync_remote(self, args)
@@ -538,6 +586,7 @@ el.replaceWith(d);
  • set_idletime
  • set_remote_host
  • set_service_mode
  • +
  • set_shell_config
  • set_sync_remote
  • set_theme
  • show_completion
  • diff --git a/docs/connpy/cli/forms.html b/docs/connpy/cli/forms.html index da27067..b2875a6 100644 --- a/docs/connpy/cli/forms.html +++ b/docs/connpy/cli/forms.html @@ -61,6 +61,7 @@ el.replaceWith(d); self.validators = Validators(app) def questions_edit(self): + import inquirer questions = [] questions.append(inquirer.Confirm("host", message="Edit Hostname/IP?")) questions.append(inquirer.Confirm("protocol", message="Edit Protocol/app?")) @@ -74,6 +75,7 @@ el.replaceWith(d); return inquirer.prompt(questions) def questions_nodes(self, unique, uniques=None, edit=None): + import inquirer try: defaults = self.app.services.nodes.get_node_details(unique) if "tags" not in defaults: @@ -151,6 +153,7 @@ el.replaceWith(d); return result def questions_profiles(self, unique, edit=None): + import inquirer try: defaults = self.app.services.profiles.get_profile(unique, resolve=False) if "tags" not in defaults: @@ -216,6 +219,7 @@ el.replaceWith(d); return result def questions_bulk(self, nodes="", hosts=""): + import inquirer questions = [] questions.append(inquirer.Text("ids", message="add a comma separated list of nodes to add", default=nodes, validate=self.validators.bulk_node_validation)) questions.append(inquirer.Text("location", message="Add a @folder, @subfolder@folder or leave empty", validate=self.validators.bulk_folder_validation)) @@ -253,6 +257,7 @@ el.replaceWith(d); def mcp_wizard(self, mcp_servers): """Interactive wizard to manage MCP servers.""" + import inquirer from .helpers import theme while True: @@ -345,6 +350,7 @@ el.replaceWith(d);
    def mcp_wizard(self, mcp_servers):
         """Interactive wizard to manage MCP servers."""
    +    import inquirer
         from .helpers import theme
         
         while True:
    @@ -435,6 +441,7 @@ el.replaceWith(d);
     Expand source code
     
     
    def questions_bulk(self, nodes="", hosts=""):
    +    import inquirer
         questions = []
         questions.append(inquirer.Text("ids", message="add a comma separated list of nodes to add", default=nodes, validate=self.validators.bulk_node_validation))
         questions.append(inquirer.Text("location", message="Add a @folder, @subfolder@folder or leave empty", validate=self.validators.bulk_folder_validation))
    @@ -481,6 +488,7 @@ el.replaceWith(d);
     Expand source code
     
     
    def questions_edit(self):
    +    import inquirer
         questions = []
         questions.append(inquirer.Confirm("host", message="Edit Hostname/IP?"))
         questions.append(inquirer.Confirm("protocol", message="Edit Protocol/app?"))
    @@ -504,6 +512,7 @@ el.replaceWith(d);
     Expand source code
     
     
    def questions_nodes(self, unique, uniques=None, edit=None):
    +    import inquirer
         try:
             defaults = self.app.services.nodes.get_node_details(unique)
             if "tags" not in defaults:
    @@ -591,6 +600,7 @@ el.replaceWith(d);
     Expand source code
     
     
    def questions_profiles(self, unique, edit=None):
    +    import inquirer
         try:
             defaults = self.app.services.profiles.get_profile(unique, resolve=False)
             if "tags" not in defaults:
    diff --git a/docs/connpy/cli/helpers.html b/docs/connpy/cli/helpers.html
    index 4b523ad..28da9cf 100644
    --- a/docs/connpy/cli/helpers.html
    +++ b/docs/connpy/cli/helpers.html
    @@ -68,6 +68,7 @@ el.replaceWith(d);
             else:
                 return answer[0]
         else:
    +        import inquirer
             questions = [inquirer.List(name, message="Pick {} to {}:".format(name,action), choices=list_, carousel=True)]
             answer = inquirer.prompt(questions, theme=theme)
             if answer == None:
    @@ -125,6 +126,26 @@ el.replaceWith(d);
     
     
    def get_theme():
         """Returns a fresh instance of the theme with current colors."""
    +    from inquirer.themes import Default, term
    +
    +    class ConnpyTheme(Default):
    +        def __init__(self):
    +            super().__init__()
    +            try:
    +                from ..printer import _global_active_styles
    +                # Use user_prompt as primary accent, fallback to info/cyan
    +                accent = _global_active_styles.get("user_prompt", _global_active_styles.get("info", "cyan"))
    +                accent_color = hex_to_blessed(accent)
    +                
    +                self.Question.mark_color = accent_color
    +                self.List.selection_color = accent_color
    +                self.List.selection_cursor = ">"
    +            except:
    +                # Absolute fallback to standard cyan
    +                self.Question.mark_color = term.cyan
    +                self.List.selection_color = term.bold_cyan
    +                self.List.selection_cursor = ">"
    +
         return ConnpyTheme()

    Returns a fresh instance of the theme with current colors.

    @@ -139,6 +160,7 @@ el.replaceWith(d);
    def hex_to_blessed(hex_str):
         """Convert hex color string to blessed/ansi format."""
    +    from inquirer.themes import term
         if not hex_str or not isinstance(hex_str, str):
             return term.normal
         
    @@ -242,39 +264,6 @@ el.replaceWith(d);
     

    Classes

    -
    -class ConnpyTheme -
    -
    -
    - -Expand source code - -
    class ConnpyTheme(Default):
    -    def __init__(self):
    -        super().__init__()
    -        try:
    -            from ..printer import _global_active_styles
    -            # Use user_prompt as primary accent, fallback to info/cyan
    -            accent = _global_active_styles.get("user_prompt", _global_active_styles.get("info", "cyan"))
    -            accent_color = hex_to_blessed(accent)
    -            
    -            self.Question.mark_color = accent_color
    -            self.List.selection_color = accent_color
    -            self.List.selection_cursor = ">"
    -        except:
    -            # Absolute fallback to standard cyan
    -            self.Question.mark_color = term.cyan
    -            self.List.selection_color = term.bold_cyan
    -            self.List.selection_cursor = ">"
    -
    -
    -

    Ancestors

    -
      -
    • inquirer.themes.Default
    • -
    • inquirer.themes.Theme
    • -
    -
    class ThemeProxy
    @@ -322,9 +311,6 @@ el.replaceWith(d);
  • Classes

    diff --git a/docs/connpy/cli/import_export_handler.html b/docs/connpy/cli/import_export_handler.html index 6f6aa1b..10698db 100644 --- a/docs/connpy/cli/import_export_handler.html +++ b/docs/connpy/cli/import_export_handler.html @@ -58,12 +58,24 @@ el.replaceWith(d);
    class ImportExportHandler:
         def __init__(self, app):
             self.app = app
    -        self.forms = Forms(app)
    +        self._forms = None
    +
    +    @property
    +    def forms(self):
    +        if self._forms is None:
    +            from .forms import Forms
    +            self._forms = Forms(self.app)
    +        return self._forms
    +
    +    @forms.setter
    +    def forms(self, value):
    +        self._forms = value
     
         def dispatch_import(self, args):
             file_path = args.data[0]
             try:
                 printer.warning("This could overwrite your current configuration!")
    +            import inquirer
                 question = [inquirer.Confirm("import", message=f"Are you sure you want to import {file_path}?")]
                 confirm = inquirer.prompt(question)
                 if confirm == None or not confirm["import"]:
    @@ -135,6 +147,24 @@ el.replaceWith(d);
                 sys.exit(1)
    +

    Instance variables

    +
    +
    prop forms
    +
    +
    + +Expand source code + +
    @property
    +def forms(self):
    +    if self._forms is None:
    +        from .forms import Forms
    +        self._forms = Forms(self.app)
    +    return self._forms
    +
    +
    +
    +

    Methods

    @@ -228,6 +258,7 @@ el.replaceWith(d); file_path = args.data[0] try: printer.warning("This could overwrite your current configuration!") + import inquirer question = [inquirer.Confirm("import", message=f"Are you sure you want to import {file_path}?")] confirm = inquirer.prompt(question) if confirm == None or not confirm["import"]: @@ -264,6 +295,7 @@ el.replaceWith(d);
  • bulk
  • dispatch_export
  • dispatch_import
  • +
  • forms
  • diff --git a/docs/connpy/cli/index.html b/docs/connpy/cli/index.html index 24769ee..3d58a06 100644 --- a/docs/connpy/cli/index.html +++ b/docs/connpy/cli/index.html @@ -92,6 +92,10 @@ el.replaceWith(d);
    +
    connpy.cli.shell_handler
    +
    +
    +
    connpy.cli.sso_handler
    @@ -146,6 +150,7 @@ el.replaceWith(d);
  • connpy.cli.plugin_handler
  • connpy.cli.profile_handler
  • connpy.cli.run_handler
  • +
  • connpy.cli.shell_handler
  • connpy.cli.sso_handler
  • connpy.cli.sync_handler
  • connpy.cli.terminal_ui
  • diff --git a/docs/connpy/cli/login_handler.html b/docs/connpy/cli/login_handler.html index 8b0d6f3..f1209eb 100644 --- a/docs/connpy/cli/login_handler.html +++ b/docs/connpy/cli/login_handler.html @@ -70,6 +70,14 @@ el.replaceWith(d); sys.exit(1) def login(self, args): + # Handle token management actions first + if getattr(args, "create_token", None): + return self.create_token(args) + if getattr(args, "list_tokens", False): + return self.list_tokens(args) + if getattr(args, "revoke_token", None): + return self.revoke_token(args) + if getattr(args, "status", False): return self.show_status() @@ -191,11 +199,137 @@ el.replaceWith(d); exp_dt = datetime.datetime.fromtimestamp(exp, datetime.timezone.utc) printer.info(f"Expires at: {exp_dt.strftime('%Y-%m-%d %H:%M:%S UTC')}") except Exception as e: - printer.error(f"Failed to check local session status: {e}")
    + printer.error(f"Failed to check local session status: {e}") + + def _get_auth_service(self): + """Gets an authenticated auth service stub, reusing existing or creating one.""" + auth_service = getattr(self.app.services, "auth", None) + if not auth_service: + import grpc + from ..grpc_layer.stubs import AuthStub + remote_host = self.app.services.remote_host or self.app.config.config.get("remote_host") + if not remote_host: + printer.error("Remote host is not configured. Run 'connpy config --remote HOST:PORT' first.") + sys.exit(1) + try: + # Load existing session token for authentication + token_path = os.path.join(self.app.config.defaultdir, ".token") + if not os.path.exists(token_path): + printer.error("No active session. Please log in first using 'connpy login'.") + sys.exit(1) + with open(token_path, "r") as f: + session_token = f.read().strip() + + from ..grpc_layer.stubs import AuthClientInterceptor + interceptor = AuthClientInterceptor(lambda: session_token) + channel = grpc.intercept_channel(grpc.insecure_channel(remote_host), interceptor) + auth_service = AuthStub(channel, remote_host=remote_host) + except Exception as e: + printer.error(f"Failed to connect to remote server: {e}") + sys.exit(1) + return auth_service + + def create_token(self, args): + auth_service = self._get_auth_service() + name = args.create_token + expires_days = getattr(args, "expires_days", 0) or 0 + + try: + result = auth_service.create_api_token(name, expires_in_days=expires_days) + printer.success(f"API token '{name}' created successfully.") + printer.warning("⚠ Copy this token now. It will NOT be shown again:") + printer.data("Token", result["raw_token"]) + printer.info(f"Token ID: {result['token_id']}") + if expires_days > 0: + printer.info(f"Expires in: {expires_days} days") + else: + printer.info("Expires: Never (permanent)") + except ConnpyError as e: + printer.error(f"Failed to create token: {e}") + sys.exit(1) + except Exception as e: + printer.error(f"Failed to create token: {e}") + sys.exit(1) + + def list_tokens(self, args): + auth_service = self._get_auth_service() + + try: + tokens = auth_service.list_api_tokens() + if not tokens: + printer.info("No API tokens found.") + return + + import yaml + # Clean up empty strings from protobuf defaults + cleaned = [] + for t in tokens: + cleaned.append({ + "token_id": t["token_id"], + "name": t["name"], + "prefix": t["token_prefix"], + "created": t["created_at"] or "N/A", + "last_used": t["last_used_at"] or "Never", + "expires": t["expires_at"] or "Never", + }) + yaml_str = yaml.dump(cleaned, sort_keys=False, default_flow_style=False) + printer.data("API Tokens", yaml_str) + except ConnpyError as e: + printer.error(f"Failed to list tokens: {e}") + sys.exit(1) + except Exception as e: + printer.error(f"Failed to list tokens: {e}") + sys.exit(1) + + def revoke_token(self, args): + auth_service = self._get_auth_service() + token_id = args.revoke_token + + try: + auth_service.revoke_api_token(token_id) + printer.success(f"Token '{token_id}' revoked successfully.") + except ConnpyError as e: + printer.error(f"Failed to revoke token: {e}") + sys.exit(1) + except Exception as e: + printer.error(f"Failed to revoke token: {e}") + sys.exit(1)

    Methods

    +
    +def create_token(self, args) +
    +
    +
    + +Expand source code + +
    def create_token(self, args):
    +    auth_service = self._get_auth_service()
    +    name = args.create_token
    +    expires_days = getattr(args, "expires_days", 0) or 0
    +
    +    try:
    +        result = auth_service.create_api_token(name, expires_in_days=expires_days)
    +        printer.success(f"API token '{name}' created successfully.")
    +        printer.warning("⚠  Copy this token now. It will NOT be shown again:")
    +        printer.data("Token", result["raw_token"])
    +        printer.info(f"Token ID: {result['token_id']}")
    +        if expires_days > 0:
    +            printer.info(f"Expires in: {expires_days} days")
    +        else:
    +            printer.info("Expires: Never (permanent)")
    +    except ConnpyError as e:
    +        printer.error(f"Failed to create token: {e}")
    +        sys.exit(1)
    +    except Exception as e:
    +        printer.error(f"Failed to create token: {e}")
    +        sys.exit(1)
    +
    +
    +
    def dispatch(self, args)
    @@ -216,6 +350,46 @@ el.replaceWith(d);
    +
    +def list_tokens(self, args) +
    +
    +
    + +Expand source code + +
    def list_tokens(self, args):
    +    auth_service = self._get_auth_service()
    +
    +    try:
    +        tokens = auth_service.list_api_tokens()
    +        if not tokens:
    +            printer.info("No API tokens found.")
    +            return
    +
    +        import yaml
    +        # Clean up empty strings from protobuf defaults
    +        cleaned = []
    +        for t in tokens:
    +            cleaned.append({
    +                "token_id": t["token_id"],
    +                "name": t["name"],
    +                "prefix": t["token_prefix"],
    +                "created": t["created_at"] or "N/A",
    +                "last_used": t["last_used_at"] or "Never",
    +                "expires": t["expires_at"] or "Never",
    +            })
    +        yaml_str = yaml.dump(cleaned, sort_keys=False, default_flow_style=False)
    +        printer.data("API Tokens", yaml_str)
    +    except ConnpyError as e:
    +        printer.error(f"Failed to list tokens: {e}")
    +        sys.exit(1)
    +    except Exception as e:
    +        printer.error(f"Failed to list tokens: {e}")
    +        sys.exit(1)
    +
    +
    +
    def login(self, args)
    @@ -225,6 +399,14 @@ el.replaceWith(d); Expand source code
    def login(self, args):
    +    # Handle token management actions first
    +    if getattr(args, "create_token", None):
    +        return self.create_token(args)
    +    if getattr(args, "list_tokens", False):
    +        return self.list_tokens(args)
    +    if getattr(args, "revoke_token", None):
    +        return self.revoke_token(args)
    +
         if getattr(args, "status", False):
             return self.show_status()
     
    @@ -312,6 +494,30 @@ el.replaceWith(d);
     
     
    +
    +def revoke_token(self, args) +
    +
    +
    + +Expand source code + +
    def revoke_token(self, args):
    +    auth_service = self._get_auth_service()
    +    token_id = args.revoke_token
    +
    +    try:
    +        auth_service.revoke_api_token(token_id)
    +        printer.success(f"Token '{token_id}' revoked successfully.")
    +    except ConnpyError as e:
    +        printer.error(f"Failed to revoke token: {e}")
    +        sys.exit(1)
    +    except Exception as e:
    +        printer.error(f"Failed to revoke token: {e}")
    +        sys.exit(1)
    +
    +
    +
    def show_status(self)
    @@ -389,10 +595,13 @@ el.replaceWith(d);
    • LoginHandler

      -
        + diff --git a/docs/connpy/cli/node_handler.html b/docs/connpy/cli/node_handler.html index 49688f0..977bf19 100644 --- a/docs/connpy/cli/node_handler.html +++ b/docs/connpy/cli/node_handler.html @@ -58,7 +58,18 @@ el.replaceWith(d);
        class NodeHandler:
             def __init__(self, app):
                 self.app = app
        -        self.forms = Forms(app)
        +        self._forms = None
        +
        +    @property
        +    def forms(self):
        +        if self._forms is None:
        +            from .forms import Forms
        +            self._forms = Forms(self.app)
        +        return self._forms
        +
        +    @forms.setter
        +    def forms(self, value):
        +        self._forms = value
         
             def _filter_exact_match(self, matches, query):
                 if not query or len(matches) <= 1:
        @@ -146,6 +157,7 @@ el.replaceWith(d);
                     sys.exit(2)
         
                 printer.info(f"Removing: {matches}")
        +        import inquirer
                 question = [inquirer.Confirm("delete", message="Are you sure you want to continue?")]
                 confirm = inquirer.prompt(question)
                 if confirm == None or not confirm["delete"]:
        @@ -306,6 +318,24 @@ el.replaceWith(d);
                     sys.exit(1)
        +

        Instance variables

        +
        +
        prop forms
        +
        +
        + +Expand source code + +
        @property
        +def forms(self):
        +    if self._forms is None:
        +        from .forms import Forms
        +        self._forms = Forms(self.app)
        +    return self._forms
        +
        +
        +
        +

        Methods

        @@ -434,6 +464,7 @@ el.replaceWith(d); sys.exit(2) printer.info(f"Removing: {matches}") + import inquirer question = [inquirer.Confirm("delete", message="Are you sure you want to continue?")] confirm = inquirer.prompt(question) if confirm == None or not confirm["delete"]: @@ -630,6 +661,7 @@ el.replaceWith(d);
      • connect
      • delete
      • dispatch
      • +
      • forms
      • modify
      • show
      • version
      • diff --git a/docs/connpy/cli/profile_handler.html b/docs/connpy/cli/profile_handler.html index 0d6680f..8f81379 100644 --- a/docs/connpy/cli/profile_handler.html +++ b/docs/connpy/cli/profile_handler.html @@ -58,7 +58,18 @@ el.replaceWith(d);
        class ProfileHandler:
             def __init__(self, app):
                 self.app = app
        -        self.forms = Forms(app)
        +        self._forms = None
        +
        +    @property
        +    def forms(self):
        +        if self._forms is None:
        +            from .forms import Forms
        +            self._forms = Forms(self.app)
        +        return self._forms
        +
        +    @forms.setter
        +    def forms(self, value):
        +        self._forms = value
         
             def dispatch(self, args):
                 if not self.app.case:
        @@ -78,6 +89,7 @@ el.replaceWith(d);
                     printer.error("Can't delete default profile")
                     sys.exit(6)
                     
        +        import inquirer
                 question = [inquirer.Confirm("delete", message=f"Are you sure you want to delete {name}?")]
                 confirm = inquirer.prompt(question)
                 if confirm == None or not confirm["delete"]:
        @@ -145,6 +157,24 @@ el.replaceWith(d);
                     sys.exit(1)
        +

        Instance variables

        +
        +
        prop forms
        +
        +
        + +Expand source code + +
        @property
        +def forms(self):
        +    if self._forms is None:
        +        from .forms import Forms
        +        self._forms = Forms(self.app)
        +    return self._forms
        +
        +
        +
        +

        Methods

        @@ -194,6 +224,7 @@ el.replaceWith(d); printer.error("Can't delete default profile") sys.exit(6) + import inquirer question = [inquirer.Confirm("delete", message=f"Are you sure you want to delete {name}?")] confirm = inquirer.prompt(question) if confirm == None or not confirm["delete"]: @@ -300,10 +331,11 @@ el.replaceWith(d);
        • ProfileHandler

          -
            + diff --git a/docs/connpy/cli/shell_handler.html b/docs/connpy/cli/shell_handler.html new file mode 100644 index 0000000..71185eb --- /dev/null +++ b/docs/connpy/cli/shell_handler.html @@ -0,0 +1,187 @@ + + + + + + +connpy.cli.shell_handler API documentation + + + + + + + + + + + +
            +
            +
            +

            Module connpy.cli.shell_handler

            +
            +
            +
            +
            +
            +
            +
            +
            +
            +
            +

            Classes

            +
            +
            +class ShellHandler +(app) +
            +
            +
            + +Expand source code + +
            class ShellHandler:
            +    def __init__(self, app):
            +        self.app = app
            +
            +    def dispatch(self, args):
            +        shell_config = self.app.config.config.get("shell", {}) if hasattr(self.app.config, "config") else {}
            +        command = getattr(args, 'command_override', None) or shell_config.get("command") or os.environ.get("SHELL", "/bin/bash")
            +
            +        try:
            +            exe = shlex.split(command)[0]
            +        except Exception:
            +            exe = command
            +
            +        if not shutil.which(exe):
            +            printer.error(f"Shell command executable not found: {exe}")
            +            sys.exit(1)
            +
            +        node_info = self._build_local_identity(shell_config)
            +
            +        tags = {
            +            "os": node_info["os"],
            +            "prompt": node_info["prompt"]
            +        }
            +
            +        n = node(
            +            unique=node_info["name"],
            +            host=command,
            +            protocol="local",
            +            config=self.app.config,
            +            tags=tags
            +        )
            +
            +        capture_file = getattr(args, 'capture_file', None)
            +        if capture_file:
            +            n.logs = capture_file
            +        elif shell_config.get("logging"):
            +            n.logs = shell_config.get("log_path", os.path.expanduser("~/.config/conn/shell_logs/session.log"))
            +
            +        n.interact(debug=getattr(args, 'debug', False))
            +
            +    def _build_local_identity(self, shell_config):
            +        return {
            +            "name": "local-shell",
            +            "host": socket.gethostname(),
            +            "os": shell_config.get("os", "linux"),
            +            "prompt": shell_config.get("prompt", r'\$\s*$|#\s*$')
            +        }
            +
            +
            +

            Methods

            +
            +
            +def dispatch(self, args) +
            +
            +
            + +Expand source code + +
            def dispatch(self, args):
            +    shell_config = self.app.config.config.get("shell", {}) if hasattr(self.app.config, "config") else {}
            +    command = getattr(args, 'command_override', None) or shell_config.get("command") or os.environ.get("SHELL", "/bin/bash")
            +
            +    try:
            +        exe = shlex.split(command)[0]
            +    except Exception:
            +        exe = command
            +
            +    if not shutil.which(exe):
            +        printer.error(f"Shell command executable not found: {exe}")
            +        sys.exit(1)
            +
            +    node_info = self._build_local_identity(shell_config)
            +
            +    tags = {
            +        "os": node_info["os"],
            +        "prompt": node_info["prompt"]
            +    }
            +
            +    n = node(
            +        unique=node_info["name"],
            +        host=command,
            +        protocol="local",
            +        config=self.app.config,
            +        tags=tags
            +    )
            +
            +    capture_file = getattr(args, 'capture_file', None)
            +    if capture_file:
            +        n.logs = capture_file
            +    elif shell_config.get("logging"):
            +        n.logs = shell_config.get("log_path", os.path.expanduser("~/.config/conn/shell_logs/session.log"))
            +
            +    n.interact(debug=getattr(args, 'debug', False))
            +
            +
            +
            +
            +
            +
            +
            +
            + +
            + + + diff --git a/docs/connpy/cli/sso_handler.html b/docs/connpy/cli/sso_handler.html index 01406bb..cb9e10f 100644 --- a/docs/connpy/cli/sso_handler.html +++ b/docs/connpy/cli/sso_handler.html @@ -92,6 +92,7 @@ el.replaceWith(d); sys.exit(1) def add_provider(self, args): + import inquirer provider = args.provider sso = self.app.config.config.get("sso", {}) providers = sso.setdefault("providers", {}) @@ -165,6 +166,7 @@ el.replaceWith(d); sys.exit(1) # Confirm delete + import inquirer questions = [inquirer.Confirm("confirm", message=f"Are you sure you want to delete SSO Provider '{provider}'?", default=False)] answers = inquirer.prompt(questions) if not answers or not answers["confirm"]: @@ -225,6 +227,7 @@ el.replaceWith(d); Expand source code
            def add_provider(self, args):
            +    import inquirer
                 provider = args.provider
                 sso = self.app.config.config.get("sso", {})
                 providers = sso.setdefault("providers", {})
            @@ -308,6 +311,7 @@ el.replaceWith(d);
                     sys.exit(1)
                     
                 # Confirm delete
            +    import inquirer
                 questions = [inquirer.Confirm("confirm", message=f"Are you sure you want to delete SSO Provider '{provider}'?", default=False)]
                 answers = inquirer.prompt(questions)
                 if not answers or not answers["confirm"]:
            diff --git a/docs/connpy/cli/terminal_ui.html b/docs/connpy/cli/terminal_ui.html
            index f53544e..c53528f 100644
            --- a/docs/connpy/cli/terminal_ui.html
            +++ b/docs/connpy/cli/terminal_ui.html
            @@ -57,25 +57,39 @@ el.replaceWith(d);
             
             
            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.session_state = session_state if session_state is not None else {
            -            'persona': 'engineer',
            -            'trust_mode': False,
            -            'memories': [],
            -            'os': None,
            -            'prompt': None
            -        }
            +        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('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)
             
            -        self.mode_range, self.mode_single, self.mode_lines = 0, 1, 2 
            +    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."""
            @@ -109,16 +123,52 @@ el.replaceWith(d);
                             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:
            +                if last_total_cmds is not None and total_cmds > last_total_cmds and saved_cmd > 1:
            +                    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': 1,
            -                'total_cmds': len(blocks),
            -                'total_lines': len(buffer.split('\n')),
            -                'context_lines': min(50, len(buffer.split('\n'))),
            -                'context_mode': self.mode_range,
            +                '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
                         self.console.print("") # Real line break
            @@ -137,6 +187,7 @@ el.replaceWith(d);
                                 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):
            @@ -144,6 +195,7 @@ el.replaceWith(d);
                                 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):
            @@ -153,6 +205,7 @@ el.replaceWith(d);
                                 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')
            @@ -575,16 +628,52 @@ el.replaceWith(d);
                         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:
            +            if last_total_cmds is not None and total_cmds > last_total_cmds and saved_cmd > 1:
            +                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': 1,
            -            'total_cmds': len(blocks),
            -            'total_lines': len(buffer.split('\n')),
            -            'context_lines': min(50, len(buffer.split('\n'))),
            -            'context_mode': self.mode_range,
            +            '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
                     self.console.print("") # Real line break
            @@ -603,6 +692,7 @@ el.replaceWith(d);
                             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):
            @@ -610,6 +700,7 @@ el.replaceWith(d);
                             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):
            @@ -619,6 +710,7 @@ el.replaceWith(d);
                             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')
            diff --git a/docs/connpy/cli/validators.html b/docs/connpy/cli/validators.html
            index 3bbf7cd..a88da20 100644
            --- a/docs/connpy/cli/validators.html
            +++ b/docs/connpy/cli/validators.html
            @@ -61,61 +61,61 @@ el.replaceWith(d);
             
                 def host_validation(self, answers, current, regex = "^.+$"):
                     if not re.match(regex, current):
            -            raise inquirer.errors.ValidationError("", reason="Host cannot be empty")
            +            _raise_val_err("Host cannot be empty")
                     if current.startswith("@"):
                         if current[1:] not in self.app.profiles:
            -                raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +                _raise_val_err("Profile {} don't exist".format(current))
                     return True
             
                 def profile_protocol_validation(self, answers, current, regex = "(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)"):
                     if not re.match(regex, current):
            -            raise inquirer.errors.ValidationError("", reason="Pick between ssh, telnet, kubectl, docker, ssm or leave empty")
            +            _raise_val_err("Pick between ssh, telnet, kubectl, docker, ssm or leave empty")
                     return True
             
                 def protocol_validation(self, answers, current, regex = "(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)"):
                     if not re.match(regex, current):
            -            raise inquirer.errors.ValidationError("", reason="Pick between ssh, telnet, kubectl, docker, ssm, leave empty or @profile")
            +            _raise_val_err("Pick between ssh, telnet, kubectl, docker, ssm, leave empty or @profile")
                     if current.startswith("@"):
                         if current[1:] not in self.app.profiles:
            -                raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +                _raise_val_err("Profile {} don't exist".format(current))
                     return True
             
                 def profile_port_validation(self, answers, current, regex = "(^[0-9]*$)"):
                     if not re.match(regex, current):
            -            raise inquirer.errors.ValidationError("", reason="Pick a port between 1-65535, @profile o leave empty")
            +            _raise_val_err("Pick a port between 1-65535, @profile o leave empty")
                     try:
                         port = int(current)
                     except ValueError:
                         port = 0
                     if current != "" and not 1 <= int(port) <= 65535:
            -            raise inquirer.errors.ValidationError("", reason="Pick a port between 1-65535 or leave empty")
            +            _raise_val_err("Pick a port between 1-65535 or leave empty")
                     return True
             
                 def port_validation(self, answers, current, regex = "(^[0-9]*$|^@.+$)"):
                     if not re.match(regex, current):
            -            raise inquirer.errors.ValidationError("", reason="Pick a port between 1-65535, @profile or leave empty")
            +            _raise_val_err("Pick a port between 1-65535, @profile or leave empty")
                     try:
                         port = int(current)
                     except ValueError:
                         port = 0
                     if current.startswith("@"):
                         if current[1:] not in self.app.profiles:
            -                raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +                _raise_val_err("Profile {} don't exist".format(current))
                     elif current != "" and not 1 <= int(port) <= 65535:
            -            raise inquirer.errors.ValidationError("", reason="Pick a port between 1-65535, @profile o leave empty")
            +            _raise_val_err("Pick a port between 1-65535, @profile o leave empty")
                     return True
             
                 def pass_validation(self, answers, current, regex = "(^@.+$)"):
                     profiles = current.split(",")
                     for i in profiles:
                         if not re.match(regex, i) or i[1:] not in self.app.profiles:
            -                raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(i))
            +                _raise_val_err("Profile {} don't exist".format(i))
                     return True
             
                 def tags_validation(self, answers, current):
                     if current.startswith("@"):
                         if current[1:] not in self.app.profiles:
            -                raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +                _raise_val_err("Profile {} don't exist".format(current))
                     elif current != "":
                         isdict = False
                         try:
            @@ -123,7 +123,7 @@ el.replaceWith(d);
                         except Exception:
                             pass
                         if not isinstance (isdict, dict):
            -                raise inquirer.errors.ValidationError("", reason="Tags should be a python dictionary.".format(current))
            +                _raise_val_err("Tags should be a python dictionary.".format(current))
                     return True
             
                 def profile_tags_validation(self, answers, current):
            @@ -134,36 +134,36 @@ el.replaceWith(d);
                         except Exception:
                             pass
                         if not isinstance (isdict, dict):
            -                raise inquirer.errors.ValidationError("", reason="Tags should be a python dictionary.".format(current))
            +                _raise_val_err("Tags should be a python dictionary.".format(current))
                     return True
             
                 def jumphost_validation(self, answers, current):
                     if current.startswith("@"):
                         if current[1:] not in self.app.profiles:
            -                raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +                _raise_val_err("Profile {} don't exist".format(current))
                     elif current != "":
                         if current not in self.app.nodes_list:
            -                raise inquirer.errors.ValidationError("", reason="Node {} don't exist.".format(current))
            +                _raise_val_err("Node {} don't exist.".format(current))
                     return True
             
                 def profile_jumphost_validation(self, answers, current):
                     if current != "":
                         if current not in self.app.nodes_list:
            -                raise inquirer.errors.ValidationError("", reason="Node {} don't exist.".format(current))
            +                _raise_val_err("Node {} don't exist.".format(current))
                     return True
             
                 def default_validation(self, answers, current):
                     if current.startswith("@"):
                         if current[1:] not in self.app.profiles:
            -                raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +                _raise_val_err("Profile {} don't exist".format(current))
                     return True
             
                 def bulk_node_validation(self, answers, current, regex = "^[0-9a-zA-Z_.,$#-]+$"):
                     if not re.match(regex, current):
            -            raise inquirer.errors.ValidationError("", reason="Host cannot be empty")
            +            _raise_val_err("Host cannot be empty")
                     if current.startswith("@"):
                         if current[1:] not in self.app.profiles:
            -                raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +                _raise_val_err("Profile {} don't exist".format(current))
                     return True
             
                 def bulk_folder_validation(self, answers, current):
            @@ -176,19 +176,19 @@ el.replaceWith(d);
                         
                     matches = list(filter(lambda k: k == candidate, self.app.folders))
                     if current != "" and len(matches) == 0:
            -            raise inquirer.errors.ValidationError("", reason="Location {} don't exist".format(current))
            +            _raise_val_err("Location {} don't exist".format(current))
                     return True
             
                 def bulk_host_validation(self, answers, current, regex = "^.+$"):
                     if not re.match(regex, current):
            -            raise inquirer.errors.ValidationError("", reason="Host cannot be empty")
            +            _raise_val_err("Host cannot be empty")
                     if current.startswith("@"):
                         if current[1:] not in self.app.profiles:
            -                raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +                _raise_val_err("Profile {} don't exist".format(current))
                     hosts = current.split(",")
                     nodes = answers["ids"].split(",")
                     if len(hosts) > 1 and len(hosts) != len(nodes):
            -                raise inquirer.errors.ValidationError("", reason="Hosts list should be the same length of nodes list")
            +                _raise_val_err("Hosts list should be the same length of nodes list")
                     return True
            @@ -212,7 +212,7 @@ el.replaceWith(d); matches = list(filter(lambda k: k == candidate, self.app.folders)) if current != "" and len(matches) == 0: - raise inquirer.errors.ValidationError("", reason="Location {} don't exist".format(current)) + _raise_val_err("Location {} don't exist".format(current)) return True
            @@ -227,14 +227,14 @@ el.replaceWith(d);
            def bulk_host_validation(self, answers, current, regex = "^.+$"):
                 if not re.match(regex, current):
            -        raise inquirer.errors.ValidationError("", reason="Host cannot be empty")
            +        _raise_val_err("Host cannot be empty")
                 if current.startswith("@"):
                     if current[1:] not in self.app.profiles:
            -            raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +            _raise_val_err("Profile {} don't exist".format(current))
                 hosts = current.split(",")
                 nodes = answers["ids"].split(",")
                 if len(hosts) > 1 and len(hosts) != len(nodes):
            -            raise inquirer.errors.ValidationError("", reason="Hosts list should be the same length of nodes list")
            +            _raise_val_err("Hosts list should be the same length of nodes list")
                 return True
            @@ -249,10 +249,10 @@ el.replaceWith(d);
            def bulk_node_validation(self, answers, current, regex = "^[0-9a-zA-Z_.,$#-]+$"):
                 if not re.match(regex, current):
            -        raise inquirer.errors.ValidationError("", reason="Host cannot be empty")
            +        _raise_val_err("Host cannot be empty")
                 if current.startswith("@"):
                     if current[1:] not in self.app.profiles:
            -            raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +            _raise_val_err("Profile {} don't exist".format(current))
                 return True
            @@ -268,7 +268,7 @@ el.replaceWith(d);
            def default_validation(self, answers, current):
                 if current.startswith("@"):
                     if current[1:] not in self.app.profiles:
            -            raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +            _raise_val_err("Profile {} don't exist".format(current))
                 return True
            @@ -283,10 +283,10 @@ el.replaceWith(d);
            def host_validation(self, answers, current, regex = "^.+$"):
                 if not re.match(regex, current):
            -        raise inquirer.errors.ValidationError("", reason="Host cannot be empty")
            +        _raise_val_err("Host cannot be empty")
                 if current.startswith("@"):
                     if current[1:] not in self.app.profiles:
            -            raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +            _raise_val_err("Profile {} don't exist".format(current))
                 return True
            @@ -302,10 +302,10 @@ el.replaceWith(d);
            def jumphost_validation(self, answers, current):
                 if current.startswith("@"):
                     if current[1:] not in self.app.profiles:
            -            raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
            +            _raise_val_err("Profile {} don't exist".format(current))
                 elif current != "":
                     if current not in self.app.nodes_list:
            -            raise inquirer.errors.ValidationError("", reason="Node {} don't exist.".format(current))
            +            _raise_val_err("Node {} don't exist.".format(current))
                 return True
            @@ -322,7 +322,7 @@ el.replaceWith(d); profiles = current.split(",") for i in profiles: if not re.match(regex, i) or i[1:] not in self.app.profiles: - raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(i)) + _raise_val_err("Profile {} don't exist".format(i)) return True
    @@ -337,16 +337,16 @@ el.replaceWith(d);
    def port_validation(self, answers, current, regex = "(^[0-9]*$|^@.+$)"):
         if not re.match(regex, current):
    -        raise inquirer.errors.ValidationError("", reason="Pick a port between 1-65535, @profile or leave empty")
    +        _raise_val_err("Pick a port between 1-65535, @profile or leave empty")
         try:
             port = int(current)
         except ValueError:
             port = 0
         if current.startswith("@"):
             if current[1:] not in self.app.profiles:
    -            raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
    +            _raise_val_err("Profile {} don't exist".format(current))
         elif current != "" and not 1 <= int(port) <= 65535:
    -        raise inquirer.errors.ValidationError("", reason="Pick a port between 1-65535, @profile o leave empty")
    +        _raise_val_err("Pick a port between 1-65535, @profile o leave empty")
         return True
    @@ -362,7 +362,7 @@ el.replaceWith(d);
    def profile_jumphost_validation(self, answers, current):
         if current != "":
             if current not in self.app.nodes_list:
    -            raise inquirer.errors.ValidationError("", reason="Node {} don't exist.".format(current))
    +            _raise_val_err("Node {} don't exist.".format(current))
         return True
    @@ -377,13 +377,13 @@ el.replaceWith(d);
    def profile_port_validation(self, answers, current, regex = "(^[0-9]*$)"):
         if not re.match(regex, current):
    -        raise inquirer.errors.ValidationError("", reason="Pick a port between 1-65535, @profile o leave empty")
    +        _raise_val_err("Pick a port between 1-65535, @profile o leave empty")
         try:
             port = int(current)
         except ValueError:
             port = 0
         if current != "" and not 1 <= int(port) <= 65535:
    -        raise inquirer.errors.ValidationError("", reason="Pick a port between 1-65535 or leave empty")
    +        _raise_val_err("Pick a port between 1-65535 or leave empty")
         return True
    @@ -398,7 +398,7 @@ el.replaceWith(d);
    def profile_protocol_validation(self, answers, current, regex = "(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)"):
         if not re.match(regex, current):
    -        raise inquirer.errors.ValidationError("", reason="Pick between ssh, telnet, kubectl, docker, ssm or leave empty")
    +        _raise_val_err("Pick between ssh, telnet, kubectl, docker, ssm or leave empty")
         return True
    @@ -419,7 +419,7 @@ el.replaceWith(d); except Exception: pass if not isinstance (isdict, dict): - raise inquirer.errors.ValidationError("", reason="Tags should be a python dictionary.".format(current)) + _raise_val_err("Tags should be a python dictionary.".format(current)) return True
    @@ -434,10 +434,10 @@ el.replaceWith(d);
    def protocol_validation(self, answers, current, regex = "(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)"):
         if not re.match(regex, current):
    -        raise inquirer.errors.ValidationError("", reason="Pick between ssh, telnet, kubectl, docker, ssm, leave empty or @profile")
    +        _raise_val_err("Pick between ssh, telnet, kubectl, docker, ssm, leave empty or @profile")
         if current.startswith("@"):
             if current[1:] not in self.app.profiles:
    -            raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
    +            _raise_val_err("Profile {} don't exist".format(current))
         return True
    @@ -453,7 +453,7 @@ el.replaceWith(d);
    def tags_validation(self, answers, current):
         if current.startswith("@"):
             if current[1:] not in self.app.profiles:
    -            raise inquirer.errors.ValidationError("", reason="Profile {} don't exist".format(current))
    +            _raise_val_err("Profile {} don't exist".format(current))
         elif current != "":
             isdict = False
             try:
    @@ -461,7 +461,7 @@ el.replaceWith(d);
             except Exception:
                 pass
             if not isinstance (isdict, dict):
    -            raise inquirer.errors.ValidationError("", reason="Tags should be a python dictionary.".format(current))
    +            _raise_val_err("Tags should be a python dictionary.".format(current))
         return True
    diff --git a/docs/connpy/grpc_layer/connpy_pb2_grpc.html b/docs/connpy/grpc_layer/connpy_pb2_grpc.html index d9af6ba..c6b6408 100644 --- a/docs/connpy/grpc_layer/connpy_pb2_grpc.html +++ b/docs/connpy/grpc_layer/connpy_pb2_grpc.html @@ -153,6 +153,21 @@ el.replaceWith(d); request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, response_serializer=connpy__pb2.SSOProvidersResponse.SerializeToString, ), + 'create_api_token': grpc.unary_unary_rpc_method_handler( + servicer.create_api_token, + request_deserializer=connpy__pb2.CreateApiTokenRequest.FromString, + response_serializer=connpy__pb2.CreateApiTokenResponse.SerializeToString, + ), + 'list_api_tokens': grpc.unary_unary_rpc_method_handler( + servicer.list_api_tokens, + request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + response_serializer=connpy__pb2.ListApiTokensResponse.SerializeToString, + ), + 'revoke_api_token': grpc.unary_unary_rpc_method_handler( + servicer.revoke_api_token, + request_deserializer=connpy__pb2.RevokeApiTokenRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), } generic_handler = grpc.method_handlers_generic_handler( 'connpy.AuthService', rpc_method_handlers) @@ -1779,6 +1794,87 @@ def predict_execution_results(request, wait_for_ready, timeout, metadata, + _registered_method=True) + + @staticmethod + def create_api_token(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/connpy.AuthService/create_api_token', + connpy__pb2.CreateApiTokenRequest.SerializeToString, + connpy__pb2.CreateApiTokenResponse.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def list_api_tokens(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/connpy.AuthService/list_api_tokens', + google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + connpy__pb2.ListApiTokensResponse.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def revoke_api_token(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/connpy.AuthService/revoke_api_token', + connpy__pb2.RevokeApiTokenRequest.SerializeToString, + google_dot_protobuf_dot_empty__pb2.Empty.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, _registered_method=True)

    Missing associated documentation comment in .proto file.

    @@ -1821,6 +1917,43 @@ def change_password(request,
    +
    +def create_api_token(request,
    target,
    options=(),
    channel_credentials=None,
    call_credentials=None,
    insecure=False,
    compression=None,
    wait_for_ready=None,
    timeout=None,
    metadata=None)
    +
    +
    +
    + +Expand source code + +
    @staticmethod
    +def create_api_token(request,
    +        target,
    +        options=(),
    +        channel_credentials=None,
    +        call_credentials=None,
    +        insecure=False,
    +        compression=None,
    +        wait_for_ready=None,
    +        timeout=None,
    +        metadata=None):
    +    return grpc.experimental.unary_unary(
    +        request,
    +        target,
    +        '/connpy.AuthService/create_api_token',
    +        connpy__pb2.CreateApiTokenRequest.SerializeToString,
    +        connpy__pb2.CreateApiTokenResponse.FromString,
    +        options,
    +        channel_credentials,
    +        insecure,
    +        call_credentials,
    +        compression,
    +        wait_for_ready,
    +        timeout,
    +        metadata,
    +        _registered_method=True)
    +
    +
    +
    def get_sso_providers(request,
    target,
    options=(),
    channel_credentials=None,
    call_credentials=None,
    insecure=False,
    compression=None,
    wait_for_ready=None,
    timeout=None,
    metadata=None)
    @@ -1858,6 +1991,43 @@ def get_sso_providers(request,
    +
    +def list_api_tokens(request,
    target,
    options=(),
    channel_credentials=None,
    call_credentials=None,
    insecure=False,
    compression=None,
    wait_for_ready=None,
    timeout=None,
    metadata=None)
    +
    +
    +
    + +Expand source code + +
    @staticmethod
    +def list_api_tokens(request,
    +        target,
    +        options=(),
    +        channel_credentials=None,
    +        call_credentials=None,
    +        insecure=False,
    +        compression=None,
    +        wait_for_ready=None,
    +        timeout=None,
    +        metadata=None):
    +    return grpc.experimental.unary_unary(
    +        request,
    +        target,
    +        '/connpy.AuthService/list_api_tokens',
    +        google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
    +        connpy__pb2.ListApiTokensResponse.FromString,
    +        options,
    +        channel_credentials,
    +        insecure,
    +        call_credentials,
    +        compression,
    +        wait_for_ready,
    +        timeout,
    +        metadata,
    +        _registered_method=True)
    +
    +
    +
    def login(request,
    target,
    options=(),
    channel_credentials=None,
    call_credentials=None,
    insecure=False,
    compression=None,
    wait_for_ready=None,
    timeout=None,
    metadata=None)
    @@ -1932,6 +2102,43 @@ def login_sso(request,
    +
    +def revoke_api_token(request,
    target,
    options=(),
    channel_credentials=None,
    call_credentials=None,
    insecure=False,
    compression=None,
    wait_for_ready=None,
    timeout=None,
    metadata=None)
    +
    +
    +
    + +Expand source code + +
    @staticmethod
    +def revoke_api_token(request,
    +        target,
    +        options=(),
    +        channel_credentials=None,
    +        call_credentials=None,
    +        insecure=False,
    +        compression=None,
    +        wait_for_ready=None,
    +        timeout=None,
    +        metadata=None):
    +    return grpc.experimental.unary_unary(
    +        request,
    +        target,
    +        '/connpy.AuthService/revoke_api_token',
    +        connpy__pb2.RevokeApiTokenRequest.SerializeToString,
    +        google_dot_protobuf_dot_empty__pb2.Empty.FromString,
    +        options,
    +        channel_credentials,
    +        insecure,
    +        call_credentials,
    +        compression,
    +        wait_for_ready,
    +        timeout,
    +        metadata,
    +        _registered_method=True)
    +
    +
    +
    @@ -1964,6 +2171,24 @@ def login_sso(request, raise NotImplementedError('Method not implemented!') def get_sso_providers(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def create_api_token(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def list_api_tokens(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def revoke_api_token(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') @@ -1992,6 +2217,22 @@ def login_sso(request,

    Missing associated documentation comment in .proto file.

    +
    +def create_api_token(self, request, context) +
    +
    +
    + +Expand source code + +
    def create_api_token(self, request, context):
    +    """Missing associated documentation comment in .proto file."""
    +    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    +    context.set_details('Method not implemented!')
    +    raise NotImplementedError('Method not implemented!')
    +
    +

    Missing associated documentation comment in .proto file.

    +
    def get_sso_providers(self, request, context)
    @@ -2008,6 +2249,22 @@ def login_sso(request,

    Missing associated documentation comment in .proto file.

    +
    +def list_api_tokens(self, request, context) +
    +
    +
    + +Expand source code + +
    def list_api_tokens(self, request, context):
    +    """Missing associated documentation comment in .proto file."""
    +    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    +    context.set_details('Method not implemented!')
    +    raise NotImplementedError('Method not implemented!')
    +
    +

    Missing associated documentation comment in .proto file.

    +
    def login(self, request, context)
    @@ -2040,6 +2297,22 @@ def login_sso(request,

    Missing associated documentation comment in .proto file.

    +
    +def revoke_api_token(self, request, context) +
    +
    +
    + +Expand source code + +
    def revoke_api_token(self, request, context):
    +    """Missing associated documentation comment in .proto file."""
    +    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    +    context.set_details('Method not implemented!')
    +    raise NotImplementedError('Method not implemented!')
    +
    +

    Missing associated documentation comment in .proto file.

    +
    @@ -2079,6 +2352,21 @@ def login_sso(request, '/connpy.AuthService/get_sso_providers', request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, response_deserializer=connpy__pb2.SSOProvidersResponse.FromString, + _registered_method=True) + self.create_api_token = channel.unary_unary( + '/connpy.AuthService/create_api_token', + request_serializer=connpy__pb2.CreateApiTokenRequest.SerializeToString, + response_deserializer=connpy__pb2.CreateApiTokenResponse.FromString, + _registered_method=True) + self.list_api_tokens = channel.unary_unary( + '/connpy.AuthService/list_api_tokens', + request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + response_deserializer=connpy__pb2.ListApiTokensResponse.FromString, + _registered_method=True) + self.revoke_api_token = channel.unary_unary( + '/connpy.AuthService/revoke_api_token', + request_serializer=connpy__pb2.RevokeApiTokenRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, _registered_method=True)

    Missing associated documentation comment in .proto file.

    @@ -6510,20 +6798,26 @@ def stop_api(request,
  • AuthService

    -
      +
    • AuthServiceServicer

      -
        +
      • diff --git a/docs/connpy/grpc_layer/server.html b/docs/connpy/grpc_layer/server.html index 03e7a8c..5a94c52 100644 --- a/docs/connpy/grpc_layer/server.html +++ b/docs/connpy/grpc_layer/server.html @@ -514,6 +514,8 @@ def service(self): return self._unauthenticated_handler(handler_call_details, "Authorization token is missing") username = self.registry.user_service.verify_jwt(token) + if not username and token.startswith("cnp_pat_"): + username = self.registry.user_service.verify_api_token(token) if not username: return self._unauthenticated_handler(handler_call_details, "Invalid or expired token") @@ -628,6 +630,8 @@ def service(self): return self._unauthenticated_handler(handler_call_details, "Authorization token is missing") username = self.registry.user_service.verify_jwt(token) + if not username and token.startswith("cnp_pat_"): + username = self.registry.user_service.verify_api_token(token) if not username: return self._unauthenticated_handler(handler_call_details, "Invalid or expired token") @@ -834,6 +838,58 @@ interceptor chooses to service this RPC, or None otherwise.

  • except ValueError as e: context.abort(grpc.StatusCode.INVALID_ARGUMENT, str(e)) + return Empty() + + @handle_errors + def create_api_token(self, request, context): + username = _current_user.get() + if not username: + context.abort(grpc.StatusCode.UNAUTHENTICATED, "Authentication required") + + try: + expires_in_days = request.expires_in_days if request.expires_in_days > 0 else None + result = self.registry.user_service.create_api_token( + username, request.name, expires_in_days=expires_in_days + ) + except ValueError as e: + context.abort(grpc.StatusCode.INVALID_ARGUMENT, str(e)) + + return connpy_pb2.CreateApiTokenResponse( + token_id=result["token_id"], + raw_token=result["raw_token"], + name=result["name"], + ) + + @handle_errors + def list_api_tokens(self, request, context): + username = _current_user.get() + if not username: + context.abort(grpc.StatusCode.UNAUTHENTICATED, "Authentication required") + + tokens = self.registry.user_service.list_api_tokens(username) + token_infos = [ + connpy_pb2.ApiTokenInfo( + token_id=t["token_id"], + name=t.get("name") or "", + token_prefix=t.get("token_prefix") or "", + created_at=t.get("created_at") or "", + last_used_at=t.get("last_used_at") or "", + expires_at=t.get("expires_at") or "", + ) + for t in tokens + ] + return connpy_pb2.ListApiTokensResponse(tokens=token_infos) + + @handle_errors + def revoke_api_token(self, request, context): + username = _current_user.get() + if not username: + context.abort(grpc.StatusCode.UNAUTHENTICATED, "Authentication required") + + removed = self.registry.user_service.revoke_api_token(username, request.token_id) + if not removed: + context.abort(grpc.StatusCode.NOT_FOUND, f"Token '{request.token_id}' not found") + return Empty()

    Missing associated documentation comment in .proto file.

    @@ -846,9 +902,12 @@ interceptor chooses to service this RPC, or None otherwise.

  • AuthServiceServicer:
  • @@ -1496,10 +1555,59 @@ interceptor chooses to service this RPC, or None otherwise.

    raw_bytes = str(raw_bytes).encode() from connpy.utils import log_cleaner - last_line = log_cleaner(raw_bytes.decode(errors='replace')).split('\n')[-1].strip() + cleaned_buffer = log_cleaner(raw_bytes.decode(errors='replace')) + last_line = cleaned_buffer.split('\n')[-1].strip() if cleaned_buffer.strip() else "(prompt)" blocks = service.build_context_blocks(raw_bytes, n.cmd_byte_positions, node_info, last_line=last_line) node_info["context_blocks"] = blocks + total_cmds = len(blocks) + total_lines = len(cleaned_buffer.split('\n')) + + if not hasattr(remote_stream, 'copilot_state') or remote_stream.copilot_state is None: + remote_stream.copilot_state = {} + session_state = remote_stream.copilot_state + + if isinstance(node_info, dict): + for k, v in node_info.items(): + if k in ('context_mode', 'context_cmd', 'context_lines', 'persona', 'trust', 'os', 'prompt'): + session_state[k] = v + + saved_mode = session_state.get('context_mode', 0) + saved_cmd = session_state.get('context_cmd', 1) + saved_lines = session_state.get('context_lines', 50) + last_total_cmds = session_state.get('last_total_cmds', None) + last_total_lines = session_state.get('last_total_lines', None) + + is_range = saved_mode in (0, 'RANGE', 'range') + is_lines = saved_mode in (2, 'LINES', 'lines') + is_single = saved_mode in (1, 'SINGLE', 'single') + + if is_range or is_single: + if last_total_cmds is not None and total_cmds > last_total_cmds and saved_cmd > 1: + 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 + + session_state['context_cmd'] = max(1, initial_cmd) + session_state['context_lines'] = max(1, initial_lines) + session_state['last_total_cmds'] = total_cmds + session_state['last_total_lines'] = total_lines + + node_info.update(session_state) + node_info['context_cmd'] = min(session_state['context_cmd'], max(1, total_cmds)) + node_info['context_lines'] = min(session_state['context_lines'], max(1, total_lines)) node_info_json = json.dumps(node_info) # Convert buffer to string if it's bytes for the preview @@ -1544,6 +1652,17 @@ interceptor chooses to service this RPC, or None otherwise.

    if req_session_id and req_session_id != copilot_session_id: continue # Ignore stale request from a previous session + merged_node_info_str = req_data.get("node_info_json", "") + if merged_node_info_str: + try: + merged_node_info = json.loads(merged_node_info_str) + node_info.update(merged_node_info) + # Sync context state from frontend into session_state for persistence + for k in ('context_mode', 'context_cmd', 'context_lines'): + if k in merged_node_info: + session_state[k] = merged_node_info[k] + except: pass + if "question" not in req_data or not req_data["question"] or req_data["question"] == "CANCEL" or req_data.get("action") in ("cancel", "web_cancel"): if req_data.get("action") == "web_cancel": os.write(child_fd, b'\x05') @@ -1551,13 +1670,6 @@ interceptor chooses to service this RPC, or None otherwise.

    os.write(child_fd, b'\x15\r') return question = req_data["question"] - - merged_node_info_str = req_data.get("node_info_json", "") - if merged_node_info_str: - try: - merged_node_info = json.loads(merged_node_info_str) - node_info.update(merged_node_info) - except: pass context_buffer = req_data.get("context_buffer", "") if context_buffer.startswith('{"context_start_pos"'): @@ -1620,6 +1732,15 @@ interceptor chooses to service this RPC, or None otherwise.

    if not action_data: return action = action_data.get("action", "cancel") + merged_node_info_str = action_data.get("node_info_json", "") + if merged_node_info_str: + try: + merged_node_info = json.loads(merged_node_info_str) + for k in ('context_mode', 'context_cmd', 'context_lines'): + if k in merged_node_info: + session_state[k] = merged_node_info[k] + except: pass + if action == "continue": continue # Loop back for next question diff --git a/docs/connpy/grpc_layer/stubs.html b/docs/connpy/grpc_layer/stubs.html index 80fce9c..0746793 100644 --- a/docs/connpy/grpc_layer/stubs.html +++ b/docs/connpy/grpc_layer/stubs.html @@ -864,7 +864,37 @@ Call-Future's exception value will be an RpcError.

    @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) + 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

    @@ -884,6 +914,51 @@ def change_password(self, old_password, new_password):
    +
    +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)
    @@ -904,6 +979,21 @@ def login(self, username, password):
    +
    +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)
    +
    +
    +
    @@ -2785,7 +2875,10 @@ def stop_api(self):

    AuthStub

  • diff --git a/docs/connpy/index.html b/docs/connpy/index.html index facfec7..f974912 100644 --- a/docs/connpy/index.html +++ b/docs/connpy/index.html @@ -41,7 +41,7 @@ el.replaceWith(d);

    App Logo

    -

    Connpy (v6.0.3)

    +

    Connpy (v6.1.0)

    @@ -71,6 +71,20 @@ el.replaceWith(d);

    Connect to external data sources and tools dynamically via the Model Context Protocol (MCP). Use the interactive wizard or command actions to configure MCP servers:

    conn ai --mcp
     
    +

    1d. Local Interactive Shell (conn shell)

    +

    Launch a local interactive shell with AI Copilot support enabled directly on your host machine:

    +
    conn shell                     # Start local shell (default: $SHELL or /bin/bash)
    +conn shell -c /bin/zsh         # Override shell executable
    +conn shell --capture session.log # Log session output to file
    +
    +
      +
    • Nested Sessions & Passthrough: Supports running nested conn / connpy connections inside conn shell. Automatically detects foreground conn processes and forwards Ctrl+Space down to the active device connection instead of triggering the local Copilot.
    • +
    • Shell Configuration: Configure default shell command, prompt regex, or OS type via conn config:
    • +
    +
    conn config --shell-command /bin/zsh
    +conn config --shell-prompt "\$\s*$"
    +conn config --shell-os ubuntu
    +

    2. ⚙️ Automation & Playbooks

    2a. Quick Run (conn run)

    @@ -165,13 +179,18 @@ conn plugin --remote --sync
    conn config --service-mode remote
     conn config --remote localhost:50051
     
    -

    8c. User Management

    -

    Manage server-side user credentials for distributed setups:

    +

    8c. User Management & API Tokens

    +

    Manage server-side user credentials and Personal Access Tokens (PAT) for automated setups:

    conn user --add username
     conn user --list
     conn user --regen-password username
    +
    +# Personal Access Tokens (PAT) for non-interactive API access
    +conn user --create-token "CI/CD Token" --expires-in 30
    +conn user --list-tokens
    +conn user --revoke-token <token_id>
     
    -

    Use --path to specify custom configuration folders in server Mode B.

    +

    Use --path to specify custom configuration folders in server Mode B. Pass API tokens via CONNPY_TOKEN environment variable.

    8d. SSO / OIDC

    Configure identity providers (e.g. Authelia, Keycloak) for SSO gRPC authentication using the interactive wizard:

    conn sso --add provider_name
    @@ -236,6 +255,10 @@ print(response)
     

    Sub-modules

    +
    connpy.ai
    +
    +
    +
    connpy.cli
    @@ -665,2600 +688,6 @@ indicating successful verification.

    -
    -class ai -(config,
    org=None,
    api_key=None,
    engineer_model=None,
    architect_model=None,
    engineer_api_key=None,
    architect_api_key=None,
    console=None,
    confirm_handler=None,
    trust=False,
    engineer_auth=None,
    architect_auth=None,
    **kwargs)
    -
    -
    -
    - -Expand source code - -
    @ClassHook
    -class ai:
    -    """Hybrid Multi-Agent System: Selective Escalation with Role Persistence."""
    -
    -    SAFE_COMMANDS = [
    -        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, org=None, api_key=None, engineer_model=None, architect_model=None, engineer_api_key=None, architect_api_key=None, console=None, confirm_handler=None, trust=False, engineer_auth=None, architect_auth=None, **kwargs):
    -        self.config = config
    -        self.console = console or printer.console
    -        self.confirm_handler = confirm_handler or self._local_confirm_handler
    -        self.trusted_session = trust  # Trust mode for the entire session
    -        self.interrupted = False
    -        self.one_shot = kwargs.get("one_shot", False)
    -
    -        
    -        # 1. Load generic configuration with global inheritance/merge
    -        if hasattr(self.config, "get_effective_setting"):
    -            aiconfig = self.config.get_effective_setting("ai", {})
    -        else:
    -            aiconfig = self.config.config.get("ai", {}) if hasattr(self.config, "config") else {}
    -        
    -        # Modelos (Prioridad: Argumento -> Config -> Default)
    -        self.engineer_model = engineer_model or aiconfig.get("engineer_model") or "gemini/gemini-3.1-flash-lite"
    -        self.architect_model = architect_model or aiconfig.get("architect_model") or "anthropic/claude-sonnet-4-6"
    -        
    -        # API Keys (Prioridad: Argumento -> Config)
    -        self.engineer_key = engineer_api_key or aiconfig.get("engineer_api_key")
    -        self.architect_key = architect_api_key or aiconfig.get("architect_api_key")
    -
    -        # Auth configurations (Prioridad: Argumento -> Config)
    -        self.engineer_auth = engineer_auth if engineer_auth is not None else aiconfig.get("engineer_auth")
    -        if self.engineer_auth is None:
    -            self.engineer_auth = {}
    -        elif not isinstance(self.engineer_auth, dict):
    -            self.engineer_auth = {}
    -
    -        self.architect_auth = architect_auth if architect_auth is not None else aiconfig.get("architect_auth")
    -        if self.architect_auth is None:
    -            self.architect_auth = {}
    -        elif not isinstance(self.architect_auth, dict):
    -            self.architect_auth = {}
    -
    -        # Backward compatibility fallbacks: only inject api_key if the auth dict is empty/not configured
    -        if self.engineer_key and not self.engineer_auth:
    -            self.engineer_auth["api_key"] = self.engineer_key
    -        if self.architect_key and not self.architect_auth:
    -            self.architect_auth["api_key"] = self.architect_key
    -
    -        # Strategic Reasoning Engine (Architect) availability
    -        is_architect_keyless = "vertex" in self.architect_model.lower() or "ollama" in self.architect_model.lower() or "local" in self.architect_model.lower()
    -        self.has_architect = bool(self.architect_key or self.architect_auth or is_architect_keyless)
    -
    -        # Custom Trusted Commands Regexes
    -        custom_trusted = aiconfig.get("trusted_commands", [])
    -        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 [])
    -        
    -        # Limits
    -        self.max_history = 30
    -        self.max_truncate = 50000
    -        self.soft_limit_iterations = 20  # Show warning and suggest Ctrl+C
    -        self.hard_limit_iterations = 50  # Force stop
    -
    -        # External tool registry (populated by plugins via ClassHook.modify)
    -        self.external_engineer_tools = []     # Tool defs for Engineer LLM
    -        self.external_architect_tools = []    # Tool defs for Architect LLM
    -        self.external_tool_handlers = {}      # {"tool_name": handler_callable}
    -        self.tool_status_formatters = {}      # {"tool_name": formatter_callable}
    -        self.engineer_prompt_extensions = []  # Extra text for engineer prompt
    -        self.architect_prompt_extensions = [] # Extra text for architect prompt
    -        
    -        # MCP Manager
    -        self.mcp_manager = MCPClientManager(self.config)
    -
    -        # Long-term memory
    -        self.memory_path = os.path.join(self.config.defaultdir, "ai_memory.md")
    -        self.long_term_memory = ""
    -        if os.path.exists(self.memory_path):
    -            try:
    -                with open(self.memory_path, "r") as f:
    -                    self.long_term_memory = f.read()
    -            except FileNotFoundError:
    -                self.long_term_memory = ""
    -            except PermissionError as e:
    -                self.console.print(f"[warning]Warning: Cannot read AI memory file: {e}[/warning]")
    -            except Exception as e:
    -                self.console.print(f"[warning]Warning: Failed to load AI memory: {e}[/warning]")
    -
    -        # Session Management
    -        self.sessions_dir = os.path.join(self.config.defaultdir, "ai_sessions")
    -        os.makedirs(self.sessions_dir, exist_ok=True)
    -        self.session_id = getattr(self.config, "session_id", None)
    -        self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json") if self.session_id else None
    -
    -        # Agnostic base prompts
    -        architect_instructions = ""
    -        if self.has_architect:
    -            architect_instructions = """
    -            CRITICAL - CONSULT vs ESCALATE:
    -            - ALWAYS use 'consult_architect' for: Configuration planning, design decisions, complex troubleshooting.
    -              Examples: "consultalo con el arquitecto", "preguntale al arquitecto", "que opina el arquitecto"
    -              You stay in control and present the advice to the user.
    -            
    -            - ONLY use 'escalate_to_architect' when user EXPLICITLY asks to TALK to the Architect:
    -              Examples: "quiero hablar con el arquitecto", "pasame con el arquitecto", "que me atienda el arquitecto"
    -              After escalation, you hand over control completely.
    -            
    -            - DEFAULT: When in doubt, use 'consult_architect'. Escalation is rare.
    -"""
    -        else:
    -            architect_instructions = """
    -            CRITICAL - ARCHITECT UNAVAILABLE:
    -            - The Strategic Reasoning Engine (Architect) is currently UNAVAILABLE because its API key or authentication is not configured.
    -            - DO NOT attempt to consult or escalate to the architect.
    -            - If the user asks to consult the architect, inform them that the Architect is offline and offer to help them directly to the best of your abilities.
    -"""
    -
    -        self._engineer_base_prompt = dedent(f"""
    -            Role: TECHNICAL EXECUTION ENGINE.
    -            Expertise: Universal Networking (Cisco, Nokia, Juniper, 6wind, etc.).
    -            
    -            Rules:
    -            - BE FAST AND EXTREMELY CONCISE: Provide direct answers. No filler words, no decorative language, no polite pleasantries. Save output tokens at all costs.
    -            - KNOWLEDGE FIRST: For general networking questions (AS numbers, protocol details, standards, generic commands), use your internal knowledge. ONLY use tools when the user's specific infrastructure data is required.
    -            - INVENTORY ONLY: 'run_commands', 'list_nodes', and 'get_node_info' are ONLY for interacting with the user's inventory.
    -            - BROADCAST RESTRICTION: Avoid using filter '.*' in 'run_commands' unless the user explicitly requests a global action. Try to target specific nodes or groups based on the conversation.
    -            - AUTONOMY: Proactively use iterative tool calls to find the root cause of infrastructure issues.
    -            - BATCH OPERATIONS: When working on multiple devices, call tools in parallel.
    -            - COMPLETE MISSIONS: Execute ALL steps of a mission before reporting back.
    -            - DIAGRAM: Use ASCII art or Unicode box-drawing characters directly in your responses to visualize topologies or paths when helpful.
    -            - EVIDENCE: Include 'Key Snippets' from tool outputs. Be token-efficient.
    -            - LANGUAGE: You MUST respond in the same language used by the user in their question or instruction.
    -            - 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."}}
    -        """).strip()
    -
    -        self._architect_base_prompt = dedent(f"""
    -            Role: STRATEGIC REASONING ENGINE.
    -            Expertise: Network Architecture, Complex Troubleshooting, and Design Validation.
    -            
    -            Rules:
    -            - CONCISENESS IS MANDATORY: Strip out fluff, decorative language, and filler words. Provide direct, tactical instructions and analysis to save output tokens.
    -            - STRATEGY: Define technical missions for the Engineer. 
    -            - DIAGRAM: Use ASCII art or Unicode box-drawing characters in your responses to visualize topologies, traffic paths, or logic flows.
    -            - ENGINEER CAPABILITIES: Your Engineer can:
    -                * Filter nodes (list_nodes), Run CLI commands (run_commands), Get metadata (get_node_info).
    -            - ANALYSIS: Review technical findings to identify patterns or design failures.
    -            - LANGUAGE: You MUST respond in the same language used by the user in their question or instruction.
    -            - MEMORY: Update long-term facts ONLY when the user explicitly requests it.
    -            
    -            CRITICAL - EFFICIENT DELEGATION:
    -            - Plan ALL tasks upfront before delegating.
    -            - Delegate ONCE with a complete, detailed mission including ALL steps.
    -            - Example: "List all routers matching 'border.*', then run 'show ip bgp summary' and 'show ip route' on each, then analyze the outputs."
    -            - DO NOT delegate multiple times for the same goal. Batch everything into ONE mission.
    -            - Wait for Engineer's complete report before responding to user.
    -            
    -            CRITICAL - RETURNING CONTROL:
    -            - When your strategic analysis is complete and no further architectural decisions are needed, use 'return_to_engineer' to hand control back.
    -            - The Engineer is better suited for ongoing technical execution and troubleshooting.
    -            - Only stay in control if the user explicitly needs strategic oversight for multiple interactions.
    -            
    -            Network Context: {self.long_term_memory if self.long_term_memory else "Empty."}
    -        """).strip()
    -
    -    def _local_confirm_handler(self, prompt, default="n"):
    -        """Default confirmation handler using rich.prompt."""
    -        from rich.prompt import Prompt
    -        return Prompt.ask(prompt, default=default)
    -
    -    @property
    -    def engineer_system_prompt(self):
    -        """Build engineer system prompt with plugin extensions."""
    -        if self.engineer_prompt_extensions:
    -            extensions = "\n".join(self.engineer_prompt_extensions)
    -            return self._engineer_base_prompt + f"\n\nPlugin Capabilities:\n{extensions}"
    -        return self._engineer_base_prompt
    -
    -    @property
    -    def architect_system_prompt(self):
    -        """Build architect system prompt with plugin extensions."""
    -        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."
    -        if self.architect_prompt_extensions:
    -            extensions = "\n".join(self.architect_prompt_extensions)
    -            return prompt + f"\n\nPlugin Capabilities:\n{extensions}"
    -        return prompt
    -
    -    def register_ai_tool(self, tool_definition, handler, target="engineer", engineer_prompt=None, architect_prompt=None, status_formatter=None):
    -        """Register an external tool for the AI system.
    -
    -        Args:
    -            tool_definition (dict): OpenAI-compatible tool definition.
    -            handler (callable): Function(ai_instance, **tool_args) -> str.
    -            target (str): 'engineer', 'architect', or 'both'.
    -            engineer_prompt (str): Extra text for engineer system prompt.
    -            architect_prompt (str): Extra text for architect system prompt.
    -            status_formatter (callable): Function(args_dict) -> status string.
    -        """
    -        name = tool_definition["function"]["name"]
    -        
    -        # Check if already registered to prevent duplicates
    -        if target in ("engineer", "both"):
    -            if not any(t["function"]["name"] == name for t in self.external_engineer_tools):
    -                self.external_engineer_tools.append(tool_definition)
    -        if target in ("architect", "both"):
    -            if not any(t["function"]["name"] == name for t in self.external_architect_tools):
    -                self.external_architect_tools.append(tool_definition)
    -        
    -        self.external_tool_handlers[name] = handler
    -        
    -        if engineer_prompt and engineer_prompt not in self.engineer_prompt_extensions:
    -            self.engineer_prompt_extensions.append(engineer_prompt)
    -        if architect_prompt and architect_prompt not in self.architect_prompt_extensions:
    -            self.architect_prompt_extensions.append(architect_prompt)
    -        if status_formatter:
    -            self.tool_status_formatters[name] = status_formatter
    -
    -    def _stream_completion(self, model, messages, tools, api_key=None, status=None, label="", debug=False, chunk_callback=None, auth=None, **kwargs):
    -        """Stream a completion call, rendering styled Markdown in real-time.
    -
    -        Returns (response, streamed) where:
    -        - response: reconstructed ModelResponse (same as non-streaming)
    -        - streamed: True if text was rendered to console during streaming
    -        """
    -        auth_dict = auth if auth is not None else {}
    -        if api_key and "api_key" not in auth_dict:
    -            auth_dict = auth_dict.copy()
    -            auth_dict["api_key"] = api_key
    -
    -        stream_resp = completion(model=model, messages=messages, tools=tools, stream=True, **auth_dict, **kwargs)
    -
    -        chunks = []
    -        full_content = ""
    -        is_streaming_text = False
    -        has_tool_calls = False
    -        header_printed = False
    -
    -        # Determine styling based on current brain
    -        role_label = "Network Architect" if "architect" in label.lower() else "Network Engineer"
    -        alias = "architect" if "architect" in label.lower() else "engineer"
    -        title = f"[bold {alias}]{role_label}[/bold {alias}]"
    -        border = alias
    -
    -        try:
    -            for chunk in stream_resp:
    -                chunks.append(chunk)
    -                delta = chunk.choices[0].delta
    -
    -                # Detect tool calls
    -                if hasattr(delta, 'tool_calls') and delta.tool_calls:
    -                    has_tool_calls = True
    -
    -                # Stream text content with styled rendering
    -                if hasattr(delta, 'content') and delta.content:
    -                    full_content += delta.content
    -
    -                    if chunk and chunk_callback:
    -                        # Check for remote interruption during streaming
    -                        if hasattr(self, "interrupted") and self.interrupted:
    -                            raise KeyboardInterrupt
    -                        chunk_callback(delta.content)
    -
    -                    if not chunk_callback:
    -                        if not is_streaming_text:
    -                            if status:
    -                                try:
    -                                    status.stop()
    -                                except Exception:
    -                                    pass
    -                            
    -                            # Create a stable, direct Console to bypass _ConsoleProxy recreation bugs
    -                            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())
    -                            
    -                            stable_console.print(Rule(f"[bold {border}]{title}[/bold {border}]", style=border))
    -                            header_printed = True
    -                            md_parser = IncrementalMarkdownParser(console=stable_console)
    -                            is_streaming_text = True
    -                        
    -                        md_parser.feed(delta.content)
    -        except Exception as e:
    -            if not chunks:
    -                raise
    -        finally:
    -            if header_printed:
    -                try:
    -                    md_parser.flush()
    -                    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=border))
    -                except Exception:
    -                    pass
    -        
    -        # Rebuild complete response from chunks
    -        try:
    -            response = stream_chunk_builder(chunks, messages=messages)
    -        except Exception:
    -            # Fallback: manual reconstruction if stream_chunk_builder fails
    -            full_content_rebuilt = ""
    -            tool_calls_map = {}
    -            for c in chunks:
    -                d = c.choices[0].delta
    -                if hasattr(d, 'content') and d.content:
    -                    full_content_rebuilt += d.content
    -                if hasattr(d, 'tool_calls') and d.tool_calls:
    -                    for tc in d.tool_calls:
    -                        idx = tc.index
    -                        if idx not in tool_calls_map:
    -                            tool_calls_map[idx] = {"id": tc.id or "", "type": "function", "function": {"name": getattr(tc.function, 'name', '') or '', "arguments": getattr(tc.function, 'arguments', '') or ''}}
    -                        else:
    -                            if tc.id: tool_calls_map[idx]["id"] = tc.id
    -                            if tc.function:
    -                                if tc.function.name: tool_calls_map[idx]["function"]["name"] = tc.function.name
    -                                if tc.function.arguments: tool_calls_map[idx]["function"]["arguments"] += tc.function.arguments
    -            
    -            # Build a minimal response-like object
    -            class FakeFunc:
    -                def __init__(self, name, arguments): self.name = name; self.arguments = arguments
    -            class FakeTC:
    -                def __init__(self, d): self.id = d["id"]; self.function = FakeFunc(d["function"]["name"], d["function"]["arguments"])
    -                def model_dump(self, **kw): return {"id": self.id, "type": "function", "function": {"name": self.function.name, "arguments": self.function.arguments}}
    -            class FakeMsg:
    -                def __init__(self, content, tcs): self.content = content or None; self.tool_calls = tcs if tcs else None; self.role = "assistant"
    -                def model_dump(self, **kw):
    -                    d = {"role": "assistant", "content": self.content}
    -                    if self.tool_calls: d["tool_calls"] = [tc.model_dump() for tc in self.tool_calls]
    -                    return d
    -            class FakeChoice:
    -                def __init__(self, msg): self.message = msg
    -            class FakeResp:
    -                def __init__(self, choice): self.choices = [choice]; self.usage = None
    -            
    -            tcs = [FakeTC(tool_calls_map[i]) for i in sorted(tool_calls_map)] if tool_calls_map else None
    -            response = FakeResp(FakeChoice(FakeMsg(full_content_rebuilt or full_content, tcs)))
    -        
    -        # Only count as "streamed" if we rendered text AND it was the final response (no tool calls)
    -        streamed = is_streaming_text and not has_tool_calls
    -        return response, streamed
    -
    -    def _sanitize_messages(self, messages):
    -        """Sanitize message list for strict providers like Gemini.
    -        
    -        Ensures that:
    -        1. Every assistant message with tool_calls is followed by ALL its tool responses
    -        2. No user/system messages appear between tool_calls and tool responses
    -        3. Orphaned tool_calls at the end are removed
    -        4. Orphaned tool responses without a preceding tool_call are removed
    -        5. Incompatible metadata like cache_control is stripped for non-Anthropic models
    -        6. Enforces strict alternating history to prevent BadRequestError on Gemini.
    -        """
    -        if not messages:
    -            return messages
    -        
    -        # Pre-process messages to pull text from list contents (Anthropic cache format) 
    -        # and remove explicit cache keys.
    -        pre_sanitized = []
    -        for msg in messages:
    -            m = msg.copy() if isinstance(msg, dict) else msg.model_dump(exclude_none=True)
    -            
    -            # Convert content list to plain string if it's a system message with caching metadata
    -            if m.get('role') == 'system' and isinstance(m.get('content'), list):
    -                if m['content'] and isinstance(m['content'][0], dict) and m['content'][0].get('text'):
    -                    m['content'] = m['content'][0]['text']
    -                else:
    -                    m['content'] = ""
    -
    -            # Remove any explicit cache_control key anywhere
    -            if 'cache_control' in m: del m['cache_control']
    -            if isinstance(m.get('content'), list):
    -                for item in m['content']:
    -                    if isinstance(item, dict) and 'cache_control' in item: del item['cache_control']
    -            
    -            pre_sanitized.append(m)
    -
    -        sanitized = []
    -        last_role = None
    -        
    -        i = 0
    -        while i < len(pre_sanitized):
    -            msg = pre_sanitized[i]
    -            role = msg.get('role', '')
    -            
    -            if role == 'system':
    -                sanitized.append(msg)
    -                last_role = 'system'
    -                i += 1
    -                
    -            elif role == 'user':
    -                if last_role == 'user' and sanitized:
    -                    # Combine consecutive user messages
    -                    sanitized[-1]['content'] = str(sanitized[-1].get('content', '') or '') + '\n' + str(msg.get('content', '') or '')
    -                else:
    -                    sanitized.append(msg)
    -                    last_role = 'user'
    -                i += 1
    -                
    -            elif role == 'assistant':
    -                has_tools = bool(msg.get('tool_calls'))
    -                
    -                # Gemini strict sequence: Assistant MUST be preceded by user or tool.
    -                # If preceded by system, assistant, or if it's the very first message...
    -                if last_role not in ('user', 'tool'):
    -                    sanitized.append({"role": "user", "content": "[System sequence separator: History Truncated/Merged]"})
    -                    last_role = 'user'
    -                
    -                if has_tools:
    -                    # Look ahead for matching tool responses
    -                    tool_responses = []
    -                    j = i + 1
    -                    while j < len(pre_sanitized):
    -                        next_msg = pre_sanitized[j]
    -                        if next_msg.get('role') == 'tool':
    -                            tool_responses.append(next_msg)
    -                            j += 1
    -                        else:
    -                            break
    -                    
    -                    if tool_responses:
    -                        sanitized.append(msg)
    -                        sanitized.extend(tool_responses)
    -                        last_role = 'tool'
    -                        i = j
    -                    else:
    -                        # Orphaned tool_calls with no responses - skip the assistant message
    -                        # If we just added a dummy user message for this assistant, remove it too
    -                        if sanitized and sanitized[-1].get('content') == "[System sequence separator: History Truncated/Merged]":
    -                            sanitized.pop()
    -                            last_role = sanitized[-1].get('role', '') if sanitized else None
    -                        i += 1
    -                else:
    -                    sanitized.append(msg)
    -                    last_role = 'assistant'
    -                    i += 1
    -                    
    -            elif role == 'tool':
    -                # Orphaned tool response (no preceding assistant with tool_calls) - skip
    -                i += 1
    -                
    -            else:
    -                sanitized.append(msg)
    -                last_role = role
    -                i += 1
    -        
    -        return sanitized
    -
    -    def _truncate(self, text, limit=None):
    -        """Truncate text to specified limit, keeping head (60%) and tail (40%)."""
    -        if not isinstance(text, str): return str(text)
    -        final_limit = limit or self.max_truncate
    -        if len(text) <= final_limit: return text
    -        head_limit = int(final_limit * 0.6)
    -        tail_limit = int(final_limit * 0.4)
    -        return (text[:head_limit] + f"\n\n[... OUTPUT TRUNCATED ...]\n\n" + text[-tail_limit:])
    -
    -    def _print_debug_observation(self, fn, obs, status=None):
    -        """Prints a tool observation in a readable way during debug mode."""
    -        # Try to parse as JSON if it's a string
    -        if isinstance(obs, str):
    -            try:
    -                obs_data = json.loads(obs)
    -            except Exception:
    -                obs_data = obs
    -        else:
    -            obs_data = obs
    -        
    -        if isinstance(obs_data, dict):
    -            elements = []
    -            for k, v in obs_data.items():
    -                elements.append(Text(f"• {k}:", style="key"))
    -                # Use Text for values to ensure newlines are rendered
    -                val = str(v)
    -                # If it's a multiline string from a delegation task, keep it clean
    -                elements.append(Text(val))
    -            
    -            if not elements:
    -                content = Text("Empty data set")
    -            else:
    -                # Add a small spacer instead of a Rule for cleaner look
    -                from rich.console import Group
    -                content = Group(*elements)
    -        elif isinstance(obs_data, list):
    -            content = Text("\n".join(f"• {item}" for item in obs_data))
    -        else:
    -            content = Text(str(obs_data))
    -            
    -        title = f"[bold]{fn}[/bold]"
    -        
    -        # Stop status before printing panel to avoid ghosting
    -        if status:
    -            try: status.stop()
    -            except: pass
    -            
    -        self.console.print(Panel(content, title=title, border_style="ai_status"))
    -        
    -        # Resume status
    -        if status:
    -            try: status.start()
    -            except: pass
    -
    -    def manage_memory_tool(self, content, action="append"):
    -        """Save or update long-term memory. Only use when user explicitly requests it."""
    -        if not content or not content.strip():
    -            return "Error: Cannot save empty content to memory."
    -        
    -        try:
    -            mode = "a" if action == "append" else "w"
    -            os.makedirs(os.path.dirname(self.memory_path), exist_ok=True)
    -            with open(self.memory_path, mode) as f:
    -                timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
    -                f.write(f"\n\n## {timestamp}\n{content.strip()}\n" if action == "append" else content)
    -            
    -            # Reload memory after update
    -            with open(self.memory_path, "r") as f:
    -                self.long_term_memory = f.read()
    -            
    -            return "Memory updated successfully."
    -        except PermissionError as e:
    -            return f"Error: Permission denied writing to memory file: {e}"
    -        except Exception as e:
    -            return f"Error updating memory: {str(e)}"
    -
    -
    -    def list_nodes_tool(self, filter_pattern=".*"):
    -        """List nodes matching the filter pattern. Returns metadata for <=5 nodes, names only for more."""
    -        try:
    -            matched_names = self.config._getallnodes(filter_pattern)
    -            if not matched_names: return "No nodes found."
    -            if len(matched_names) <= 5:
    -                matched_data = self.config.getitems(matched_names, extract=True)
    -                res = {}
    -                for name, data in matched_data.items():
    -                    os_tag = "unknown"
    -                    if isinstance(data, dict):
    -                        ts = data.get("tags")
    -                        if isinstance(ts, dict): os_tag = ts.get("os", "unknown")
    -                    res[name] = {"os": os_tag}
    -                return res
    -            return {"count": len(matched_names), "nodes": matched_names, "note": "Use 'get_node_info' for details."}
    -        except Exception as e: 
    -            return f"Error listing nodes: {str(e)}"
    -
    -    def _is_safe_command(self, cmd):
    -        """Check if a command matches safe patterns."""
    -        return any(re.match(pattern, cmd.strip(), re.IGNORECASE) for pattern in self.safe_commands)
    -    
    -    def run_commands_tool(self, nodes_filter, commands, status=None):
    -        """Execute commands on nodes matching the filter. Native interactive confirmation for unsafe commands."""
    -        # Handle if commands is a JSON string
    -        if isinstance(commands, str):
    -            try:
    -                commands = json.loads(commands)
    -            except ValueError:
    -                commands = [c.strip() for c in commands.split('\n') if c.strip()]
    -        
    -        # Expand multi-line commands within a list (in case the AI packs them)
    -        if isinstance(commands, list):
    -            expanded_commands = []
    -            for cmd in commands:
    -                expanded_commands.extend([c.strip() for c in str(cmd).split('\n') if c.strip()])
    -            commands = expanded_commands
    -        else:
    -            commands = [str(commands)]
    -        
    -        # Check command safety natively
    -        if not self.trusted_session:
    -            unsafe_commands = [cmd for cmd in commands if not self._is_safe_command(cmd)]
    -            if unsafe_commands:
    -                # Stop the spinner so prompt doesn't get messed up
    -                if status: status.stop()
    -                
    -                # Show ALL commands with unsafe ones highlighted
    -                formatted_cmds = []
    -                for cmd in commands:
    -                    if cmd in unsafe_commands:
    -                        formatted_cmds.append(f"  • [warning]{cmd}[/warning]")
    -                    else:
    -                        formatted_cmds.append(f"  • {cmd}")
    -                
    -                panel_content = f"Target: {nodes_filter}\nCommands:\n" + "\n".join(formatted_cmds)
    -                # Use print_important if available (for remote bridges) fallback to standard print
    -                print_fn = getattr(self.console, "print_important", self.console.print)
    -                print_fn(Panel(panel_content, title="[bold warning]⚠️ UNSAFE COMMANDS DETECTED[/bold warning]", border_style="warning"))
    -                
    -                try:
    -                    user_resp = self.confirm_handler("[bold warning]Execute? (y: yes / n: no / a: allow all this session / <text>: feedback)[/bold warning]", default="n")
    -                except KeyboardInterrupt:
    -                    if status: status.update("[ai_status]Engineer: Resuming...")
    -                    self.console.print("[fail]✗ Aborted by user (Ctrl+C).[/fail]")
    -                    raise
    -                
    -                # Resume the spinner
    -                if status: status.update("[ai_status]Engineer: Processing user response...")
    -                
    -                user_resp_lower = user_resp.strip().lower()
    -                if user_resp_lower in ['a', 'allow']:
    -                    self.trusted_session = True
    -                    self.console.print("[pass]✓ Trust Mode Enabled. All future commands in this session will execute without confirmation.[/pass]")
    -                elif user_resp_lower in ['y', 'yes']:
    -                    self.console.print("[pass]✓ Executing...[/pass]")
    -                elif user_resp_lower in ['n', 'no', '', 'cancel']:
    -                    self.console.print("[fail]✗ Execution rejected by user.[/fail]")
    -                    return "Error: User rejected execution."
    -                else:
    -                    self.console.print(f"[user_prompt]User feedback: [/user_prompt]{user_resp}")
    -                    return f"User requested changes: {user_resp}. Please adjust the commands based on this feedback and try again."
    -        
    -        try:
    -            matched_names = self.config._getallnodes(nodes_filter)
    -            if not matched_names: return "No nodes found matching filter."
    -            thisnodes_dict = self.config.getitems(matched_names, extract=True)
    -            result = nodes(thisnodes_dict, config=self.config).run(commands)
    -            return result
    -        except Exception as e: 
    -            return f"Error executing commands: {str(e)}"
    -
    -    def get_node_info_tool(self, node_name):
    -        """Get detailed metadata for a specific node. Passwords are masked."""
    -        try:
    -            d = self.config.getitem(node_name, extract=True)
    -            if 'password' in d: d['password'] = '***'
    -            return d
    -        except Exception as e: 
    -            return f"Error getting node info: {str(e)}"
    -
    -    def _engineer_loop(self, task, status=None, debug=False, chat_history=None):
    -        """Internal loop where the Engineer executes technical tasks for the Architect."""
    -        # Cache optimization for the Engineer (Only for direct Anthropic, Vertex has different rules)
    -        if "claude" in self.engineer_model.lower() and "vertex" not in self.engineer_model.lower():
    -            messages = [{"role": "system", "content": [{"type": "text", "text": self.engineer_system_prompt, "cache_control": {"type": "ephemeral"}}]}]
    -        else:
    -            messages = [{"role": "system", "content": self.engineer_system_prompt}]
    -            
    -        if chat_history:
    -            # Clean chat history from caching metadata if engineer is not a compatible Claude model
    -            if "claude" not in self.engineer_model.lower() or "vertex" in self.engineer_model.lower():
    -                messages.extend(self._sanitize_messages(chat_history[-5:]))
    -            else:
    -                messages.extend(chat_history[-5:])
    -        
    -        messages.append({"role": "user", "content": f"MISSION: {task}"})
    -        
    -        tools = self._get_engineer_tools()
    -        usage = {"input": 0, "output": 0, "total": 0}
    -        iteration = 0
    -        soft_limit_warned = False
    -        
    -        try:
    -            # Set up remote interrupt callback if bridge is provided
    -            if status and hasattr(status, "on_interrupt"):
    -                status.on_interrupt = lambda: setattr(self, "interrupted", True)
    -
    -            while iteration < self.hard_limit_iterations:
    -                iteration += 1
    -                
    -                # Check for interruption
    -                if self.interrupted:
    -                    raise KeyboardInterrupt
    -                
    -                if status and not chat_history:
    -                    status_text = f"[ai_status]Engineer: Analyzing mission... (step {iteration})"
    -                    if iteration >= self.soft_limit_iterations:
    -                        status_text += " [warning]⚠ Taking longer than expected (Ctrl+C to interrupt)[/warning]"
    -                    status.update(status_text)
    -                
    -                try:
    -                    safe_messages = self._sanitize_messages(messages)
    -                    response = completion(model=self.engineer_model, messages=safe_messages, tools=tools, **self.engineer_auth)
    -                except Exception as e:
    -                    if status: status.stop()
    -                    raise ValueError(f"Engineer failed to connect: {str(e)}")
    -                
    -                if hasattr(response, "usage") and response.usage:
    -                    usage["input"] += getattr(response.usage, "prompt_tokens", 0)
    -                    usage["output"] += getattr(response.usage, "completion_tokens", 0)
    -                    usage["total"] += getattr(response.usage, "total_tokens", 0)
    -
    -                resp_msg = response.choices[0].message
    -                msg_dict = resp_msg.model_dump(exclude_none=True)
    -                if msg_dict.get("tool_calls") and msg_dict.get("content") == "": msg_dict["content"] = None
    -                messages.append(msg_dict)
    -
    -                if not resp_msg.tool_calls: break
    -                for tc in resp_msg.tool_calls:
    -                    fn, args = tc.function.name, json.loads(tc.function.arguments)
    -                    
    -                    # Real-time notification of the technical task (Only if not in Architect loop)
    -                    if status and not chat_history:
    -                        s_text = ""
    -                        if fn == "list_nodes": s_text = f"[ai_status]Engineer: [SEARCH] {args.get('filter_pattern','.*')}"
    -                        elif fn == "run_commands": 
    -                            cmds = args.get('commands', [])
    -                            cmd_str = cmds[0] if cmds else ""
    -                            s_text = f"[ai_status]Engineer: [CMD] {cmd_str}"
    -                        elif fn == "get_node_info": s_text = f"[ai_status]Engineer: [INSPECT] {args.get('node_name','')}"
    -                        elif fn.startswith("mcp_"):
    -                            server = fn.split("__")[0].replace("mcp_", "")
    -                            tool = fn.split("__")[1] if "__" in fn else fn
    -                            s_text = f"[ai_status]Engineer: [MCP:{server}] {tool}"
    -                        elif fn in self.tool_status_formatters: s_text = self.tool_status_formatters[fn](args)
    -                        
    -                        if s_text:
    -                            if iteration >= self.soft_limit_iterations:
    -                                s_text += " [warning]⚠ Taking longer than expected (Ctrl+C to interrupt)[/warning]"
    -                            status.update(s_text)
    -
    -                    if debug:
    -                        self._print_debug_observation(f"Decision: {fn}", args, status=status)
    -                    
    -                    if fn == "list_nodes": obs = self.list_nodes_tool(**args)
    -                    elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
    -                    elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
    -                    elif fn.startswith("mcp_"):
    -                        obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
    -                    elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
    -                    else: obs = f"Error: Unknown tool '{fn}'."
    -                    
    -                    if debug:
    -                        self._print_debug_observation(f"Observation: {fn}", obs, status=status)
    -                    
    -                    # Ensure observation is a string and truncated for the LLM
    -                    obs_str = obs if isinstance(obs, str) else json.dumps(obs)
    -                    messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": self._truncate(obs_str)})
    -            
    -            if iteration >= self.hard_limit_iterations:
    -                self.console.print(f"[error]⛔ Engineer reached hard limit ({self.hard_limit_iterations} steps). Forcing stop.[/error]")
    -            
    -            if debug and resp_msg.content:
    -                self.console.print(Panel(Text(resp_msg.content), title="[bold engineer]Engineer Final Report to Architect[/bold engineer]", border_style="engineer"))
    -            
    -            return resp_msg.content, usage
    -        except Exception as e:
    -            return f"Engineer failed: {str(e)}", usage
    -
    -    def _get_engineer_tools(self, os_filter: str = None):
    -        """Define tools available to the Engineer."""
    -        base_tools = [
    -            {"type": "function", "function": {"name": "list_nodes", "description": "[Universal Platform] Lists available nodes in the inventory.", "parameters": {"type": "object", "properties": {"filter_pattern": {"type": "string", "description": "Regex to filter nodes (e.g. '.*', 'border.*')."}}}}},
    -            {"type": "function", "function": {"name": "run_commands", "description": "[Universal Platform] Runs one or more commands on matched nodes. MANDATORY: You MUST call 'list_nodes' first to verify the target list.", "parameters": {"type": "object", "properties": {"nodes_filter": {"type": "string", "description": "Exact node name or verified filter pattern."}, "commands": {"type": "array", "items": {"type": "string"}, "description": "List of commands (e.g. ['show ip route', 'show int desc'])."}}, "required": ["nodes_filter", "commands"]}}},
    -            {"type": "function", "function": {"name": "get_node_info", "description": "[Universal Platform] Gets full metadata for a specific node.", "parameters": {"type": "object", "properties": {"node_name": {"type": "string"}}, "required": ["node_name"]}}}
    -        ]
    -        
    -        # Add dynamic tools from MCP
    -        try:
    -            mcp_tools = run_ai_async(self.mcp_manager.get_tools_for_llm(os_filter=os_filter)).result(timeout=10)
    -            base_tools.extend(mcp_tools)
    -        except Exception as e:
    -            # Silently fail for LLM tools
    -            pass
    -
    -        if self.architect_key:
    -            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"]}}}
    -            ])
    -            
    -        # Deduplicate by name to prevent Gemini BadRequestError
    -        all_tools = base_tools + self.external_engineer_tools
    -        seen_names = set()
    -        unique_tools = []
    -        for t in all_tools:
    -            name = t["function"]["name"]
    -            if name not in seen_names:
    -                unique_tools.append(t)
    -                seen_names.add(name)
    -        return unique_tools
    -
    -    def _get_architect_tools(self):
    -        """Define tools available to the Strategic Reasoning Engine."""
    -        base_tools = [
    -            {"type": "function", "function": {"name": "delegate_to_engineer", "description": "Delegates a technical mission to the Engineer.", "parameters": {"type": "object", "properties": {"task": {"type": "string", "description": "Detailed technical mission or goal."}}, "required": ["task"]}}},
    -            {"type": "function", "function": {"name": "return_to_engineer", "description": "Return control to the Engineer. Use this when your strategic analysis is complete and the Engineer should handle the rest of the conversation.", "parameters": {"type": "object", "properties": {"summary": {"type": "string", "description": "Brief summary of your analysis to hand over to the Engineer."}}, "required": ["summary"]}}},
    -            {"type": "function", "function": {"name": "manage_memory_tool", "description": "Saves information to long-term memory. MANDATORY: Only use this if the user explicitly asks to remember or save something.", "parameters": {"type": "object", "properties": {"content": {"type": "string"}, "action": {"type": "string", "enum": ["append", "replace"]}}, "required": ["content"]}}}
    -        ]
    -        if getattr(self, "one_shot", False):
    -            base_tools = [t for t in base_tools if t["function"]["name"] not in ("delegate_to_engineer", "return_to_engineer")]
    -        
    -        all_tools = base_tools + self.external_architect_tools
    -        seen_names = set()
    -        unique_tools = []
    -        for t in all_tools:
    -            name = t["function"]["name"]
    -            if name not in seen_names:
    -                unique_tools.append(t)
    -                seen_names.add(name)
    -        return unique_tools
    -
    -    def _get_sessions(self):
    -        """Returns a list of session metadata sorted by date."""
    -        sessions = []
    -        if not os.path.exists(self.sessions_dir):
    -            return []
    -        for f in os.listdir(self.sessions_dir):
    -            if f.endswith(".json"):
    -                path = os.path.join(self.sessions_dir, f)
    -                try:
    -                    with open(path, "r") as fs:
    -                        data = json.load(fs)
    -                        sessions.append({
    -                            "id": f[:-5],
    -                            "title": data.get("title", "Untitled Session"),
    -                            "created_at": data.get("created_at", "Unknown"),
    -                            "model": data.get("model", "Unknown"),
    -                            "path": path
    -                        })
    -                except Exception:
    -                    continue
    -        return sorted(sessions, key=lambda x: x["created_at"], reverse=True)
    -
    -    def list_sessions(self, limit=20):
    -        """Prints a list of sessions using printer.table."""
    -        sessions = self._get_sessions()
    -        if not sessions:
    -            printer.info("No saved AI sessions found.")
    -            return
    -        
    -        total = len(sessions)
    -        if limit and total > limit:
    -            sessions = sessions[:limit]
    -            
    -        columns = ["ID", "Title", "Created At", "Model"]
    -        rows = [[s["id"], s["title"], s["created_at"], s["model"]] for s in sessions]
    -        
    -        title = "AI Persisted Sessions"
    -        if limit and total > limit:
    -            title += f" (Showing last {limit} of {total})"
    -            
    -        printer.table(title, columns, rows)
    -        if limit and total > limit:
    -            printer.info(f"Use '--list --all' (if supported) or check the sessions directory to see all {total} sessions.")
    -
    -    def load_session_data(self, session_id):
    -        """Loads a session's raw data by ID."""
    -        path = os.path.join(self.sessions_dir, f"{session_id}.json")
    -        if os.path.exists(path):
    -            try:
    -                with open(path, "r") as f:
    -                    data = json.load(f)
    -                    self.session_id = session_id
    -                    self.session_path = path
    -                    return data
    -            except Exception as e:
    -                printer.error(f"Failed to load session {session_id}: {e}")
    -        return None
    -
    -    def delete_session(self, session_id):
    -        """Deletes a session by ID."""
    -        path = os.path.join(self.sessions_dir, f"{session_id}.json")
    -        if os.path.exists(path):
    -            os.remove(path)
    -            printer.success(f"Session {session_id} deleted.")
    -        else:
    -            printer.error(f"Session {session_id} not found.")
    -
    -    def get_last_session_id(self):
    -        """Returns the ID of the most recent session."""
    -        sessions = self._get_sessions()
    -        return sessions[0]["id"] if sessions else None
    -
    -    def _generate_session_id(self, query):
    -        """Generates a unique session ID based on timestamp and a random suffix."""
    -        ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    -        suffix = secrets.token_hex(2)
    -        return f"{ts}-{suffix}"
    -
    -    def save_session(self, history, title=None, model=None):
    -        """Saves current history to the session file."""
    -        if not self.session_id:
    -            # Generate ID from first user query if available
    -            first_user_msg = next((m["content"] for m in history if m["role"] == "user"), "new-session")
    -            self.session_id = self._generate_session_id(first_user_msg)
    -            self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json")
    -        elif not self.session_path:
    -            self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json")
    -
    -        # If it's a new file, we might want to set a better title
    -        if not os.path.exists(self.session_path) and not title:
    -            raw_title = next((m["content"] for m in history if m["role"] == "user"), "New Session")
    -            # Clean title: remove newlines, multiple spaces
    -            clean_title = " ".join(raw_title.split())
    -            if len(clean_title) > 40:
    -                title = clean_title[:37].strip() + "..."
    -            else:
    -                title = clean_title
    -
    -        try:
    -            # Read existing metadata if it exists
    -            metadata = {}
    -            if os.path.exists(self.session_path):
    -                with open(self.session_path, "r") as f:
    -                    metadata = json.load(f)
    -            
    -            metadata.update({
    -                "id": self.session_id,
    -                "title": title or metadata.get("title", "New Session"),
    -                "created_at": metadata.get("created_at", datetime.datetime.now().isoformat()),
    -                "updated_at": datetime.datetime.now().isoformat(),
    -                "model": model or metadata.get("model", self.engineer_model),
    -                "history": history
    -            })
    -
    -            with open(self.session_path, "w") as f:
    -                json.dump(metadata, f, indent=4)
    -        except Exception as e:
    -            printer.error(f"Failed to save session: {e}")
    -
    -        except Exception as e:
    -            printer.error(f"Failed to save session: {e}")
    -
    -    @MethodHook
    -    def ask(self, user_input, dryrun=False, chat_history=None, status=None, debug=False, stream=True, session_id=None, chunk_callback=None):
    -        is_engineer_keyless = "vertex" in self.engineer_model.lower() or "ollama" in self.engineer_model.lower() or "local" in self.engineer_model.lower()
    -        if not self.engineer_key and not self.engineer_auth and not is_engineer_keyless:
    -            raise ValueError("Engineer API key or authentication not configured. Use 'connpy config --engineer-auth <auth>' to set it.")
    -
    -        def update_status(text):
    -            if not status:
    -                return
    -            if iteration >= self.soft_limit_iterations:
    -                warning_suffix = " [warning]⚠ Taking longer than expected (Ctrl+C to interrupt)[/warning]"
    -                if warning_suffix not in text:
    -                    text += warning_suffix
    -            status.update(text)
    -            
    -        if chat_history is None: chat_history = []
    -        
    -        # Load session if provided and history is empty
    -        if session_id:
    -            # Force the session_id even if it doesn't exist yet
    -            self.session_id = session_id
    -            self.session_path = os.path.join(self.sessions_dir, f"{session_id}.json")
    -            
    -            if not chat_history:
    -                session_data = self.load_session_data(session_id)
    -                if session_data:
    -                    chat_history = session_data.get("history", [])
    -                # If we loaded history, the caller might need it back
    -                # But typically ask() is called in a loop with an external history object
    -
    -        usage = {"input": 0, "output": 0, "total": 0}
    -        
    -        # 1. Initial Role Selector (Sticky Brain)
    -        explicit_architect = re.match(r'^(architect|arquitecto|@architect)[:\s]', user_input, re.I)
    -        explicit_engineer = re.match(r'^(engineer|ingeniero|@engineer)[:\s]', user_input, re.I)
    -        
    -        if explicit_architect:
    -            current_brain = "architect"
    -        elif explicit_engineer:
    -            current_brain = "engineer"
    -        else:
    -            # Sticky Brain: Detect if the Architect was in control in recent history
    -            is_architect_active = False
    -            for msg in reversed(chat_history[-5:]):
    -                tcs = msg.get('tool_calls') if isinstance(msg, dict) else getattr(msg, 'tool_calls', None)
    -                if tcs:
    -                    for tc in tcs:
    -                        fn = tc.get('function', {}).get('name') if isinstance(tc, dict) else getattr(getattr(tc, 'function', None), 'name', '')
    -                        # Architect stays in control if delegating tasks or if Engineer escalated to them
    -                        # consult_architect is just Engineer asking for advice - Engineer keeps control
    -                        if fn in ['delegate_to_engineer', 'escalate_to_architect']:
    -                            is_architect_active = True; break
    -                if is_architect_active: break
    -            current_brain = "architect" if is_architect_active else "engineer"
    -        
    -        # 2. Message preparation and cleaning
    -        clean_input = re.sub(r'^(architect|arquitecto|engineer|ingeniero|@architect|@engineer)[:\s]+', '', user_input, flags=re.IGNORECASE).strip()
    -        
    -        system_prompt = self.architect_system_prompt if current_brain == "architect" else self.engineer_system_prompt
    -        tools = self._get_architect_tools() if current_brain == "architect" else self._get_engineer_tools()
    -        model = self.architect_model if current_brain == "architect" else self.engineer_model
    -        key = self.architect_key if current_brain == "architect" else self.engineer_key
    -        current_auth = self.architect_auth if current_brain == "architect" else self.engineer_auth
    -
    -        # Optimized structure for Prompt Caching (Only for direct Anthropic, Vertex has different rules)
    -        if "claude" in model.lower() and "vertex" not in model.lower():
    -            messages = [{"role": "system", "content": [{"type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}}]}]
    -        else:
    -            messages = [{"role": "system", "content": system_prompt}]
    -        
    -        # History interleaving
    -        last_role = "system"
    -        # Sanitize history if the current target model is not compatible with cache_control
    -        history_to_process = chat_history[-self.max_history:]
    -        if "claude" not in model.lower() or "vertex" in model.lower():
    -            history_to_process = self._sanitize_messages(history_to_process)
    -
    -        for msg in history_to_process:
    -            m = msg if isinstance(msg, dict) else msg.model_dump(exclude_none=True)
    -            role = m.get('role')
    -            if role == last_role and role == 'user':
    -                messages[-1]['content'] += "\n" + (m.get('content') or "")
    -                continue
    -            if role == 'assistant' and m.get('tool_calls') and m.get('content') == "": m['content'] = None
    -            messages.append(m)
    -            last_role = role
    -
    -        if last_role == 'user': messages[-1]['content'] += "\n" + clean_input
    -        else: messages.append({"role": "user", "content": clean_input})
    -
    -        # 3. Execution loop
    -        iteration = 0
    -        try:
    -            # Set up remote interrupt callback if bridge is provided
    -            if status and hasattr(status, "on_interrupt"):
    -                status.on_interrupt = lambda: setattr(self, "interrupted", True)
    -
    -            while iteration < self.hard_limit_iterations:
    -                iteration += 1
    -                
    -                # Check for interruption
    -                if self.interrupted:
    -                    raise KeyboardInterrupt
    -                
    -                # Soft limit warning - handled inline within update_status
    -                
    -                label = "[architect][bold]Architect[/bold][/architect]" if current_brain == "architect" else "[engineer][bold]Engineer[/bold][/engineer]"
    -                if status: 
    -                    # Notify responder identity for web/remote clients
    -                    if getattr(status, "is_web", False) or getattr(status, "is_remote", False):
    -                        status.update(f"__RESPONDER__:{current_brain}")
    -                    update_status(f"{label} is thinking... (step {iteration})")
    -                
    -                streamed_response = False
    -                try:
    -                    safe_messages = self._sanitize_messages(messages)
    -                    if stream:
    -                        response, streamed_response = self._stream_completion(
    -                            model=model, messages=safe_messages, tools=tools, auth=current_auth,
    -                            status=status, label=label, debug=debug, num_retries=3,
    -                            chunk_callback=chunk_callback
    -                        )
    -                    else:
    -                        response = completion(model=model, messages=safe_messages, tools=tools, num_retries=3, **current_auth)
    -                except Exception as e:
    -                    if current_brain == "architect":
    -                        if status: update_status("[unavailable]Architect unavailable! Falling back to Engineer...")
    -                        # Preserve context when falling back - use clean_input directly
    -                        current_brain = "engineer"
    -                        model = self.engineer_model
    -                        tools = self._get_engineer_tools()
    -                        key = self.engineer_key
    -                        current_auth = self.engineer_auth
    -                        # Rebuild messages with Engineer system prompt and original user request
    -                        messages = [{"role": "system", "content": self.engineer_system_prompt}]
    -                        # Add chat history if exists (excluding system prompt)
    -                        if chat_history:
    -                            for msg in chat_history[-self.max_history:]:
    -                                if msg.get('role') != 'system':
    -                                    messages.append(msg)
    -                        # Add current user request
    -                        messages.append({"role": "user", "content": clean_input})
    -                        continue
    -                    else: 
    -                        return {"response": f"Error: Both engines failed. {str(e)}", "chat_history": messages[1:], "usage": usage}
    -                
    -                if hasattr(response, "usage") and response.usage:
    -                    usage["input"] += getattr(response.usage, "prompt_tokens", 0)
    -                    usage["output"] += getattr(response.usage, "completion_tokens", 0)
    -                    usage["total"] += getattr(response.usage, "total_tokens", 0)
    -
    -                resp_msg = response.choices[0].message
    -                msg_dict = resp_msg.model_dump(exclude_none=True)
    -                if msg_dict.get("tool_calls") and msg_dict.get("content") == "": msg_dict["content"] = None
    -                messages.append(msg_dict)
    -
    -                if debug and resp_msg.content and not streamed_response:
    -                    # In CLI debug mode, only print intermediate reasoning if there are tool calls AND it wasn't already streamed.
    -                    # If there are no tool calls, this content is the final answer and will be printed by the caller.
    -                    if resp_msg.tool_calls:
    -                        if status:
    -                            try: status.stop()
    -                            except: pass
    -                        self.console.print(Panel(Markdown(resp_msg.content), title=f"[{current_brain}][bold]{label} Reasoning[/bold][/{current_brain}]", border_style="architect" if current_brain == "architect" else "engineer"))
    -                        if status:
    -                            try: status.start()
    -                            except: pass
    -
    -                if not resp_msg.tool_calls: break
    -                
    -                # Track if we need to inject a user message after all tool responses
    -                pending_user_message = None
    -                
    -                for tc in resp_msg.tool_calls:
    -                    fn, args = tc.function.name, json.loads(tc.function.arguments)
    -                    
    -                    # Validate tool access based on current brain
    -                    if fn in ['delegate_to_engineer'] and current_brain != "architect":
    -                        obs = f"Error: Tool '{fn}' is only available to the Architect (Architect). You are the Engineer (Engineer). Use 'run_commands' directly to execute configuration."
    -                        messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": obs})
    -                        continue
    -                    
    -                    if status:
    -                        if fn == "delegate_to_engineer": update_status(f"[architect]Architect: [DELEGATING MISSION] {args.get('task','')[:40]}...")
    -                        elif fn == "manage_memory_tool": update_status(f"[architect]Architect: [UPDATING MEMORY]")
    -
    -                    if debug:
    -                        self._print_debug_observation(f"Decision: {fn}", args, status=status)
    -
    -                    if fn == "delegate_to_engineer":
    -                        obs, eng_usage = self._engineer_loop(args["task"], status=status, debug=debug, chat_history=messages[:-1])
    -                        usage["input"] += eng_usage["input"]; usage["output"] += eng_usage["output"]; usage["total"] += eng_usage["total"]
    -                    elif fn == "consult_architect":
    -                        if status: update_status("[architect]Engineer consulting Architect...")
    -                        try:
    -                            # Consultation only - Engineer stays in control
    -                            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
    -                            )
    -                            obs = claude_resp.choices[0].message.content
    -                            if debug:
    -                                if status:
    -                                    try: status.stop()
    -                                    except: pass
    -                                self.console.print(Panel(Markdown(obs), title="[architect]Architect Consultation[/architect]", border_style="architect"))
    -                                if status:
    -                                    try: status.start()
    -                                    except: pass
    -                        except Exception as e:
    -                            if status: update_status("[unavailable]Architect unavailable! Engineer continuing alone...")
    -                            obs = f"Architect unavailable ({str(e)}). Proceeding with your best technical judgment."
    -                    
    -                    elif fn == "escalate_to_architect":
    -                        if status: update_status("[architect]Transferring control to Architect...")
    -                        # Full escalation - Architect takes over
    -                        current_brain = "architect"
    -                        model = self.architect_model
    -                        tools = self._get_architect_tools()
    -                        key = self.architect_key
    -                        current_auth = self.architect_auth
    -                        messages[0] = {"role": "system", "content": self.architect_system_prompt}
    -                        # Prepare handover context to inject AFTER all tool responses
    -                        handover_msg = f"HANDOVER FROM EXECUTION ENGINE\n\nReason: {args['reason']}\n\nContext: {args['context']}\n\nYou are now in control of this conversation."
    -                        pending_user_message = handover_msg
    -                        obs = "Control transferred to Architect. Handover context will be provided."
    -                        if debug:
    -                            if status:
    -                                try: status.stop()
    -                                except: pass
    -                            self.console.print(Panel(Text(handover_msg), title="[architect]Escalation to Architect[/architect]", border_style="architect"))
    -                            if status:
    -                                try: status.start()
    -                                except: pass
    -                    
    -                    elif fn == "return_to_engineer":
    -                        if status: update_status("[engineer]Transferring control back to Engineer...")
    -                        # Architect returns control to Engineer
    -                        current_brain = "engineer"
    -                        model = self.engineer_model
    -                        tools = self._get_engineer_tools()
    -                        key = self.engineer_key
    -                        current_auth = self.engineer_auth
    -                        messages[0] = {"role": "system", "content": self.engineer_system_prompt}
    -                        # Prepare handover context to inject AFTER all tool responses
    -                        handover_msg = f"HANDOVER FROM ARCHITECT\n\nSummary: {args['summary']}\n\nYou are now back in control. Continue handling the user's requests."
    -                        pending_user_message = handover_msg
    -                        obs = "Control returned to Engineer. Handover summary will be provided."
    -                        if debug:
    -                            if status:
    -                                try: status.stop()
    -                                except: pass
    -                            self.console.print(Panel(Text(handover_msg), title="[engineer]Return to Engineer[/engineer]", border_style="engineer"))
    -                            if status:
    -                                try: status.start()
    -                                except: pass
    -                    
    -                    elif fn == "list_nodes": obs = self.list_nodes_tool(**args)
    -                    elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
    -                    elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
    -                    elif fn == "manage_memory_tool": obs = self.manage_memory_tool(**args)
    -                    elif fn.startswith("mcp_"):
    -                        obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
    -                    elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
    -                    else: obs = f"Error: {fn} unknown."
    -
    -                    if debug and fn not in ["delegate_to_engineer", "consult_architect", "escalate_to_architect", "return_to_engineer"]:
    -                        self._print_debug_observation(f"Observation: {fn}", obs, status=status)
    -
    -                    # Ensure observation is a string and truncated for the LLM
    -                    obs_str = obs if isinstance(obs, str) else json.dumps(obs)
    -                    messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": self._truncate(obs_str)})                
    -                # Inject pending user message AFTER all tool responses are added
    -                if pending_user_message:
    -                    messages.append({"role": "user", "content": pending_user_message})
    -            
    -            if iteration >= self.hard_limit_iterations:
    -                self.console.print(f"[error]⛔ Agent reached hard limit ({self.hard_limit_iterations} steps). Forcing stop to prevent infinite loop.[/error]")
    -                # Only inject user message if we're not in the middle of tool calls
    -                last_msg = messages[-1] if messages else {}
    -                if last_msg.get("role") != "assistant" or not last_msg.get("tool_calls"):
    -                    messages.append({"role": "user", "content": "Hard iteration limit reached. Please provide a summary of your findings so far."})
    -                    try:
    -                        safe_messages = self._sanitize_messages(messages)
    -                        response = completion(model=model, messages=safe_messages, tools=[], **current_auth)
    -                        resp_msg = response.choices[0].message
    -                        messages.append(resp_msg.model_dump(exclude_none=True))
    -                    except Exception as e:
    -                        if status:
    -                            update_status(f"[error]Error fetching summary: {e}[/error]")
    -                        printer.warning(f"Failed to fetch final summary from LLM: {e}")
    -        except KeyboardInterrupt:
    -            if status: status.update("[error]Interrupted! Closing pending tasks...")
    -            last_msg = messages[-1]
    -            if last_msg.get("tool_calls"):
    -                for tc in last_msg["tool_calls"]:
    -                    messages.append({"tool_call_id": tc.get("id"), "role": "tool", "name": tc.get("function", {}).get("name"), "content": "Operation cancelled by user."})
    -            
    -            # Use a fresh list for the summary call to avoid history corruption
    -            summary_messages = list(messages)
    -            summary_messages.append({"role": "user", "content": "USER INTERRUPTED. Briefly summarize what you were doing and stop."})
    -            try:
    -                safe_messages = self._sanitize_messages(summary_messages)
    -                # Use tools=None to force a text summary during interruption
    -                response = completion(model=model, messages=safe_messages, tools=None, **current_auth)
    -                resp_msg = response.choices[0].message
    -                messages.append(resp_msg.model_dump(exclude_none=True))
    -                
    -                # IMPORTANT: Manually trigger callback for the summary so Web UI sees it
    -                if chunk_callback and resp_msg.content:
    -                    chunk_callback(resp_msg.content)
    -            except Exception:
    -                error_msg = "Operation interrupted by user. Summary unavailable."
    -                messages.append({"role": "assistant", "content": error_msg})
    -                if chunk_callback:
    -                    chunk_callback(error_msg)
    -        finally:
    -            # Auto-save session
    -            self.save_session(messages, model=model)
    -
    -        return {
    -            "response": messages[-1].get("content"), 
    -            "chat_history": messages[1:], 
    -            "app_related": True, 
    -            "usage": usage,
    -            "responder": current_brain,  # "architect" or "engineer"
    -            "streamed": streamed_response
    -        }
    -
    -    @MethodHook
    -    async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
    -        import json
    -        import re
    -        from litellm import acompletion
    -        import asyncio
    -        import warnings
    -        import aiohttp
    -        
    -        # Suppress unawaited coroutine warnings from LiteLLM's internal streaming logic during sudden cancellation
    -        warnings.filterwarnings("ignore", message="coroutine '.*async_streaming.*' was never awaited", category=RuntimeWarning)
    -        
    -        node_info = node_info or {}
    -        os_info = node_info.get("os", "unknown")
    -        node_name = node_info.get("name", "unknown")
    -        persona = node_info.get("persona", "engineer")
    -        memories = node_info.get("memories", [])
    -        
    -        vendor_reference = ""
    -        if os_info and os_info != "unknown":
    -            try:
    -                os_filename = os_info.lower().replace(" ", "_")
    -                ref_path = os.path.join(self.config.defaultdir, "ai_references", f"{os_filename}.md")
    -                if os.path.exists(ref_path):
    -                    with open(ref_path, "r") as f:
    -                        vendor_reference = f.read().strip()
    -            except Exception:
    -                pass
    -        
    -        if persona == "architect":
    -            system_prompt = f"""Role: NETWORK ARCHITECT. You act as a senior strategic advisor during a live SSH session.
    -Rules:
    -1. MANDATORY: You MUST respond in the same language used by the user in their question.
    -2. Answer the user's question directly and EXCLUSIVELY based on the Terminal Context. 
    -3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information.
    -4. Focus on the "why" and "how". Analyze topologies, design patterns, and validate configurations.
    -5. Do NOT provide commands to execute unless specifically requested. Instead, explain the consequences and best practices.
    -6. Keep your guide concise and authoritative.
    -7. You MUST output your response in the following strict format:
    -<guide>
    -Your brief tactical guide in markdown.
    -</guide>
    -<commands>
    -</commands>
    -<risk>
    -low
    -</risk>
    -8. Risk level is usually "low" for read-only/no commands.
    -
    -Terminal Context:
    -{terminal_buffer}
    -
    -Device OS: {os_info}
    -Node: {node_name}"""
    -        else:
    -            system_prompt = f"""Role: TERMINAL COPILOT. You assist a network engineer during a live SSH session.
    -Rules:
    -1. MANDATORY: You MUST respond in the same language used by the user in their question.
    -2. EXTREMELY IMPORTANT: Answer EXCLUSIVELY based on the provided Terminal Context. 
    -3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information. Instead, explicitly state that you don't see the data and offer the correct CLI commands to retrieve it.
    -4. If the user asks you to analyze, parse, or extract data from the Terminal Context, DO IT directly in the <guide> section (you can use markdown tables or lists). Do NOT just give them a command to do it themselves.
    -5. If the user wants to execute an action, provide the required CLI commands inside a <commands> block, one command per line. If no commands are needed, leave it empty or omit the block.
    -6. ULTRA-CONCISE. Keep your guide to the point.
    -7. You MUST output your response in the following strict format:
    -<guide>
    -Your brief tactical guide in markdown. 3-4 sentences max.
    -</guide>
    -<commands>
    -command 1
    -command 2
    -</commands>
    -<risk>
    -low, high, or destructive
    -</risk>
    -8. Risk level: "low" for read-only/no commands, "high" for config changes, "destructive" for potentially dangerous ops.
    -
    -Terminal Context:
    -{terminal_buffer}
    -
    -Device OS: {os_info}
    -Node: {node_name}"""
    -        
    -        if vendor_reference:
    -            system_prompt += f"\n\nVendor Command Reference:\n{vendor_reference}"
    -
    -        if memories:
    -            system_prompt += "\n\nSession Memory (Important Facts):\n"
    -            for m in memories:
    -                system_prompt += f"- {m}\n"
    -
    -        # Fetch MCP tools for the current OS
    -        mcp_tools = []
    -        try:
    -            mcp_tools = await self.mcp_manager.get_tools_for_llm(os_filter=os_info)
    -        except Exception:
    -            pass
    -            
    -        if mcp_tools:
    -            system_prompt += f"\n\nAvailable MCP Tools: {', '.join([t['function']['name'] for t in mcp_tools])}"
    -            system_prompt += "\nUse these tools to validate syntax or find exact commands if needed before providing the final guide."
    -
    -        messages = [
    -            {"role": "system", "content": system_prompt},
    -            {"role": "user", "content": user_question}
    -        ]
    -
    -        iteration = 0
    -        max_iterations = 5 # Allow up to 5 iterations for tool usage
    -        
    -        # Use models based on persona
    -        current_model = self.architect_model if persona == "architect" else self.engineer_model
    -        current_key = self.architect_key if persona == "architect" else self.engineer_key
    -        current_auth = self.architect_auth if persona == "architect" else self.engineer_auth
    -
    -        try:
    -            while iteration < max_iterations:
    -                iteration += 1
    -
    -                response = await acompletion(
    -                    model=current_model,
    -                    messages=messages,
    -                    tools=mcp_tools if mcp_tools else None,
    -                    stream=True,
    -                    **current_auth
    -                )
    -                
    -                full_content = ""
    -                streamed_guide = ""
    -                tool_calls = []
    -                
    -                async for chunk in response:
    -                    delta = chunk.choices[0].delta
    -                    
    -                    # Accumulate tool calls
    -                    if hasattr(delta, 'tool_calls') and delta.tool_calls:
    -                        for tc in delta.tool_calls:
    -                            idx = tc.index
    -                            if idx >= len(tool_calls):
    -                                tool_calls.append({"id": tc.id, "type": "function", "function": {"name": tc.function.name or "", "arguments": tc.function.arguments or ""}})
    -                            else:
    -                                if tc.id: tool_calls[idx]["id"] = tc.id
    -                                if tc.function.name: tool_calls[idx]["function"]["name"] = tc.function.name
    -                                if tc.function.arguments: tool_calls[idx]["function"]["arguments"] += tc.function.arguments
    -
    -                    if hasattr(delta, 'content') and delta.content:
    -                        full_content += delta.content
    -                        
    -                        if chunk_callback and not tool_calls: # Only stream if not using tools
    -                            start_idx = full_content.find("<guide>")
    -                            if start_idx != -1:
    -                                after_start = full_content[start_idx + 7:]
    -                                end_idx = after_start.find("</guide>")
    -                                
    -                                if end_idx != -1:
    -                                    current_guide = after_start[:end_idx]
    -                                else:
    -                                    current_guide = after_start
    -                                    if current_guide.endswith("<"): current_guide = current_guide[:-1]
    -                                    elif current_guide.endswith("</"): current_guide = current_guide[:-2]
    -                                    elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
    -                                    elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
    -                                    elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
    -                                    elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
    -                                    elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
    -                                
    -                                new_text = current_guide[len(streamed_guide):]
    -                                if new_text:
    -                                    chunk_callback(new_text)
    -                                    streamed_guide += new_text
    -
    -                if not tool_calls:
    -                    break
    -                    
    -                # Execute tool calls
    -                messages.append({"role": "assistant", "content": full_content or None, "tool_calls": tool_calls})
    -                for tc in tool_calls:
    -                    fn = tc["function"]["name"]
    -                    args = json.loads(tc["function"]["arguments"])
    -                    
    -                    if "mcp_" in fn:
    -                        try:
    -                            obs = await asyncio.wait_for(self.mcp_manager.call_tool(fn, args), timeout=30.0)
    -                        except Exception as e:
    -                            obs = f"Error calling MCP tool: {e}"
    -                    else:
    -                        obs = f"Error: Tool {fn} not allowed in Copilot."
    -                        
    -                    messages.append({"tool_call_id": tc["id"], "role": "tool", "name": fn, "content": self._truncate(str(obs))})
    -
    -            # If we hit the limit and it was still using tools, force a final answer
    -            if tool_calls and iteration >= max_iterations:
    -                messages.append({"role": "user", "content": "Tool limit reached. Provide your final tactical guide now based on the findings."})
    -                response = await acompletion(
    -                    model=self.engineer_model,
    -                    messages=messages,
    -                    tools=None,
    -                    stream=True,
    -                    **self.engineer_auth
    -                )
    -                
    -                full_content = ""
    -                streamed_guide = ""
    -                async for chunk in response:
    -                    delta = chunk.choices[0].delta
    -                    if hasattr(delta, 'content') and delta.content:
    -                        full_content += delta.content
    -                        if chunk_callback:
    -                            start_idx = full_content.find("<guide>")
    -                            if start_idx != -1:
    -                                after_start = full_content[start_idx + 7:]
    -                                end_idx = after_start.find("</guide>")
    -                                if end_idx != -1:
    -                                    current_guide = after_start[:end_idx]
    -                                else:
    -                                    current_guide = after_start
    -                                    if current_guide.endswith("<"): current_guide = current_guide[:-1]
    -                                    elif current_guide.endswith("</"): current_guide = current_guide[:-2]
    -                                    elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
    -                                    elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
    -                                    elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
    -                                    elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
    -                                    elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
    -                                new_text = current_guide[len(streamed_guide):]
    -                                if new_text:
    -                                    chunk_callback(new_text)
    -                                    streamed_guide += new_text
    -
    -            guide = ""
    -            commands = []
    -            risk_level = "low"
    -            
    -            guide_match = re.search(r"<guide>(.*?)</guide>", full_content, re.DOTALL)
    -            if guide_match:
    -                guide = guide_match.group(1).strip()
    -                
    -            cmd_match = re.search(r"<commands>(.*?)</commands>", full_content, re.DOTALL)
    -            if cmd_match:
    -                cmds_raw = cmd_match.group(1).strip()
    -                if cmds_raw:
    -                    commands = [c.strip() for c in cmds_raw.split('\n') if c.strip()]
    -                    
    -            risk_match = re.search(r"<risk>(.*?)</risk>", full_content, re.DOTALL)
    -            if risk_match:
    -                risk_level = risk_match.group(1).strip().lower()
    -
    -            if not guide and full_content and not ("<guide>" in full_content):
    -                guide = full_content.strip()
    -
    -            return {
    -                "commands": commands,
    -                "guide": guide,
    -                "risk_level": risk_level,
    -                "error": None
    -            }
    -            
    -        except asyncio.CancelledError:
    -            # Client cancelled the request via gRPC or local interrupt
    -            if 'response' in locals():
    -                try:
    -                    if hasattr(response, 'aclose'):
    -                        # Fire and forget the close to avoid blocking the cancel
    -                        asyncio.create_task(response.aclose())
    -                    elif hasattr(response, 'close'):
    -                        response.close()
    -                except Exception:
    -                    pass
    -            return None
    -        except Exception as e:
    -            return {
    -                "commands": [],
    -                "guide": "",
    -                "risk_level": "low",
    -                "error": str(e)
    -            }
    -
    -    @MethodHook
    -    def confirm(self, user_input): return True
    -
    -

    Hybrid Multi-Agent System: Selective Escalation with Role Persistence.

    -

    Class variables

    -
    -
    var SAFE_COMMANDS
    -
    -
    -
    -
    -

    Instance variables

    -
    -
    prop architect_system_prompt
    -
    -
    - -Expand source code - -
    @property
    -def architect_system_prompt(self):
    -    """Build architect system prompt with plugin extensions."""
    -    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."
    -    if self.architect_prompt_extensions:
    -        extensions = "\n".join(self.architect_prompt_extensions)
    -        return prompt + f"\n\nPlugin Capabilities:\n{extensions}"
    -    return prompt
    -
    -

    Build architect system prompt with plugin extensions.

    -
    -
    prop engineer_system_prompt
    -
    -
    - -Expand source code - -
    @property
    -def engineer_system_prompt(self):
    -    """Build engineer system prompt with plugin extensions."""
    -    if self.engineer_prompt_extensions:
    -        extensions = "\n".join(self.engineer_prompt_extensions)
    -        return self._engineer_base_prompt + f"\n\nPlugin Capabilities:\n{extensions}"
    -    return self._engineer_base_prompt
    -
    -

    Build engineer system prompt with plugin extensions.

    -
    -
    -

    Methods

    -
    -
    -async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None) -
    -
    -
    - -Expand source code - -
        @MethodHook
    -    async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
    -        import json
    -        import re
    -        from litellm import acompletion
    -        import asyncio
    -        import warnings
    -        import aiohttp
    -        
    -        # Suppress unawaited coroutine warnings from LiteLLM's internal streaming logic during sudden cancellation
    -        warnings.filterwarnings("ignore", message="coroutine '.*async_streaming.*' was never awaited", category=RuntimeWarning)
    -        
    -        node_info = node_info or {}
    -        os_info = node_info.get("os", "unknown")
    -        node_name = node_info.get("name", "unknown")
    -        persona = node_info.get("persona", "engineer")
    -        memories = node_info.get("memories", [])
    -        
    -        vendor_reference = ""
    -        if os_info and os_info != "unknown":
    -            try:
    -                os_filename = os_info.lower().replace(" ", "_")
    -                ref_path = os.path.join(self.config.defaultdir, "ai_references", f"{os_filename}.md")
    -                if os.path.exists(ref_path):
    -                    with open(ref_path, "r") as f:
    -                        vendor_reference = f.read().strip()
    -            except Exception:
    -                pass
    -        
    -        if persona == "architect":
    -            system_prompt = f"""Role: NETWORK ARCHITECT. You act as a senior strategic advisor during a live SSH session.
    -Rules:
    -1. MANDATORY: You MUST respond in the same language used by the user in their question.
    -2. Answer the user's question directly and EXCLUSIVELY based on the Terminal Context. 
    -3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information.
    -4. Focus on the "why" and "how". Analyze topologies, design patterns, and validate configurations.
    -5. Do NOT provide commands to execute unless specifically requested. Instead, explain the consequences and best practices.
    -6. Keep your guide concise and authoritative.
    -7. You MUST output your response in the following strict format:
    -<guide>
    -Your brief tactical guide in markdown.
    -</guide>
    -<commands>
    -</commands>
    -<risk>
    -low
    -</risk>
    -8. Risk level is usually "low" for read-only/no commands.
    -
    -Terminal Context:
    -{terminal_buffer}
    -
    -Device OS: {os_info}
    -Node: {node_name}"""
    -        else:
    -            system_prompt = f"""Role: TERMINAL COPILOT. You assist a network engineer during a live SSH session.
    -Rules:
    -1. MANDATORY: You MUST respond in the same language used by the user in their question.
    -2. EXTREMELY IMPORTANT: Answer EXCLUSIVELY based on the provided Terminal Context. 
    -3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information. Instead, explicitly state that you don't see the data and offer the correct CLI commands to retrieve it.
    -4. If the user asks you to analyze, parse, or extract data from the Terminal Context, DO IT directly in the <guide> section (you can use markdown tables or lists). Do NOT just give them a command to do it themselves.
    -5. If the user wants to execute an action, provide the required CLI commands inside a <commands> block, one command per line. If no commands are needed, leave it empty or omit the block.
    -6. ULTRA-CONCISE. Keep your guide to the point.
    -7. You MUST output your response in the following strict format:
    -<guide>
    -Your brief tactical guide in markdown. 3-4 sentences max.
    -</guide>
    -<commands>
    -command 1
    -command 2
    -</commands>
    -<risk>
    -low, high, or destructive
    -</risk>
    -8. Risk level: "low" for read-only/no commands, "high" for config changes, "destructive" for potentially dangerous ops.
    -
    -Terminal Context:
    -{terminal_buffer}
    -
    -Device OS: {os_info}
    -Node: {node_name}"""
    -        
    -        if vendor_reference:
    -            system_prompt += f"\n\nVendor Command Reference:\n{vendor_reference}"
    -
    -        if memories:
    -            system_prompt += "\n\nSession Memory (Important Facts):\n"
    -            for m in memories:
    -                system_prompt += f"- {m}\n"
    -
    -        # Fetch MCP tools for the current OS
    -        mcp_tools = []
    -        try:
    -            mcp_tools = await self.mcp_manager.get_tools_for_llm(os_filter=os_info)
    -        except Exception:
    -            pass
    -            
    -        if mcp_tools:
    -            system_prompt += f"\n\nAvailable MCP Tools: {', '.join([t['function']['name'] for t in mcp_tools])}"
    -            system_prompt += "\nUse these tools to validate syntax or find exact commands if needed before providing the final guide."
    -
    -        messages = [
    -            {"role": "system", "content": system_prompt},
    -            {"role": "user", "content": user_question}
    -        ]
    -
    -        iteration = 0
    -        max_iterations = 5 # Allow up to 5 iterations for tool usage
    -        
    -        # Use models based on persona
    -        current_model = self.architect_model if persona == "architect" else self.engineer_model
    -        current_key = self.architect_key if persona == "architect" else self.engineer_key
    -        current_auth = self.architect_auth if persona == "architect" else self.engineer_auth
    -
    -        try:
    -            while iteration < max_iterations:
    -                iteration += 1
    -
    -                response = await acompletion(
    -                    model=current_model,
    -                    messages=messages,
    -                    tools=mcp_tools if mcp_tools else None,
    -                    stream=True,
    -                    **current_auth
    -                )
    -                
    -                full_content = ""
    -                streamed_guide = ""
    -                tool_calls = []
    -                
    -                async for chunk in response:
    -                    delta = chunk.choices[0].delta
    -                    
    -                    # Accumulate tool calls
    -                    if hasattr(delta, 'tool_calls') and delta.tool_calls:
    -                        for tc in delta.tool_calls:
    -                            idx = tc.index
    -                            if idx >= len(tool_calls):
    -                                tool_calls.append({"id": tc.id, "type": "function", "function": {"name": tc.function.name or "", "arguments": tc.function.arguments or ""}})
    -                            else:
    -                                if tc.id: tool_calls[idx]["id"] = tc.id
    -                                if tc.function.name: tool_calls[idx]["function"]["name"] = tc.function.name
    -                                if tc.function.arguments: tool_calls[idx]["function"]["arguments"] += tc.function.arguments
    -
    -                    if hasattr(delta, 'content') and delta.content:
    -                        full_content += delta.content
    -                        
    -                        if chunk_callback and not tool_calls: # Only stream if not using tools
    -                            start_idx = full_content.find("<guide>")
    -                            if start_idx != -1:
    -                                after_start = full_content[start_idx + 7:]
    -                                end_idx = after_start.find("</guide>")
    -                                
    -                                if end_idx != -1:
    -                                    current_guide = after_start[:end_idx]
    -                                else:
    -                                    current_guide = after_start
    -                                    if current_guide.endswith("<"): current_guide = current_guide[:-1]
    -                                    elif current_guide.endswith("</"): current_guide = current_guide[:-2]
    -                                    elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
    -                                    elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
    -                                    elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
    -                                    elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
    -                                    elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
    -                                
    -                                new_text = current_guide[len(streamed_guide):]
    -                                if new_text:
    -                                    chunk_callback(new_text)
    -                                    streamed_guide += new_text
    -
    -                if not tool_calls:
    -                    break
    -                    
    -                # Execute tool calls
    -                messages.append({"role": "assistant", "content": full_content or None, "tool_calls": tool_calls})
    -                for tc in tool_calls:
    -                    fn = tc["function"]["name"]
    -                    args = json.loads(tc["function"]["arguments"])
    -                    
    -                    if "mcp_" in fn:
    -                        try:
    -                            obs = await asyncio.wait_for(self.mcp_manager.call_tool(fn, args), timeout=30.0)
    -                        except Exception as e:
    -                            obs = f"Error calling MCP tool: {e}"
    -                    else:
    -                        obs = f"Error: Tool {fn} not allowed in Copilot."
    -                        
    -                    messages.append({"tool_call_id": tc["id"], "role": "tool", "name": fn, "content": self._truncate(str(obs))})
    -
    -            # If we hit the limit and it was still using tools, force a final answer
    -            if tool_calls and iteration >= max_iterations:
    -                messages.append({"role": "user", "content": "Tool limit reached. Provide your final tactical guide now based on the findings."})
    -                response = await acompletion(
    -                    model=self.engineer_model,
    -                    messages=messages,
    -                    tools=None,
    -                    stream=True,
    -                    **self.engineer_auth
    -                )
    -                
    -                full_content = ""
    -                streamed_guide = ""
    -                async for chunk in response:
    -                    delta = chunk.choices[0].delta
    -                    if hasattr(delta, 'content') and delta.content:
    -                        full_content += delta.content
    -                        if chunk_callback:
    -                            start_idx = full_content.find("<guide>")
    -                            if start_idx != -1:
    -                                after_start = full_content[start_idx + 7:]
    -                                end_idx = after_start.find("</guide>")
    -                                if end_idx != -1:
    -                                    current_guide = after_start[:end_idx]
    -                                else:
    -                                    current_guide = after_start
    -                                    if current_guide.endswith("<"): current_guide = current_guide[:-1]
    -                                    elif current_guide.endswith("</"): current_guide = current_guide[:-2]
    -                                    elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
    -                                    elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
    -                                    elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
    -                                    elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
    -                                    elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
    -                                new_text = current_guide[len(streamed_guide):]
    -                                if new_text:
    -                                    chunk_callback(new_text)
    -                                    streamed_guide += new_text
    -
    -            guide = ""
    -            commands = []
    -            risk_level = "low"
    -            
    -            guide_match = re.search(r"<guide>(.*?)</guide>", full_content, re.DOTALL)
    -            if guide_match:
    -                guide = guide_match.group(1).strip()
    -                
    -            cmd_match = re.search(r"<commands>(.*?)</commands>", full_content, re.DOTALL)
    -            if cmd_match:
    -                cmds_raw = cmd_match.group(1).strip()
    -                if cmds_raw:
    -                    commands = [c.strip() for c in cmds_raw.split('\n') if c.strip()]
    -                    
    -            risk_match = re.search(r"<risk>(.*?)</risk>", full_content, re.DOTALL)
    -            if risk_match:
    -                risk_level = risk_match.group(1).strip().lower()
    -
    -            if not guide and full_content and not ("<guide>" in full_content):
    -                guide = full_content.strip()
    -
    -            return {
    -                "commands": commands,
    -                "guide": guide,
    -                "risk_level": risk_level,
    -                "error": None
    -            }
    -            
    -        except asyncio.CancelledError:
    -            # Client cancelled the request via gRPC or local interrupt
    -            if 'response' in locals():
    -                try:
    -                    if hasattr(response, 'aclose'):
    -                        # Fire and forget the close to avoid blocking the cancel
    -                        asyncio.create_task(response.aclose())
    -                    elif hasattr(response, 'close'):
    -                        response.close()
    -                except Exception:
    -                    pass
    -            return None
    -        except Exception as e:
    -            return {
    -                "commands": [],
    -                "guide": "",
    -                "risk_level": "low",
    -                "error": str(e)
    -            }
    -
    -
    -
    -
    -def ask(self,
    user_input,
    dryrun=False,
    chat_history=None,
    status=None,
    debug=False,
    stream=True,
    session_id=None,
    chunk_callback=None)
    -
    -
    -
    - -Expand source code - -
    @MethodHook
    -def ask(self, user_input, dryrun=False, chat_history=None, status=None, debug=False, stream=True, session_id=None, chunk_callback=None):
    -    is_engineer_keyless = "vertex" in self.engineer_model.lower() or "ollama" in self.engineer_model.lower() or "local" in self.engineer_model.lower()
    -    if not self.engineer_key and not self.engineer_auth and not is_engineer_keyless:
    -        raise ValueError("Engineer API key or authentication not configured. Use 'connpy config --engineer-auth <auth>' to set it.")
    -
    -    def update_status(text):
    -        if not status:
    -            return
    -        if iteration >= self.soft_limit_iterations:
    -            warning_suffix = " [warning]⚠ Taking longer than expected (Ctrl+C to interrupt)[/warning]"
    -            if warning_suffix not in text:
    -                text += warning_suffix
    -        status.update(text)
    -        
    -    if chat_history is None: chat_history = []
    -    
    -    # Load session if provided and history is empty
    -    if session_id:
    -        # Force the session_id even if it doesn't exist yet
    -        self.session_id = session_id
    -        self.session_path = os.path.join(self.sessions_dir, f"{session_id}.json")
    -        
    -        if not chat_history:
    -            session_data = self.load_session_data(session_id)
    -            if session_data:
    -                chat_history = session_data.get("history", [])
    -            # If we loaded history, the caller might need it back
    -            # But typically ask() is called in a loop with an external history object
    -
    -    usage = {"input": 0, "output": 0, "total": 0}
    -    
    -    # 1. Initial Role Selector (Sticky Brain)
    -    explicit_architect = re.match(r'^(architect|arquitecto|@architect)[:\s]', user_input, re.I)
    -    explicit_engineer = re.match(r'^(engineer|ingeniero|@engineer)[:\s]', user_input, re.I)
    -    
    -    if explicit_architect:
    -        current_brain = "architect"
    -    elif explicit_engineer:
    -        current_brain = "engineer"
    -    else:
    -        # Sticky Brain: Detect if the Architect was in control in recent history
    -        is_architect_active = False
    -        for msg in reversed(chat_history[-5:]):
    -            tcs = msg.get('tool_calls') if isinstance(msg, dict) else getattr(msg, 'tool_calls', None)
    -            if tcs:
    -                for tc in tcs:
    -                    fn = tc.get('function', {}).get('name') if isinstance(tc, dict) else getattr(getattr(tc, 'function', None), 'name', '')
    -                    # Architect stays in control if delegating tasks or if Engineer escalated to them
    -                    # consult_architect is just Engineer asking for advice - Engineer keeps control
    -                    if fn in ['delegate_to_engineer', 'escalate_to_architect']:
    -                        is_architect_active = True; break
    -            if is_architect_active: break
    -        current_brain = "architect" if is_architect_active else "engineer"
    -    
    -    # 2. Message preparation and cleaning
    -    clean_input = re.sub(r'^(architect|arquitecto|engineer|ingeniero|@architect|@engineer)[:\s]+', '', user_input, flags=re.IGNORECASE).strip()
    -    
    -    system_prompt = self.architect_system_prompt if current_brain == "architect" else self.engineer_system_prompt
    -    tools = self._get_architect_tools() if current_brain == "architect" else self._get_engineer_tools()
    -    model = self.architect_model if current_brain == "architect" else self.engineer_model
    -    key = self.architect_key if current_brain == "architect" else self.engineer_key
    -    current_auth = self.architect_auth if current_brain == "architect" else self.engineer_auth
    -
    -    # Optimized structure for Prompt Caching (Only for direct Anthropic, Vertex has different rules)
    -    if "claude" in model.lower() and "vertex" not in model.lower():
    -        messages = [{"role": "system", "content": [{"type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}}]}]
    -    else:
    -        messages = [{"role": "system", "content": system_prompt}]
    -    
    -    # History interleaving
    -    last_role = "system"
    -    # Sanitize history if the current target model is not compatible with cache_control
    -    history_to_process = chat_history[-self.max_history:]
    -    if "claude" not in model.lower() or "vertex" in model.lower():
    -        history_to_process = self._sanitize_messages(history_to_process)
    -
    -    for msg in history_to_process:
    -        m = msg if isinstance(msg, dict) else msg.model_dump(exclude_none=True)
    -        role = m.get('role')
    -        if role == last_role and role == 'user':
    -            messages[-1]['content'] += "\n" + (m.get('content') or "")
    -            continue
    -        if role == 'assistant' and m.get('tool_calls') and m.get('content') == "": m['content'] = None
    -        messages.append(m)
    -        last_role = role
    -
    -    if last_role == 'user': messages[-1]['content'] += "\n" + clean_input
    -    else: messages.append({"role": "user", "content": clean_input})
    -
    -    # 3. Execution loop
    -    iteration = 0
    -    try:
    -        # Set up remote interrupt callback if bridge is provided
    -        if status and hasattr(status, "on_interrupt"):
    -            status.on_interrupt = lambda: setattr(self, "interrupted", True)
    -
    -        while iteration < self.hard_limit_iterations:
    -            iteration += 1
    -            
    -            # Check for interruption
    -            if self.interrupted:
    -                raise KeyboardInterrupt
    -            
    -            # Soft limit warning - handled inline within update_status
    -            
    -            label = "[architect][bold]Architect[/bold][/architect]" if current_brain == "architect" else "[engineer][bold]Engineer[/bold][/engineer]"
    -            if status: 
    -                # Notify responder identity for web/remote clients
    -                if getattr(status, "is_web", False) or getattr(status, "is_remote", False):
    -                    status.update(f"__RESPONDER__:{current_brain}")
    -                update_status(f"{label} is thinking... (step {iteration})")
    -            
    -            streamed_response = False
    -            try:
    -                safe_messages = self._sanitize_messages(messages)
    -                if stream:
    -                    response, streamed_response = self._stream_completion(
    -                        model=model, messages=safe_messages, tools=tools, auth=current_auth,
    -                        status=status, label=label, debug=debug, num_retries=3,
    -                        chunk_callback=chunk_callback
    -                    )
    -                else:
    -                    response = completion(model=model, messages=safe_messages, tools=tools, num_retries=3, **current_auth)
    -            except Exception as e:
    -                if current_brain == "architect":
    -                    if status: update_status("[unavailable]Architect unavailable! Falling back to Engineer...")
    -                    # Preserve context when falling back - use clean_input directly
    -                    current_brain = "engineer"
    -                    model = self.engineer_model
    -                    tools = self._get_engineer_tools()
    -                    key = self.engineer_key
    -                    current_auth = self.engineer_auth
    -                    # Rebuild messages with Engineer system prompt and original user request
    -                    messages = [{"role": "system", "content": self.engineer_system_prompt}]
    -                    # Add chat history if exists (excluding system prompt)
    -                    if chat_history:
    -                        for msg in chat_history[-self.max_history:]:
    -                            if msg.get('role') != 'system':
    -                                messages.append(msg)
    -                    # Add current user request
    -                    messages.append({"role": "user", "content": clean_input})
    -                    continue
    -                else: 
    -                    return {"response": f"Error: Both engines failed. {str(e)}", "chat_history": messages[1:], "usage": usage}
    -            
    -            if hasattr(response, "usage") and response.usage:
    -                usage["input"] += getattr(response.usage, "prompt_tokens", 0)
    -                usage["output"] += getattr(response.usage, "completion_tokens", 0)
    -                usage["total"] += getattr(response.usage, "total_tokens", 0)
    -
    -            resp_msg = response.choices[0].message
    -            msg_dict = resp_msg.model_dump(exclude_none=True)
    -            if msg_dict.get("tool_calls") and msg_dict.get("content") == "": msg_dict["content"] = None
    -            messages.append(msg_dict)
    -
    -            if debug and resp_msg.content and not streamed_response:
    -                # In CLI debug mode, only print intermediate reasoning if there are tool calls AND it wasn't already streamed.
    -                # If there are no tool calls, this content is the final answer and will be printed by the caller.
    -                if resp_msg.tool_calls:
    -                    if status:
    -                        try: status.stop()
    -                        except: pass
    -                    self.console.print(Panel(Markdown(resp_msg.content), title=f"[{current_brain}][bold]{label} Reasoning[/bold][/{current_brain}]", border_style="architect" if current_brain == "architect" else "engineer"))
    -                    if status:
    -                        try: status.start()
    -                        except: pass
    -
    -            if not resp_msg.tool_calls: break
    -            
    -            # Track if we need to inject a user message after all tool responses
    -            pending_user_message = None
    -            
    -            for tc in resp_msg.tool_calls:
    -                fn, args = tc.function.name, json.loads(tc.function.arguments)
    -                
    -                # Validate tool access based on current brain
    -                if fn in ['delegate_to_engineer'] and current_brain != "architect":
    -                    obs = f"Error: Tool '{fn}' is only available to the Architect (Architect). You are the Engineer (Engineer). Use 'run_commands' directly to execute configuration."
    -                    messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": obs})
    -                    continue
    -                
    -                if status:
    -                    if fn == "delegate_to_engineer": update_status(f"[architect]Architect: [DELEGATING MISSION] {args.get('task','')[:40]}...")
    -                    elif fn == "manage_memory_tool": update_status(f"[architect]Architect: [UPDATING MEMORY]")
    -
    -                if debug:
    -                    self._print_debug_observation(f"Decision: {fn}", args, status=status)
    -
    -                if fn == "delegate_to_engineer":
    -                    obs, eng_usage = self._engineer_loop(args["task"], status=status, debug=debug, chat_history=messages[:-1])
    -                    usage["input"] += eng_usage["input"]; usage["output"] += eng_usage["output"]; usage["total"] += eng_usage["total"]
    -                elif fn == "consult_architect":
    -                    if status: update_status("[architect]Engineer consulting Architect...")
    -                    try:
    -                        # Consultation only - Engineer stays in control
    -                        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
    -                        )
    -                        obs = claude_resp.choices[0].message.content
    -                        if debug:
    -                            if status:
    -                                try: status.stop()
    -                                except: pass
    -                            self.console.print(Panel(Markdown(obs), title="[architect]Architect Consultation[/architect]", border_style="architect"))
    -                            if status:
    -                                try: status.start()
    -                                except: pass
    -                    except Exception as e:
    -                        if status: update_status("[unavailable]Architect unavailable! Engineer continuing alone...")
    -                        obs = f"Architect unavailable ({str(e)}). Proceeding with your best technical judgment."
    -                
    -                elif fn == "escalate_to_architect":
    -                    if status: update_status("[architect]Transferring control to Architect...")
    -                    # Full escalation - Architect takes over
    -                    current_brain = "architect"
    -                    model = self.architect_model
    -                    tools = self._get_architect_tools()
    -                    key = self.architect_key
    -                    current_auth = self.architect_auth
    -                    messages[0] = {"role": "system", "content": self.architect_system_prompt}
    -                    # Prepare handover context to inject AFTER all tool responses
    -                    handover_msg = f"HANDOVER FROM EXECUTION ENGINE\n\nReason: {args['reason']}\n\nContext: {args['context']}\n\nYou are now in control of this conversation."
    -                    pending_user_message = handover_msg
    -                    obs = "Control transferred to Architect. Handover context will be provided."
    -                    if debug:
    -                        if status:
    -                            try: status.stop()
    -                            except: pass
    -                        self.console.print(Panel(Text(handover_msg), title="[architect]Escalation to Architect[/architect]", border_style="architect"))
    -                        if status:
    -                            try: status.start()
    -                            except: pass
    -                
    -                elif fn == "return_to_engineer":
    -                    if status: update_status("[engineer]Transferring control back to Engineer...")
    -                    # Architect returns control to Engineer
    -                    current_brain = "engineer"
    -                    model = self.engineer_model
    -                    tools = self._get_engineer_tools()
    -                    key = self.engineer_key
    -                    current_auth = self.engineer_auth
    -                    messages[0] = {"role": "system", "content": self.engineer_system_prompt}
    -                    # Prepare handover context to inject AFTER all tool responses
    -                    handover_msg = f"HANDOVER FROM ARCHITECT\n\nSummary: {args['summary']}\n\nYou are now back in control. Continue handling the user's requests."
    -                    pending_user_message = handover_msg
    -                    obs = "Control returned to Engineer. Handover summary will be provided."
    -                    if debug:
    -                        if status:
    -                            try: status.stop()
    -                            except: pass
    -                        self.console.print(Panel(Text(handover_msg), title="[engineer]Return to Engineer[/engineer]", border_style="engineer"))
    -                        if status:
    -                            try: status.start()
    -                            except: pass
    -                
    -                elif fn == "list_nodes": obs = self.list_nodes_tool(**args)
    -                elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
    -                elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
    -                elif fn == "manage_memory_tool": obs = self.manage_memory_tool(**args)
    -                elif fn.startswith("mcp_"):
    -                    obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
    -                elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
    -                else: obs = f"Error: {fn} unknown."
    -
    -                if debug and fn not in ["delegate_to_engineer", "consult_architect", "escalate_to_architect", "return_to_engineer"]:
    -                    self._print_debug_observation(f"Observation: {fn}", obs, status=status)
    -
    -                # Ensure observation is a string and truncated for the LLM
    -                obs_str = obs if isinstance(obs, str) else json.dumps(obs)
    -                messages.append({"tool_call_id": tc.id, "role": "tool", "name": fn, "content": self._truncate(obs_str)})                
    -            # Inject pending user message AFTER all tool responses are added
    -            if pending_user_message:
    -                messages.append({"role": "user", "content": pending_user_message})
    -        
    -        if iteration >= self.hard_limit_iterations:
    -            self.console.print(f"[error]⛔ Agent reached hard limit ({self.hard_limit_iterations} steps). Forcing stop to prevent infinite loop.[/error]")
    -            # Only inject user message if we're not in the middle of tool calls
    -            last_msg = messages[-1] if messages else {}
    -            if last_msg.get("role") != "assistant" or not last_msg.get("tool_calls"):
    -                messages.append({"role": "user", "content": "Hard iteration limit reached. Please provide a summary of your findings so far."})
    -                try:
    -                    safe_messages = self._sanitize_messages(messages)
    -                    response = completion(model=model, messages=safe_messages, tools=[], **current_auth)
    -                    resp_msg = response.choices[0].message
    -                    messages.append(resp_msg.model_dump(exclude_none=True))
    -                except Exception as e:
    -                    if status:
    -                        update_status(f"[error]Error fetching summary: {e}[/error]")
    -                    printer.warning(f"Failed to fetch final summary from LLM: {e}")
    -    except KeyboardInterrupt:
    -        if status: status.update("[error]Interrupted! Closing pending tasks...")
    -        last_msg = messages[-1]
    -        if last_msg.get("tool_calls"):
    -            for tc in last_msg["tool_calls"]:
    -                messages.append({"tool_call_id": tc.get("id"), "role": "tool", "name": tc.get("function", {}).get("name"), "content": "Operation cancelled by user."})
    -        
    -        # Use a fresh list for the summary call to avoid history corruption
    -        summary_messages = list(messages)
    -        summary_messages.append({"role": "user", "content": "USER INTERRUPTED. Briefly summarize what you were doing and stop."})
    -        try:
    -            safe_messages = self._sanitize_messages(summary_messages)
    -            # Use tools=None to force a text summary during interruption
    -            response = completion(model=model, messages=safe_messages, tools=None, **current_auth)
    -            resp_msg = response.choices[0].message
    -            messages.append(resp_msg.model_dump(exclude_none=True))
    -            
    -            # IMPORTANT: Manually trigger callback for the summary so Web UI sees it
    -            if chunk_callback and resp_msg.content:
    -                chunk_callback(resp_msg.content)
    -        except Exception:
    -            error_msg = "Operation interrupted by user. Summary unavailable."
    -            messages.append({"role": "assistant", "content": error_msg})
    -            if chunk_callback:
    -                chunk_callback(error_msg)
    -    finally:
    -        # Auto-save session
    -        self.save_session(messages, model=model)
    -
    -    return {
    -        "response": messages[-1].get("content"), 
    -        "chat_history": messages[1:], 
    -        "app_related": True, 
    -        "usage": usage,
    -        "responder": current_brain,  # "architect" or "engineer"
    -        "streamed": streamed_response
    -    }
    -
    -
    -
    -
    -def confirm(self, user_input) -
    -
    -
    - -Expand source code - -
    @MethodHook
    -def confirm(self, user_input): return True
    -
    -
    -
    -
    -def delete_session(self, session_id) -
    -
    -
    - -Expand source code - -
    def delete_session(self, session_id):
    -    """Deletes a session by ID."""
    -    path = os.path.join(self.sessions_dir, f"{session_id}.json")
    -    if os.path.exists(path):
    -        os.remove(path)
    -        printer.success(f"Session {session_id} deleted.")
    -    else:
    -        printer.error(f"Session {session_id} not found.")
    -
    -

    Deletes a session by ID.

    -
    -
    -def get_last_session_id(self) -
    -
    -
    - -Expand source code - -
    def get_last_session_id(self):
    -    """Returns the ID of the most recent session."""
    -    sessions = self._get_sessions()
    -    return sessions[0]["id"] if sessions else None
    -
    -

    Returns the ID of the most recent session.

    -
    -
    -def get_node_info_tool(self, node_name) -
    -
    -
    - -Expand source code - -
    def get_node_info_tool(self, node_name):
    -    """Get detailed metadata for a specific node. Passwords are masked."""
    -    try:
    -        d = self.config.getitem(node_name, extract=True)
    -        if 'password' in d: d['password'] = '***'
    -        return d
    -    except Exception as e: 
    -        return f"Error getting node info: {str(e)}"
    -
    -

    Get detailed metadata for a specific node. Passwords are masked.

    -
    -
    -def list_nodes_tool(self, filter_pattern='.*') -
    -
    -
    - -Expand source code - -
    def list_nodes_tool(self, filter_pattern=".*"):
    -    """List nodes matching the filter pattern. Returns metadata for <=5 nodes, names only for more."""
    -    try:
    -        matched_names = self.config._getallnodes(filter_pattern)
    -        if not matched_names: return "No nodes found."
    -        if len(matched_names) <= 5:
    -            matched_data = self.config.getitems(matched_names, extract=True)
    -            res = {}
    -            for name, data in matched_data.items():
    -                os_tag = "unknown"
    -                if isinstance(data, dict):
    -                    ts = data.get("tags")
    -                    if isinstance(ts, dict): os_tag = ts.get("os", "unknown")
    -                res[name] = {"os": os_tag}
    -            return res
    -        return {"count": len(matched_names), "nodes": matched_names, "note": "Use 'get_node_info' for details."}
    -    except Exception as e: 
    -        return f"Error listing nodes: {str(e)}"
    -
    -

    List nodes matching the filter pattern. Returns metadata for <=5 nodes, names only for more.

    -
    -
    -def list_sessions(self, limit=20) -
    -
    -
    - -Expand source code - -
    def list_sessions(self, limit=20):
    -    """Prints a list of sessions using printer.table."""
    -    sessions = self._get_sessions()
    -    if not sessions:
    -        printer.info("No saved AI sessions found.")
    -        return
    -    
    -    total = len(sessions)
    -    if limit and total > limit:
    -        sessions = sessions[:limit]
    -        
    -    columns = ["ID", "Title", "Created At", "Model"]
    -    rows = [[s["id"], s["title"], s["created_at"], s["model"]] for s in sessions]
    -    
    -    title = "AI Persisted Sessions"
    -    if limit and total > limit:
    -        title += f" (Showing last {limit} of {total})"
    -        
    -    printer.table(title, columns, rows)
    -    if limit and total > limit:
    -        printer.info(f"Use '--list --all' (if supported) or check the sessions directory to see all {total} sessions.")
    -
    -

    Prints a list of sessions using printer.table.

    -
    -
    -def load_session_data(self, session_id) -
    -
    -
    - -Expand source code - -
    def load_session_data(self, session_id):
    -    """Loads a session's raw data by ID."""
    -    path = os.path.join(self.sessions_dir, f"{session_id}.json")
    -    if os.path.exists(path):
    -        try:
    -            with open(path, "r") as f:
    -                data = json.load(f)
    -                self.session_id = session_id
    -                self.session_path = path
    -                return data
    -        except Exception as e:
    -            printer.error(f"Failed to load session {session_id}: {e}")
    -    return None
    -
    -

    Loads a session's raw data by ID.

    -
    -
    -def manage_memory_tool(self, content, action='append') -
    -
    -
    - -Expand source code - -
    def manage_memory_tool(self, content, action="append"):
    -    """Save or update long-term memory. Only use when user explicitly requests it."""
    -    if not content or not content.strip():
    -        return "Error: Cannot save empty content to memory."
    -    
    -    try:
    -        mode = "a" if action == "append" else "w"
    -        os.makedirs(os.path.dirname(self.memory_path), exist_ok=True)
    -        with open(self.memory_path, mode) as f:
    -            timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
    -            f.write(f"\n\n## {timestamp}\n{content.strip()}\n" if action == "append" else content)
    -        
    -        # Reload memory after update
    -        with open(self.memory_path, "r") as f:
    -            self.long_term_memory = f.read()
    -        
    -        return "Memory updated successfully."
    -    except PermissionError as e:
    -        return f"Error: Permission denied writing to memory file: {e}"
    -    except Exception as e:
    -        return f"Error updating memory: {str(e)}"
    -
    -

    Save or update long-term memory. Only use when user explicitly requests it.

    -
    -
    -def register_ai_tool(self,
    tool_definition,
    handler,
    target='engineer',
    engineer_prompt=None,
    architect_prompt=None,
    status_formatter=None)
    -
    -
    -
    - -Expand source code - -
    def register_ai_tool(self, tool_definition, handler, target="engineer", engineer_prompt=None, architect_prompt=None, status_formatter=None):
    -    """Register an external tool for the AI system.
    -
    -    Args:
    -        tool_definition (dict): OpenAI-compatible tool definition.
    -        handler (callable): Function(ai_instance, **tool_args) -> str.
    -        target (str): 'engineer', 'architect', or 'both'.
    -        engineer_prompt (str): Extra text for engineer system prompt.
    -        architect_prompt (str): Extra text for architect system prompt.
    -        status_formatter (callable): Function(args_dict) -> status string.
    -    """
    -    name = tool_definition["function"]["name"]
    -    
    -    # Check if already registered to prevent duplicates
    -    if target in ("engineer", "both"):
    -        if not any(t["function"]["name"] == name for t in self.external_engineer_tools):
    -            self.external_engineer_tools.append(tool_definition)
    -    if target in ("architect", "both"):
    -        if not any(t["function"]["name"] == name for t in self.external_architect_tools):
    -            self.external_architect_tools.append(tool_definition)
    -    
    -    self.external_tool_handlers[name] = handler
    -    
    -    if engineer_prompt and engineer_prompt not in self.engineer_prompt_extensions:
    -        self.engineer_prompt_extensions.append(engineer_prompt)
    -    if architect_prompt and architect_prompt not in self.architect_prompt_extensions:
    -        self.architect_prompt_extensions.append(architect_prompt)
    -    if status_formatter:
    -        self.tool_status_formatters[name] = status_formatter
    -
    -

    Register an external tool for the AI system.

    -

    Args

    -
    -
    tool_definition : dict
    -
    OpenAI-compatible tool definition.
    -
    handler : callable
    -
    Function(ai_instance, **tool_args) -> str.
    -
    target : str
    -
    'engineer', 'architect', or 'both'.
    -
    engineer_prompt : str
    -
    Extra text for engineer system prompt.
    -
    architect_prompt : str
    -
    Extra text for architect system prompt.
    -
    status_formatter : callable
    -
    Function(args_dict) -> status string.
    -
    -
    -
    -def run_commands_tool(self, nodes_filter, commands, status=None) -
    -
    -
    - -Expand source code - -
    def run_commands_tool(self, nodes_filter, commands, status=None):
    -    """Execute commands on nodes matching the filter. Native interactive confirmation for unsafe commands."""
    -    # Handle if commands is a JSON string
    -    if isinstance(commands, str):
    -        try:
    -            commands = json.loads(commands)
    -        except ValueError:
    -            commands = [c.strip() for c in commands.split('\n') if c.strip()]
    -    
    -    # Expand multi-line commands within a list (in case the AI packs them)
    -    if isinstance(commands, list):
    -        expanded_commands = []
    -        for cmd in commands:
    -            expanded_commands.extend([c.strip() for c in str(cmd).split('\n') if c.strip()])
    -        commands = expanded_commands
    -    else:
    -        commands = [str(commands)]
    -    
    -    # Check command safety natively
    -    if not self.trusted_session:
    -        unsafe_commands = [cmd for cmd in commands if not self._is_safe_command(cmd)]
    -        if unsafe_commands:
    -            # Stop the spinner so prompt doesn't get messed up
    -            if status: status.stop()
    -            
    -            # Show ALL commands with unsafe ones highlighted
    -            formatted_cmds = []
    -            for cmd in commands:
    -                if cmd in unsafe_commands:
    -                    formatted_cmds.append(f"  • [warning]{cmd}[/warning]")
    -                else:
    -                    formatted_cmds.append(f"  • {cmd}")
    -            
    -            panel_content = f"Target: {nodes_filter}\nCommands:\n" + "\n".join(formatted_cmds)
    -            # Use print_important if available (for remote bridges) fallback to standard print
    -            print_fn = getattr(self.console, "print_important", self.console.print)
    -            print_fn(Panel(panel_content, title="[bold warning]⚠️ UNSAFE COMMANDS DETECTED[/bold warning]", border_style="warning"))
    -            
    -            try:
    -                user_resp = self.confirm_handler("[bold warning]Execute? (y: yes / n: no / a: allow all this session / <text>: feedback)[/bold warning]", default="n")
    -            except KeyboardInterrupt:
    -                if status: status.update("[ai_status]Engineer: Resuming...")
    -                self.console.print("[fail]✗ Aborted by user (Ctrl+C).[/fail]")
    -                raise
    -            
    -            # Resume the spinner
    -            if status: status.update("[ai_status]Engineer: Processing user response...")
    -            
    -            user_resp_lower = user_resp.strip().lower()
    -            if user_resp_lower in ['a', 'allow']:
    -                self.trusted_session = True
    -                self.console.print("[pass]✓ Trust Mode Enabled. All future commands in this session will execute without confirmation.[/pass]")
    -            elif user_resp_lower in ['y', 'yes']:
    -                self.console.print("[pass]✓ Executing...[/pass]")
    -            elif user_resp_lower in ['n', 'no', '', 'cancel']:
    -                self.console.print("[fail]✗ Execution rejected by user.[/fail]")
    -                return "Error: User rejected execution."
    -            else:
    -                self.console.print(f"[user_prompt]User feedback: [/user_prompt]{user_resp}")
    -                return f"User requested changes: {user_resp}. Please adjust the commands based on this feedback and try again."
    -    
    -    try:
    -        matched_names = self.config._getallnodes(nodes_filter)
    -        if not matched_names: return "No nodes found matching filter."
    -        thisnodes_dict = self.config.getitems(matched_names, extract=True)
    -        result = nodes(thisnodes_dict, config=self.config).run(commands)
    -        return result
    -    except Exception as e: 
    -        return f"Error executing commands: {str(e)}"
    -
    -

    Execute commands on nodes matching the filter. Native interactive confirmation for unsafe commands.

    -
    -
    -def save_session(self, history, title=None, model=None) -
    -
    -
    - -Expand source code - -
    def save_session(self, history, title=None, model=None):
    -    """Saves current history to the session file."""
    -    if not self.session_id:
    -        # Generate ID from first user query if available
    -        first_user_msg = next((m["content"] for m in history if m["role"] == "user"), "new-session")
    -        self.session_id = self._generate_session_id(first_user_msg)
    -        self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json")
    -    elif not self.session_path:
    -        self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json")
    -
    -    # If it's a new file, we might want to set a better title
    -    if not os.path.exists(self.session_path) and not title:
    -        raw_title = next((m["content"] for m in history if m["role"] == "user"), "New Session")
    -        # Clean title: remove newlines, multiple spaces
    -        clean_title = " ".join(raw_title.split())
    -        if len(clean_title) > 40:
    -            title = clean_title[:37].strip() + "..."
    -        else:
    -            title = clean_title
    -
    -    try:
    -        # Read existing metadata if it exists
    -        metadata = {}
    -        if os.path.exists(self.session_path):
    -            with open(self.session_path, "r") as f:
    -                metadata = json.load(f)
    -        
    -        metadata.update({
    -            "id": self.session_id,
    -            "title": title or metadata.get("title", "New Session"),
    -            "created_at": metadata.get("created_at", datetime.datetime.now().isoformat()),
    -            "updated_at": datetime.datetime.now().isoformat(),
    -            "model": model or metadata.get("model", self.engineer_model),
    -            "history": history
    -        })
    -
    -        with open(self.session_path, "w") as f:
    -            json.dump(metadata, f, indent=4)
    -    except Exception as e:
    -        printer.error(f"Failed to save session: {e}")
    -
    -    except Exception as e:
    -        printer.error(f"Failed to save session: {e}")
    -
    -

    Saves current history to the session file.

    -
    -
    -
    class configfile (conf=None, key=None, shared_config=None) @@ -4510,7 +1939,7 @@ class node: self.child.setwinsize(int(size.group(2)),int(size.group(1))) except OSError: pass - if logger: + if logger and self.protocol != "local": port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else "" logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}") @@ -4544,6 +1973,34 @@ class node: with open(self.logfile, "w") as f: f.write(self._logclean(self.mylog.getvalue().decode(), True)) + def _is_child_connpy_active(self, child_fd: int) -> bool: + if self.protocol != "local": + return False + try: + fg_pgid = os.tcgetpgrp(child_fd) + if fg_pgid <= 0: + return False + cmdline_path = f"/proc/{fg_pgid}/cmdline" + if os.path.exists(cmdline_path): + with open(cmdline_path, "rb") as f: + raw_args = f.read().split(b"\x00") + cmdline_str = " ".join([arg.decode(errors="ignore") for arg in raw_args if arg]) + + is_active = False + for raw_arg in raw_args: + arg_str = raw_arg.decode(errors="ignore") + if not arg_str: + continue + base_name = os.path.basename(arg_str) + if base_name in ["conn", "connpy", "connapp"] or "connpy" in arg_str or "connapp" in arg_str: + is_active = True + break + + return is_active + except Exception: + pass + return False + async def _async_interact_loop(self, local_stream, resize_callback, copilot_handler=None): local_stream.setup(resize_callback=resize_callback) self.current_local_stream = local_stream @@ -4608,6 +2065,14 @@ class node: # Copilot interception if copilot_handler and b'\x00' in data: + if self._is_child_connpy_active(child_fd): + try: + os.write(child_fd, data) + except OSError: + break + self.lastinput = time() + continue + # Build node info from available metadata and ensure values are strings (not bytes) def to_str(val): if isinstance(val, bytes): @@ -4715,12 +2180,39 @@ class node: except Exception: pass + async def pwd_tracker_task(): + import socket + hostname = socket.gethostname() + last_cwd = None + while True: + await asyncio.sleep(0.3) + try: + child_pid = getattr(self.child, 'pid', None) + if child_pid: + new_cwd = os.readlink(f"/proc/{child_pid}/cwd") + if new_cwd != last_cwd: + last_cwd = new_cwd + try: + os.chdir(new_cwd) + except Exception: + pass + try: + await local_stream.write(f"\033]7;file://{hostname}{new_cwd}\007".encode()) + except Exception: + pass + if isinstance(self.tags, dict): + self.tags["cwd"] = new_cwd + except Exception: + pass + try: # We wait for either the user (ingress) or the child (egress) to finish tasks = [ asyncio.create_task(ingress_task()), asyncio.create_task(egress_task()) ] + if self.protocol == "local": + tasks.append(asyncio.create_task(pwd_tracker_task())) if self.idletime > 0: tasks.append(asyncio.create_task(keepalive_task())) if hasattr(self, 'logfile') and hasattr(self, 'mylog'): @@ -4848,13 +2340,14 @@ class node: def _copilot_handler(self, config): """Unified copilot handler for local session.""" - from .cli.terminal_ui import CopilotInterface - from .services.ai_service import AIService import asyncio import os async def handler(buffer, node_info, stream, child_fd, cmd_byte_positions=None): try: + from .cli.terminal_ui import CopilotInterface + from .services.ai_service import AIService + interface = CopilotInterface( config, history=getattr(stream, 'copilot_history', None), @@ -5241,12 +2734,23 @@ class node: return self._generate_docker_cmd() elif self.protocol == "ssm": return self._generate_ssm_cmd() + elif self.protocol == "local": + return self.host else: printer.error(f"Invalid protocol: {self.protocol}") sys.exit(1) @MethodHook def _connect(self, debug=False, timeout=10, max_attempts=3, logger=None): + if self.protocol == "local": + cmd = self._get_cmd() + args = shlex.split(cmd) + self.child = pexpect.spawn(args[0], args[1:], env=os.environ.copy()) + from pexpect import fdpexpect + self.raw_child = fdpexpect.fdspawn(self.child.child_fd) + if self.logs != '': + self.logfile = self._logfile() + return True cmd = self._get_cmd() passwords = self._passtx(self.password) if self.password and any(self.password) else [] @@ -6518,11 +4022,12 @@ def test(self, commands, expected, vars = None,*, folder = None, prompt = None,
    @@ -4105,6 +5807,24 @@ el.replaceWith(d);
  • +

    SyncService

    + +
  • +
  • SystemService

  • +
  • +

    UserService

    + +
  • diff --git a/docs/connpy/services/plugin_service.html b/docs/connpy/services/plugin_service.html index 2c9385a..5d72aa8 100644 --- a/docs/connpy/services/plugin_service.html +++ b/docs/connpy/services/plugin_service.html @@ -322,13 +322,13 @@ el.replaceWith(d); is_mock = True def __init__(self, config): from ..core import node, nodes - from ..ai import ai + from ..connapp import DeferredAIProxy from ..services.provider import ServiceProvider self.config = config self.node = node self.nodes = nodes - self.ai = ai + self.ai = DeferredAIProxy() self.services = ServiceProvider(config, mode="local") @@ -645,13 +645,13 @@ el.replaceWith(d); is_mock = True def __init__(self, config): from ..core import node, nodes - from ..ai import ai + from ..connapp import DeferredAIProxy from ..services.provider import ServiceProvider self.config = config self.node = node self.nodes = nodes - self.ai = ai + self.ai = DeferredAIProxy() self.services = ServiceProvider(config, mode="local") diff --git a/docs/connpy/services/provider.html b/docs/connpy/services/provider.html index f51bb13..da74f04 100644 --- a/docs/connpy/services/provider.html +++ b/docs/connpy/services/provider.html @@ -79,6 +79,12 @@ el.replaceWith(d); self.mode = mode self.config = config self.remote_host = remote_host + self._system = None + self._execution = None + self._import_export = None + self._sync = None + self._users = None + self._ai = None if mode == "local": self._init_local() @@ -92,35 +98,20 @@ el.replaceWith(d); from .profile_service import ProfileService from .config_service import ConfigService from .plugin_service import PluginService - from .ai_service import AIService - from .system_service import SystemService - from .execution_service import ExecutionService - from .import_export_service import ImportExportService from .context_service import ContextService - from .sync_service import SyncService - from .user_service import UserService self.nodes = NodeService(self.config) self.profiles = ProfileService(self.config) self.config_svc = ConfigService(self.config) self.plugins = PluginService(self.config) - self.ai = AIService(self.config) - self.system = SystemService(self.config) - self.execution = ExecutionService(self.config) - self.import_export = ImportExportService(self.config) self.context = ContextService(self.config) - self.sync = SyncService(self.config) - self.users = UserService(self.config.defaultdir) def _init_remote(self): # Allow ConfigService to work locally so the user can revert the mode from .config_service import ConfigService from .context_service import ContextService - from .sync_service import SyncService self.config_svc = ConfigService(self.config) self.context = ContextService(self.config) - self.sync = SyncService(self.config) - self.users = None if not self.remote_host: raise InvalidConfigurationError("Remote host must be specified in remote mode") @@ -134,6 +125,9 @@ el.replaceWith(d); ) def get_token(): + env_token = os.environ.get("CONNPY_TOKEN") + if env_token: + return env_token token_path = os.path.join(self.config.defaultdir, ".token") if os.path.exists(token_path): try: @@ -159,9 +153,168 @@ el.replaceWith(d); self.system = SystemStub(channel, remote_host=self.remote_host) self.execution = ExecutionStub(channel, remote_host=self.remote_host) self.import_export = ImportExportStub(channel, remote_host=self.remote_host) - self.auth = AuthStub(channel, remote_host=self.remote_host)
    + self.auth = AuthStub(channel, remote_host=self.remote_host) + + @property + def system(self): + if self._system is None and self.mode == "local": + from .system_service import SystemService + self._system = SystemService(self.config) + return self._system + + @system.setter + def system(self, value): + self._system = value + + @property + def execution(self): + if self._execution is None and self.mode == "local": + from .execution_service import ExecutionService + self._execution = ExecutionService(self.config) + return self._execution + + @execution.setter + def execution(self, value): + self._execution = value + + @property + def import_export(self): + if self._import_export is None and self.mode == "local": + from .import_export_service import ImportExportService + self._import_export = ImportExportService(self.config) + return self._import_export + + @import_export.setter + def import_export(self, value): + self._import_export = value + + @property + def sync(self): + if self._sync is None: + from .sync_service import SyncService + self._sync = SyncService(self.config) + return self._sync + + @sync.setter + def sync(self, value): + self._sync = value + + @property + def users(self): + if self._users is None and self.mode == "local": + from .user_service import UserService + self._users = UserService(self.config.defaultdir) + return self._users + + @users.setter + def users(self, value): + self._users = value + + @property + def ai(self): + if self._ai is None and self.mode == "local": + from .ai_service import AIService + self._ai = AIService(self.config) + return self._ai + + @ai.setter + def ai(self, value): + self._ai = value

    Dynamic service backend. Transparently provides local or remote services.

    +

    Instance variables

    +
    +
    prop ai
    +
    +
    + +Expand source code + +
    @property
    +def ai(self):
    +    if self._ai is None and self.mode == "local":
    +        from .ai_service import AIService
    +        self._ai = AIService(self.config)
    +    return self._ai
    +
    +
    +
    +
    prop execution
    +
    +
    + +Expand source code + +
    @property
    +def execution(self):
    +    if self._execution is None and self.mode == "local":
    +        from .execution_service import ExecutionService
    +        self._execution = ExecutionService(self.config)
    +    return self._execution
    +
    +
    +
    +
    prop import_export
    +
    +
    + +Expand source code + +
    @property
    +def import_export(self):
    +    if self._import_export is None and self.mode == "local":
    +        from .import_export_service import ImportExportService
    +        self._import_export = ImportExportService(self.config)
    +    return self._import_export
    +
    +
    +
    +
    prop sync
    +
    +
    + +Expand source code + +
    @property
    +def sync(self):
    +    if self._sync is None:
    +        from .sync_service import SyncService
    +        self._sync = SyncService(self.config)
    +    return self._sync
    +
    +
    +
    +
    prop system
    +
    +
    + +Expand source code + +
    @property
    +def system(self):
    +    if self._system is None and self.mode == "local":
    +        from .system_service import SystemService
    +        self._system = SystemService(self.config)
    +    return self._system
    +
    +
    +
    +
    prop users
    +
    +
    + +Expand source code + +
    @property
    +def users(self):
    +    if self._users is None and self.mode == "local":
    +        from .user_service import UserService
    +        self._users = UserService(self.config.defaultdir)
    +    return self._users
    +
    +
    +
    +
    @@ -183,6 +336,14 @@ el.replaceWith(d);
  • ServiceProvider

    +
  • diff --git a/docs/connpy/services/sync_service.html b/docs/connpy/services/sync_service.html index aac676f..45f8091 100644 --- a/docs/connpy/services/sync_service.html +++ b/docs/connpy/services/sync_service.html @@ -82,6 +82,7 @@ el.replaceWith(d); def login(self): """Authenticate with Google Drive.""" + Credentials, Request, _, RefreshError, InstalledAppFlow, _, _, _ = _get_google_libs() creds = None if os.path.exists(self.token_file): creds = Credentials.from_authorized_user_file(self.token_file, self.scopes) @@ -119,6 +120,7 @@ el.replaceWith(d); def get_credentials(self): """Get valid credentials, refreshing if necessary.""" + Credentials, Request, _, RefreshError, _, _, _, _ = _get_google_libs() if os.path.exists(self.token_file): creds = Credentials.from_authorized_user_file(self.token_file, self.scopes) else: @@ -136,6 +138,7 @@ el.replaceWith(d); def check_login_status(self): """Check if logged in to Google Drive.""" + Credentials, Request, _, RefreshError, _, _, _, _ = _get_google_libs() if os.path.exists(self.token_file): creds = Credentials.from_authorized_user_file(self.token_file) if creds and creds.expired and creds.refresh_token: @@ -148,6 +151,7 @@ el.replaceWith(d); def list_backups(self): """List files in Google Drive appDataFolder.""" + _, _, build, _, _, _, _, HttpError = _get_google_libs() creds = self.get_credentials() if not creds: printer.error("Not logged in to Google Drive.") @@ -206,6 +210,7 @@ el.replaceWith(d); def upload_file(self, file_path, timestamp): """Internal method to upload to Drive.""" + _, _, build, _, _, MediaFileUpload, _, _ = _get_google_libs() creds = self.get_credentials() if not creds: return False @@ -231,6 +236,7 @@ el.replaceWith(d); def delete_backup(self, file_id): """Delete a backup from Drive.""" + _, _, build, _, _, _, _, _ = _get_google_libs() creds = self.get_credentials() if not creds: return False try: @@ -264,6 +270,7 @@ el.replaceWith(d); def download_file(self, file_id, dest): """Internal method to download from Drive.""" + _, _, build, _, _, _, MediaIoBaseDownload, _ = _get_google_libs() creds = self.get_credentials() if not creds: return False try: @@ -508,6 +515,7 @@ el.replaceWith(d);
    def check_login_status(self):
         """Check if logged in to Google Drive."""
    +    Credentials, Request, _, RefreshError, _, _, _, _ = _get_google_libs()
         if os.path.exists(self.token_file):
             creds = Credentials.from_authorized_user_file(self.token_file)
             if creds and creds.expired and creds.refresh_token:
    @@ -570,6 +578,7 @@ el.replaceWith(d);
     
     
    def delete_backup(self, file_id):
         """Delete a backup from Drive."""
    +    _, _, build, _, _, _, _, _ = _get_google_libs()
         creds = self.get_credentials()
         if not creds: return False
         try:
    @@ -592,6 +601,7 @@ el.replaceWith(d);
     
     
    def download_file(self, file_id, dest):
         """Internal method to download from Drive."""
    +    _, _, build, _, _, _, MediaIoBaseDownload, _ = _get_google_libs()
         creds = self.get_credentials()
         if not creds: return False
         try:
    @@ -619,6 +629,7 @@ el.replaceWith(d);
     
     
    def get_credentials(self):
         """Get valid credentials, refreshing if necessary."""
    +    Credentials, Request, _, RefreshError, _, _, _, _ = _get_google_libs()
         if os.path.exists(self.token_file):
             creds = Credentials.from_authorized_user_file(self.token_file, self.scopes)
         else:
    @@ -646,6 +657,7 @@ el.replaceWith(d);
     
     
    def list_backups(self):
         """List files in Google Drive appDataFolder."""
    +    _, _, build, _, _, _, _, HttpError = _get_google_libs()
         creds = self.get_credentials()
         if not creds:
             printer.error("Not logged in to Google Drive.")
    @@ -684,6 +696,7 @@ el.replaceWith(d);
     
     
    def login(self):
         """Authenticate with Google Drive."""
    +    Credentials, Request, _, RefreshError, InstalledAppFlow, _, _, _ = _get_google_libs()
         creds = None
         if os.path.exists(self.token_file):
             creds = Credentials.from_authorized_user_file(self.token_file, self.scopes)
    @@ -890,6 +903,7 @@ el.replaceWith(d);
     
     
    def upload_file(self, file_path, timestamp):
         """Internal method to upload to Drive."""
    +    _, _, build, _, _, MediaFileUpload, _, _ = _get_google_libs()
         creds = self.get_credentials()
         if not creds: return False
         
    diff --git a/docs/connpy/services/user_service.html b/docs/connpy/services/user_service.html
    index e9fe784..8dbb283 100644
    --- a/docs/connpy/services/user_service.html
    +++ b/docs/connpy/services/user_service.html
    @@ -63,6 +63,9 @@ el.replaceWith(d);
             
             # Ensure users directory exists
             os.makedirs(self.users_dir, exist_ok=True)
    +        
    +        # Reverse index cache: token_hash -> (username, token_id)
    +        self._token_index: dict[str, tuple[str, str]] = {}
     
         def _load_registry(self) -> dict:
             """Loads registry from file. If it doesn't exist, initializes it with a new JWT secret."""
    @@ -107,6 +110,16 @@ el.replaceWith(d);
                         pass
                 raise e
     
    +    def _build_token_index(self, registry: dict) -> dict[str, tuple[str, str]]:
    +        """Builds a reverse index of token_hash -> (username, token_id) for O(1) PAT lookup."""
    +        index = {}
    +        for username, user_data in registry.get("users", {}).items():
    +            for token_id, token_meta in user_data.get("api_tokens", {}).items():
    +                token_hash = token_meta.get("token_hash")
    +                if token_hash:
    +                    index[token_hash] = (username, token_id)
    +        return index
    +
         def create_user(self, username, password, config_path=None) -> dict:
             """Creates a new user with bcrypt-hashed credentials.
             
    @@ -282,7 +295,129 @@ el.replaceWith(d);
                 payload = jwt.decode(token, secret, algorithms=["HS256"])
                 return payload.get("sub")
             except (jwt.ExpiredSignatureError, jwt.InvalidTokenError, KeyError):
    -            return None
    + return None + + # --- Personal Access Token (PAT) Management --- + + def create_api_token(self, username: str, name: str, expires_in_days: int | None = None) -> dict: + """Creates a Personal Access Token for the user. + + Returns the raw token ONCE. Only the SHA-256 hash is persisted. + """ + if not name or not isinstance(name, str): + raise ValueError("Token name cannot be empty") + + registry = self._load_registry() + if username not in registry["users"]: + raise ValueError(f"User '{username}' not found") + + user_data = registry["users"][username] + if "api_tokens" not in user_data: + user_data["api_tokens"] = {} + + # Generate cryptographically secure token with recognizable prefix + raw_secret = secrets.token_hex(32) + raw_token = f"cnp_pat_{raw_secret}" + token_hash = hashlib.sha256(raw_token.encode("utf-8")).hexdigest() + token_id = f"tok_{secrets.token_hex(4)}" + + now = datetime.datetime.now(datetime.timezone.utc) + expires_at = None + if expires_in_days and expires_in_days > 0: + expires_at = (now + datetime.timedelta(days=expires_in_days)).isoformat() + + user_data["api_tokens"][token_id] = { + "name": name, + "token_hash": token_hash, + "token_prefix": raw_token[:16], + "created_at": now.isoformat(), + "last_used_at": None, + "expires_at": expires_at, + } + + self._save_registry(registry) + self._token_index = self._build_token_index(registry) + + return { + "token_id": token_id, + "raw_token": raw_token, + "name": name, + } + + def list_api_tokens(self, username: str) -> list[dict]: + """Lists all active API tokens for a user (without sensitive data).""" + registry = self._load_registry() + if username not in registry["users"]: + raise ValueError(f"User '{username}' not found") + + tokens = registry["users"][username].get("api_tokens", {}) + return [ + { + "token_id": tid, + "name": meta.get("name"), + "token_prefix": meta.get("token_prefix"), + "created_at": meta.get("created_at"), + "last_used_at": meta.get("last_used_at"), + "expires_at": meta.get("expires_at"), + } + for tid, meta in tokens.items() + ] + + def revoke_api_token(self, username: str, token_id: str) -> bool: + """Revokes (deletes) a specific API token. Returns True if found and removed.""" + registry = self._load_registry() + if username not in registry["users"]: + raise ValueError(f"User '{username}' not found") + + tokens = registry["users"][username].get("api_tokens", {}) + if token_id not in tokens: + return False + + del tokens[token_id] + self._save_registry(registry) + self._token_index = self._build_token_index(registry) + return True + + def verify_api_token(self, raw_token: str) -> str | None: + """Validates a PAT by hashing it and looking up the reverse index. + + Returns username if valid and not expired, None otherwise. + """ + token_hash = hashlib.sha256(raw_token.encode("utf-8")).hexdigest() + + # Rebuild index if empty (cold start or after process restart) + if not self._token_index: + registry = self._load_registry() + self._token_index = self._build_token_index(registry) + + match = self._token_index.get(token_hash) + if not match: + return None + + username, token_id = match + + # Validate token still exists and check expiration + registry = self._load_registry() + user_data = registry.get("users", {}).get(username, {}) + token_meta = user_data.get("api_tokens", {}).get(token_id) + + if not token_meta: + # Token was revoked between index build and now + self._token_index = self._build_token_index(registry) + return None + + # Check expiration + expires_at = token_meta.get("expires_at") + if expires_at: + exp_dt = datetime.datetime.fromisoformat(expires_at) + if datetime.datetime.now(datetime.timezone.utc) > exp_dt: + return None + + # Update last_used_at + token_meta["last_used_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat() + self._save_registry(registry) + + return username

    Methods

    @@ -356,6 +491,62 @@ el.replaceWith(d);

    Verifies old password and updates registry with new hashed password.

    +
    +def create_api_token(self, username: str, name: str, expires_in_days: int | None = None) ‑> dict +
    +
    +
    + +Expand source code + +
    def create_api_token(self, username: str, name: str, expires_in_days: int | None = None) -> dict:
    +    """Creates a Personal Access Token for the user.
    +    
    +    Returns the raw token ONCE. Only the SHA-256 hash is persisted.
    +    """
    +    if not name or not isinstance(name, str):
    +        raise ValueError("Token name cannot be empty")
    +    
    +    registry = self._load_registry()
    +    if username not in registry["users"]:
    +        raise ValueError(f"User '{username}' not found")
    +    
    +    user_data = registry["users"][username]
    +    if "api_tokens" not in user_data:
    +        user_data["api_tokens"] = {}
    +    
    +    # Generate cryptographically secure token with recognizable prefix
    +    raw_secret = secrets.token_hex(32)
    +    raw_token = f"cnp_pat_{raw_secret}"
    +    token_hash = hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
    +    token_id = f"tok_{secrets.token_hex(4)}"
    +    
    +    now = datetime.datetime.now(datetime.timezone.utc)
    +    expires_at = None
    +    if expires_in_days and expires_in_days > 0:
    +        expires_at = (now + datetime.timedelta(days=expires_in_days)).isoformat()
    +    
    +    user_data["api_tokens"][token_id] = {
    +        "name": name,
    +        "token_hash": token_hash,
    +        "token_prefix": raw_token[:16],
    +        "created_at": now.isoformat(),
    +        "last_used_at": None,
    +        "expires_at": expires_at,
    +    }
    +    
    +    self._save_registry(registry)
    +    self._token_index = self._build_token_index(registry)
    +    
    +    return {
    +        "token_id": token_id,
    +        "raw_token": raw_token,
    +        "name": name,
    +    }
    +
    +

    Creates a Personal Access Token for the user.

    +

    Returns the raw token ONCE. Only the SHA-256 hash is persisted.

    +
    def create_user(self, username, password, config_path=None) ‑> dict
    @@ -514,6 +705,35 @@ Mode B: config_path set -> Reuses existing directory after validating its str

    Retrieves raw metadata for a specific user.

    +
    +def list_api_tokens(self, username: str) ‑> list[dict] +
    +
    +
    + +Expand source code + +
    def list_api_tokens(self, username: str) -> list[dict]:
    +    """Lists all active API tokens for a user (without sensitive data)."""
    +    registry = self._load_registry()
    +    if username not in registry["users"]:
    +        raise ValueError(f"User '{username}' not found")
    +    
    +    tokens = registry["users"][username].get("api_tokens", {})
    +    return [
    +        {
    +            "token_id": tid,
    +            "name": meta.get("name"),
    +            "token_prefix": meta.get("token_prefix"),
    +            "created_at": meta.get("created_at"),
    +            "last_used_at": meta.get("last_used_at"),
    +            "expires_at": meta.get("expires_at"),
    +        }
    +        for tid, meta in tokens.items()
    +    ]
    +
    +

    Lists all active API tokens for a user (without sensitive data).

    +
    def list_users(self) ‑> list[dict]
    @@ -536,6 +756,83 @@ Mode B: config_path set -> Reuses existing directory after validating its str

    Lists all registered users with metadata.

    +
    +def revoke_api_token(self, username: str, token_id: str) ‑> bool +
    +
    +
    + +Expand source code + +
    def revoke_api_token(self, username: str, token_id: str) -> bool:
    +    """Revokes (deletes) a specific API token. Returns True if found and removed."""
    +    registry = self._load_registry()
    +    if username not in registry["users"]:
    +        raise ValueError(f"User '{username}' not found")
    +    
    +    tokens = registry["users"][username].get("api_tokens", {})
    +    if token_id not in tokens:
    +        return False
    +    
    +    del tokens[token_id]
    +    self._save_registry(registry)
    +    self._token_index = self._build_token_index(registry)
    +    return True
    +
    +

    Revokes (deletes) a specific API token. Returns True if found and removed.

    +
    +
    +def verify_api_token(self, raw_token: str) ‑> str | None +
    +
    +
    + +Expand source code + +
    def verify_api_token(self, raw_token: str) -> str | None:
    +    """Validates a PAT by hashing it and looking up the reverse index.
    +    
    +    Returns username if valid and not expired, None otherwise.
    +    """
    +    token_hash = hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
    +    
    +    # Rebuild index if empty (cold start or after process restart)
    +    if not self._token_index:
    +        registry = self._load_registry()
    +        self._token_index = self._build_token_index(registry)
    +    
    +    match = self._token_index.get(token_hash)
    +    if not match:
    +        return None
    +    
    +    username, token_id = match
    +    
    +    # Validate token still exists and check expiration
    +    registry = self._load_registry()
    +    user_data = registry.get("users", {}).get(username, {})
    +    token_meta = user_data.get("api_tokens", {}).get(token_id)
    +    
    +    if not token_meta:
    +        # Token was revoked between index build and now
    +        self._token_index = self._build_token_index(registry)
    +        return None
    +    
    +    # Check expiration
    +    expires_at = token_meta.get("expires_at")
    +    if expires_at:
    +        exp_dt = datetime.datetime.fromisoformat(expires_at)
    +        if datetime.datetime.now(datetime.timezone.utc) > exp_dt:
    +            return None
    +    
    +    # Update last_used_at
    +    token_meta["last_used_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
    +    self._save_registry(registry)
    +    
    +    return username
    +
    +

    Validates a PAT by hashing it and looking up the reverse index.

    +

    Returns username if valid and not expired, None otherwise.

    +
    def verify_jwt(self, token) ‑> str | None
    @@ -579,11 +876,15 @@ Mode B: config_path set -> Reuses existing directory after validating its str
  • admin_change_password
  • authenticate
  • change_password
  • +
  • create_api_token
  • create_user
  • delete_user
  • generate_jwt
  • get_user
  • +
  • list_api_tokens
  • list_users
  • +
  • revoke_api_token
  • +
  • verify_api_token
  • verify_jwt
  • diff --git a/docs/connpy/tunnels.html b/docs/connpy/tunnels.html index 8c1df81..0787e86 100644 --- a/docs/connpy/tunnels.html +++ b/docs/connpy/tunnels.html @@ -376,6 +376,8 @@ Handles terminal raw mode, async I/O, and SIGWINCH signals.

    }) if getattr(req, "copilot_action", ""): copilot_msg["action"] = req.copilot_action + if getattr(req, "copilot_node_info_json", ""): + copilot_msg["node_info_json"] = req.copilot_node_info_json if copilot_msg: self._loop.call_soon_threadsafe(self.copilot_queue.put_nowait, copilot_msg) @@ -454,6 +456,8 @@ Bridges the blocking gRPC iterators with the async _async_interact_loop.