diff --git a/README.md b/README.md index fd34852..4d71746 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@
-# Connpy (v6.4.0b3) +# Connpy (v6.4.0b4) [](https://pypi.org/pypi/connpy/) [](https://pypi.org/pypi/connpy/) [](https://pypi.org/pypi/connpy/) diff --git a/connpy/__init__.py b/connpy/__init__.py index 3968d83..840d225 100644 --- a/connpy/__init__.py +++ b/connpy/__init__.py @@ -5,7 +5,7 @@ -# Connpy (v6.4.0b3) +# Connpy (v6.4.0b4) [](https://pypi.org/pypi/connpy/) [](https://pypi.org/pypi/connpy/) [](https://pypi.org/pypi/connpy/) diff --git a/connpy/_version.py b/connpy/_version.py index 45f48a7..410dcb6 100644 --- a/connpy/_version.py +++ b/connpy/_version.py @@ -1 +1 @@ -__version__ = "6.4.0b3" +__version__ = "6.4.0b4" diff --git a/connpy/connapp.py b/connpy/connapp.py index ba4f058..98203b2 100755 --- a/connpy/connapp.py +++ b/connpy/connapp.py @@ -319,7 +319,7 @@ class connapp: aiparser.add_argument("--session", nargs=1, help="Resume a specific AI session by ID") aiparser.add_argument("--resume", action="store_true", help="Resume the most recent AI session") aiparser.add_argument("--delete", "--delete-session", dest="delete_session", nargs=1, help="Delete an AI session by ID") - aiparser.add_argument("--mcp", nargs='*', metavar=('ACTION', 'NAME'), help="Manage MCP servers. Actions: list, add, remove, enable, disable. Leave empty for interactive wizard.") + aiparser.add_argument("--mcp", nargs=argparse.REMAINDER, metavar=('ACTION', 'NAME'), help="Manage MCP servers. Actions: list, add, remove, enable, disable, serve. Leave empty for interactive wizard.") aiparser.set_defaults(func=self._ai.dispatch) #RUNPARSER runparser = subparsers.add_parser("run", help="Run scripts or commands on nodes", description="Run scripts or commands on nodes", formatter_class=RichHelpFormatter) diff --git a/connpy/mcp_server.py b/connpy/mcp_server.py index b78e95d..cbc894e 100644 --- a/connpy/mcp_server.py +++ b/connpy/mcp_server.py @@ -522,7 +522,15 @@ class ConnpyMCPServer: return self.server.run(transport="stdio", **kwargs) if transport == "sse": - return self.server.run(transport="sse", host=host, port=port, **kwargs) + if hasattr(self.server, "settings"): + if hasattr(self.server.settings, "host"): + self.server.settings.host = host + if hasattr(self.server.settings, "port"): + self.server.settings.port = port + try: + return self.server.run(transport="sse", host=host, port=port, **kwargs) + except TypeError: + return self.server.run(transport="sse", **kwargs) msg = f"Unknown transport: {transport}. Supported transports: 'stdio', 'sse'" raise ValueError(msg) diff --git a/docs/connpy/ai.html b/docs/connpy/ai.html index 9f71e5f..5284b0a 100644 --- a/docs/connpy/ai.html +++ b/docs/connpy/ai.html @@ -150,7 +150,7 @@ el.replaceWith(d); import yaml try: # 1. Parse YAML - data = yaml.load(playbook_yaml, Loader=yaml.FullLoader) + data = yaml.safe_load(playbook_yaml) except Exception as e: return {"valid": False, "error": f"YAML Syntax Error: {e}"} @@ -473,7 +473,7 @@ el.replaceWith(d); import yaml try: # 1. Parse YAML - data = yaml.load(playbook_yaml, Loader=yaml.FullLoader) + data = yaml.safe_load(playbook_yaml) except Exception as e: return {"valid": False, "error": f"YAML Syntax Error: {e}"} @@ -638,6 +638,9 @@ class ai: self.session_path = os.path.join(self.sessions_dir, f"{self.session_id}.json") if self.session_id else None # Agnostic base prompts + self._update_base_prompts() + + def _update_base_prompts(self): architect_instructions = "" if self.has_architect: architect_instructions = """ @@ -678,7 +681,7 @@ class ai: - NO WANDERING: Do not speculate. If stuck, report attempts. - SAFETY: When you use 'run_commands' with configuration commands, the system automatically prompts the user for confirmation. Just execute - don't ask permission first. {architect_instructions} - Network Context: {{self.long_term_memory if self.long_term_memory else "Empty."}} + Network Context: {self.long_term_memory if self.long_term_memory else "Empty."} """).strip() self._architect_base_prompt = dedent(f""" @@ -718,6 +721,7 @@ class ai: @property def engineer_system_prompt(self): """Build engineer system prompt with plugin extensions.""" + self._update_base_prompts() if self.engineer_prompt_extensions: extensions = "\n".join(self.engineer_prompt_extensions) return self._engineer_base_prompt + f"\n\nPlugin Capabilities:\n{extensions}" @@ -726,6 +730,7 @@ class ai: @property def architect_system_prompt(self): """Build architect system prompt with plugin extensions.""" + self._update_base_prompts() prompt = self._architect_base_prompt if getattr(self, "one_shot", False): prompt += "\n\nCRITICAL 1-SHOT DIAGNOSTICS DIRECTIVE:\nYou are running in a 1-shot offline diagnostics mode. There is no active conversation loop, and you are NOT conversing with a Network Engineer. You MUST deliver your complete strategic analysis immediately and directly to the user. Do not suggest or attempt to delegate/return control to the engineer." @@ -1065,6 +1070,7 @@ class ai: # Reload memory after update with open(self.memory_path, "r") as f: self.long_term_memory = f.read() + self._update_base_prompts() return "Memory updated successfully." except PermissionError as e: @@ -1300,7 +1306,7 @@ class ai: # Silently fail for LLM tools pass - if self.architect_key: + if self.has_architect: base_tools.extend([ {"type": "function", "function": {"name": "consult_architect", "description": "Ask the Strategic Reasoning Engine for advice on complex design, architecture, or troubleshooting decisions. You remain in control and will present the response to the user. Use this for: configuration planning, design validation, complex troubleshooting.", "parameters": {"type": "object", "properties": {"question": {"type": "string", "description": "Strategic question or decision needed."}, "technical_summary": {"type": "string", "description": "Technical findings and context gathered so far."}}, "required": ["question", "technical_summary"]}}}, {"type": "function", "function": {"name": "escalate_to_architect", "description": "Transfer full control to the Strategic Reasoning Engine. Use ONLY when the user explicitly requests the Architect or when the problem requires strategic oversight beyond consultation. After escalation, the Architect takes over the conversation.", "parameters": {"type": "object", "properties": {"reason": {"type": "string", "description": "Why you're escalating (e.g. 'User requested Architect', 'Complex multi-site design needed')."}, "context": {"type": "string", "description": "Full context and findings to hand over."}}, "required": ["reason", "context"]}}} @@ -1657,14 +1663,17 @@ class ai: if status: update_status("[architect]Engineer consulting Architect...") try: # Consultation only - Engineer stays in control + auth_kwargs = dict(self.architect_auth or {}) + if self.architect_key and "api_key" not in auth_kwargs: + auth_kwargs["api_key"] = self.architect_key claude_resp = completion( model=self.architect_model, messages=[ {"role": "system", "content": self.architect_system_prompt}, {"role": "user", "content": f"The Engineer needs your strategic advice.\n\nTECHNICAL SUMMARY: {args['technical_summary']}\n\nQUESTION: {args['question']}\n\nProvide strategic guidance. The Engineer will continue handling the user."} ], - api_key=self.architect_key, - num_retries=3 + num_retries=3, + **auth_kwargs ) obs = claude_resp.choices[0].message.content if debug: @@ -2101,11 +2110,11 @@ Node: {node_name}"""var SAFE_COMMANDSThe type of the None singleton.
var deferred_class_hooksThe type of the None singleton.
@property
def architect_system_prompt(self):
"""Build architect system prompt with plugin extensions."""
+ self._update_base_prompts()
prompt = self._architect_base_prompt
if getattr(self, "one_shot", False):
prompt += "\n\nCRITICAL 1-SHOT DIAGNOSTICS DIRECTIVE:\nYou are running in a 1-shot offline diagnostics mode. There is no active conversation loop, and you are NOT conversing with a Network Engineer. You MUST deliver your complete strategic analysis immediately and directly to the user. Do not suggest or attempt to delegate/return control to the engineer."
@@ -2138,6 +2148,7 @@ def architect_system_prompt(self):
@property
def engineer_system_prompt(self):
"""Build engineer system prompt with plugin extensions."""
+ self._update_base_prompts()
if self.engineer_prompt_extensions:
extensions = "\n".join(self.engineer_prompt_extensions)
return self._engineer_base_prompt + f"\n\nPlugin Capabilities:\n{extensions}"
@@ -2661,14 +2672,17 @@ def ask(self, user_input, dryrun=False, chat_history=None, status=None, debug=Fa
if status: update_status("[architect]Engineer consulting Architect...")
try:
# Consultation only - Engineer stays in control
+ auth_kwargs = dict(self.architect_auth or {})
+ if self.architect_key and "api_key" not in auth_kwargs:
+ auth_kwargs["api_key"] = self.architect_key
claude_resp = completion(
model=self.architect_model,
messages=[
{"role": "system", "content": self.architect_system_prompt},
{"role": "user", "content": f"The Engineer needs your strategic advice.\n\nTECHNICAL SUMMARY: {args['technical_summary']}\n\nQUESTION: {args['question']}\n\nProvide strategic guidance. The Engineer will continue handling the user."}
],
- api_key=self.architect_key,
- num_retries=3
+ num_retries=3,
+ **auth_kwargs
)
obs = claude_resp.choices[0].message.content
if debug:
@@ -2976,6 +2990,7 @@ def confirm(self, user_input): return True
# Reload memory after update
with open(self.memory_path, "r") as f:
self.long_term_memory = f.read()
+ self._update_base_prompts()
return "Memory updated successfully."
except PermissionError as e:
@@ -3024,8 +3039,9 @@ def confirm(self, user_input): return True
self.tool_status_formatters[name] = status_formatter
Register an external tool for the AI system.
-tool_definition : dicthandler : callableHandle MCP server configuration via CLI tokens or interactive wizard.
-class CopilotInterface
-(config,
history=None,
pt_input=None,
pt_output=None,
rich_file=None,
session_state=None)
-class CopilotInterface:
- def __init__(self, config, history=None, pt_input=None, pt_output=None, rich_file=None, session_state=None):
- from ..services.ai_service import AIService
- self.config = config
- self.history = history or InMemoryHistory()
- self.pt_input = pt_input
- self.pt_output = pt_output
- self.rich_file = rich_file
- self.ai_service = AIService(config)
- self.mode_range, self.mode_single, self.mode_lines = 0, 1, 2
-
- self.session_state = session_state if session_state is not None else {}
- self.session_state.setdefault('persona', 'engineer')
- self.session_state.setdefault('trust_mode', False)
- self.session_state.setdefault('memories', [])
- self.session_state.setdefault('copilot_chat_history', [])
- self.session_state.setdefault('os', None)
- self.session_state.setdefault('prompt', None)
- self.session_state.setdefault('context_mode', self.mode_range)
- self.session_state.setdefault('context_cmd', 1)
- self.session_state.setdefault('context_lines', 50)
- self.session_state.setdefault('last_total_cmds', None)
- self.session_state.setdefault('last_total_lines', None)
-
- if rich_file:
- self.console = Console(theme=connpy_theme, force_terminal=True, file=rich_file)
- else:
- self.console = Console(theme=connpy_theme)
-
- def _sync_session_context(self, state: dict):
- """Persist current context mode, depth, total commands, and total lines into session_state."""
- self.session_state['context_mode'] = state['context_mode']
- self.session_state['context_cmd'] = state['context_cmd']
- self.session_state['context_lines'] = state['context_lines']
- self.session_state['last_total_cmds'] = state['total_cmds']
- self.session_state['last_total_lines'] = state['total_lines']
-
- def _get_theme_color(self, style_name: str, fallback: str = "white") -> str:
- """Extract Hex or ANSI color name from the active rich theme."""
- try:
- style = connpy_theme.styles.get(style_name)
- if style and style.color:
- # If it's a standard color like 'green', Rich might return its hex triplet
- if style.color.is_default: return fallback
- return style.color.triplet.hex if style.color.triplet else style.color.name
- except: pass
- return fallback
-
- async def run_session(self,
- raw_bytes: bytes,
- node_info: dict,
- on_ai_call: Callable,
- cmd_byte_positions: List[tuple] = None,
- blocks: List[tuple] = None):
- """
- Runs the interactive Copilot session.
- on_ai_call: async function(active_buffer, question) -> result_dict
- """
- from rich.rule import Rule
-
- try:
- # Prepare UI state
- buffer = log_cleaner(raw_bytes.decode(errors='replace'))
-
- # Use pre-calculated blocks if provided (remote mode), otherwise calculate locally (local mode)
- if blocks is None:
- last_line = buffer.split('\n')[-1].strip() if buffer.strip() else "(prompt)"
- blocks = self.ai_service.build_context_blocks(raw_bytes, cmd_byte_positions, node_info, last_line=last_line)
-
- total_cmds = len(blocks)
- total_lines = len(buffer.split('\n'))
-
- saved_mode = self.session_state.get('context_mode', self.mode_range)
- saved_cmd = self.session_state.get('context_cmd', 1)
- saved_lines = self.session_state.get('context_lines', min(50, total_lines))
- last_total_cmds = self.session_state.get('last_total_cmds', None)
- last_total_lines = self.session_state.get('last_total_lines', None)
-
- is_range = saved_mode in (self.mode_range, 0, 'RANGE', 'range')
- is_lines = saved_mode in (self.mode_lines, 2, 'LINES', 'lines')
- is_single = saved_mode in (self.mode_single, 1, 'SINGLE', 'single')
-
- if is_range or is_single:
- is_mission = self.session_state.get('mission', {}).get('active', False)
- if last_total_cmds is not None and total_cmds > last_total_cmds and (saved_cmd > 1 or is_mission):
- new_cmds = total_cmds - last_total_cmds
- initial_cmd = saved_cmd + new_cmds
- else:
- initial_cmd = saved_cmd
- initial_lines = saved_lines
- elif is_lines:
- if last_total_lines is not None and total_lines > last_total_lines and saved_lines > 50:
- new_lines = total_lines - last_total_lines
- initial_lines = saved_lines + new_lines
- else:
- initial_lines = saved_lines
- initial_cmd = saved_cmd
- else:
- initial_cmd = saved_cmd
- initial_lines = saved_lines
-
- state = {
- 'context_cmd': min(max(1, initial_cmd), max(1, total_cmds)),
- 'total_cmds': total_cmds,
- 'total_lines': total_lines,
- 'context_lines': min(max(1, initial_lines), max(1, total_lines)),
- 'context_mode': saved_mode,
- 'cancelled': False,
- 'toolbar_msg': '',
- 'msg_expiry': 0
- }
- self.session_state['context_mode'] = saved_mode
- self.session_state['context_cmd'] = max(1, initial_cmd)
- self.session_state['context_lines'] = max(1, initial_lines)
- self.session_state['last_total_cmds'] = total_cmds
- self.session_state['last_total_lines'] = total_lines
-
- # 1. Visual Separation (Only show help banner on initial entry)
- self.console.print("") # Real line break
- self.console.print(Rule(title="[bold cyan] AI TERMINAL COPILOT [/bold cyan]", style="cyan"))
- if not self.session_state.get('banner_shown', False):
- self.console.print(Panel(
- "[dim]Type your question. Enter to send, Escape/Ctrl+C to cancel. Type / for commands.\n"
- "Tab to change context mode. Ctrl+\u2191/\u2193 to adjust context. \u2191\u2193 for question history.[/dim]",
- border_style="cyan"
- ))
- self.session_state['banner_shown'] = True
- self.console.print("") # Small space before the copilot prompt
-
- bindings = KeyBindings()
- @bindings.add('c-up')
- def _(event):
- if state['context_mode'] == self.mode_lines:
- state['context_lines'] = min(state['context_lines'] + 50, state['total_lines'])
- else:
- state['context_cmd'] = min(state['context_cmd'] + 1, state['total_cmds'])
- self._sync_session_context(state)
- event.app.invalidate()
- @bindings.add('c-down')
- def _(event):
- if state['context_mode'] == self.mode_lines:
- state['context_lines'] = max(state['context_lines'] - 50, min(50, state['total_lines']))
- else:
- state['context_cmd'] = max(state['context_cmd'] - 1, 1)
- self._sync_session_context(state)
- event.app.invalidate()
- @bindings.add('tab')
- def _(event):
- buf = event.current_buffer
- # If typing a slash command (no spaces yet), use tab to autocomplete inline
- if buf.text.startswith('/') and ' ' not in buf.text:
- buf.complete_next()
- else:
- state['context_mode'] = (state['context_mode'] + 1) % 3
- self._sync_session_context(state)
- event.app.invalidate()
- @bindings.add('escape', eager=True)
- @bindings.add('c-c')
- def _(event):
- state['cancelled'] = True
- event.app.exit(result='')
-
- # Multiline keybindings: Enter to submit, Ctrl+Enter (c-j) or Alt+Enter to add a newline
- @bindings.add('enter', filter=~has_completions)
- def _(event):
- event.current_buffer.validate_and_handle()
-
- @bindings.add('c-j')
- @bindings.add('escape', 'enter')
- def _(event):
- event.current_buffer.insert_text('\n')
-
- def get_active_buffer():
- if state['context_mode'] == self.mode_lines:
- return '\n'.join(buffer.split('\n')[-state['context_lines']:])
- idx = max(0, state['total_cmds'] - state['context_cmd'])
- start, end, preview = blocks[idx]
- if state['context_mode'] == self.mode_single:
- active_raw = raw_bytes[start:end]
- else:
- # Concat only the bytes of valid blocks to skip intermediate empty/cancelled prompt noise
- active_raw = b"".join(raw_bytes[b[0]:b[1]] for b in blocks[idx:])
- return preview + "\n" + log_cleaner(active_raw.decode(errors='replace'))
-
- def get_prompt_text():
- import html
- # Always use user_prompt color for the Ask prompt
- color = self._get_theme_color("user_prompt", "cyan")
-
- if state['context_mode'] == self.mode_lines:
- text = html.escape(f"Ask [Ctx: {state['context_lines']}/{state['total_lines']}L]: ")
- return HTML(f'<style fg="{color}">{text}</style>')
- active = get_active_buffer()
- lines_count = len(active.split('\n'))
- mode_str = {self.mode_range: "Range", self.mode_single: "Cmd"}[state['context_mode']]
- text = html.escape(f"Ask [{mode_str} {state['context_cmd']} ~{lines_count}L]: ")
- return HTML(f'<style fg="{color}">{text}</style>')
-
- from prompt_toolkit.application.current import get_app
-
- def get_toolbar():
- import html
- app = get_app()
- c_warning = self._get_theme_color("warning", "yellow")
-
- if app and app.current_buffer:
- text = app.current_buffer.text
- # Only show command help if typing the first command and there are no spaces
- if text.startswith('/') and ' ' not in text:
- commands = ['/os', '/prompt', '/architect', '/engineer', '/trust', '/untrust', '/memorize', '/clear', '/mission', '/cancel']
- matches = [c for c in commands if c.startswith(text.lower())]
- if matches:
- m_text = html.escape(f"Available: {' '.join(matches)}")
- return HTML(f'<style fg="{c_warning}">{m_text}</style>' + " " * 20)
-
- m_label = {self.mode_range: "RANGE", self.mode_single: "SINGLE", self.mode_lines: "LINES"}[state['context_mode']]
- if state['context_mode'] == self.mode_lines:
- base_str = f'\u25b6 [Tab: {m_label}] {state["context_lines"]}/{state["total_lines"]}L (Ctrl+\u2191/\u2193 adjusts lines)'
- else:
- idx = max(0, state['total_cmds'] - state['context_cmd'])
-
- def clean_preview(text):
- # Clean newlines and the initial prompt (all up to #, > or $) to leave only the command
- original = text.strip().replace('\r', '').replace('\n', ' ')
- cleaned = re.sub(r'^.*?[#>\$]\s*', '', original)
- # If cleaning the prompt leaves us with an empty string (e.g. it was just "iol#"), return the original
- return cleaned if cleaned else original
-
- if state['context_mode'] == self.mode_range:
- range_blocks = blocks[idx:]
- # If there is more than one block, the last one is always the empty/current prompt. We omit it visually.
- if len(range_blocks) > 1:
- range_blocks = range_blocks[:-1]
-
- # Clean and truncate very long commands so they don't break the UI
- previews = []
- for b in range_blocks:
- p = clean_preview(b[2])
- if p:
- # Truncar comandos individuales largos
- if len(p) > 25: p = p[:22].rstrip(' .,-_') + "..."
- previews.append(p)
-
- if not previews:
- desc = clean_preview(blocks[idx][2])
- elif len(previews) <= 3:
- desc = " + ".join(previews)
- else:
- desc = f"{previews[0]} + {previews[1]} + {previews[2]} (+{len(previews)-3})"
- else:
- # Modo SINGLE original
- desc = clean_preview(blocks[idx][2])
-
- base_str = f'\u25b6 [Tab: {m_label}] {desc}'
-
- # Wrap base_str in a style to maintain consistency and avoid glitches
- # The fg color will be inherited from bottom-toolbar global style if not specified here
- base_html = f'<span>{html.escape(base_str)}</span>'
-
- res_html = base_html
- if state.get('toolbar_msg'):
- if time.time() < state.get('msg_expiry', 0):
- msg = html.escape(state['toolbar_msg'])
- res_html = f'<style fg="{c_warning}">⚙️ {msg}</style> | ' + base_html
- else:
- state['toolbar_msg'] = ''
-
- # Pad with spaces to ensure the line is cleared when the message disappears
- return HTML(res_html + " " * 20)
-
- from prompt_toolkit.completion import Completer, Completion
- class SlashCommandCompleter(Completer):
- def get_completions(self, document, complete_event):
- text = document.text_before_cursor
- if text.startswith('/'):
- parts = text.split()
- # Only autocomplete the first word
- if len(parts) <= 1 or (len(parts) == 1 and not text.endswith(' ')):
- cmd_part = parts[0] if parts else text
- commands = [
- ('/os', 'Set device OS (e.g. cisco_ios)'),
- ('/prompt', 'Override prompt regex'),
- ('/architect', 'Switch to Architect persona'),
- ('/engineer', 'Switch to Engineer persona'),
- ('/trust', 'Enable auto-execute'),
- ('/untrust', 'Disable auto-execute'),
- ('/memorize', 'Add fact to memory'),
- ('/clear', 'Clear memory'),
- ('/mission', 'Start autonomous mission'),
- ('/cancel', 'Cancel active mission')
- ]
- for cmd, desc in commands:
- if cmd.startswith(cmd_part.lower()):
- yield Completion(cmd, start_position=-len(cmd_part), display_meta=desc)
-
- copilot_completer = SlashCommandCompleter()
-
- def _finalize_mission(reason="completed", final_guide=""):
- mission = self.session_state.get('mission', {})
- if not mission or not mission.get('active', False):
- return
- mission['active'] = False
- if reason == "completed":
- self.console.print("\n[bold green]🎉 Mission Completed[/bold green]")
- elif reason == "user_cancelled":
- self.console.print("\n[yellow]Mission cancelled by user.[/yellow]")
- elif reason == "limit_reached":
- self.console.print("\n[yellow]Mission step limit reached.[/yellow]")
-
- final_notes = "\n".join(mission.get('scratchpad_notes', []))
- guide = final_guide or mission.get('last_guide', '')
- asst_msg = f"Notes: {final_notes}\nGuide: {guide}" if final_notes else guide
- hist = self.session_state.setdefault("copilot_chat_history", [])
- hist.append({"role": "user", "content": f"/mission {mission.get('goal', '')}"})
- hist.append({"role": "assistant", "content": asst_msg})
- self.session_state["copilot_chat_history"] = hist[-10:]
-
- while True:
- overrides = {}
- # Check for active mission auto-looping
- mission = self.session_state.get('mission', {})
- is_mission = mission.get('active', False) and not mission.get('paused', False)
-
- if is_mission:
- # Force mode_range for mission mode
- state['context_mode'] = self.mode_range
- self.session_state['context_mode'] = self.mode_range
-
- if mission.get('start_block_idx') is None:
- mission['start_block_idx'] = state['total_cmds']
-
- start_idx = mission.get('start_block_idx', state['total_cmds'])
- cmds_since_start = max(1, (state['total_cmds'] - start_idx) + 1)
- state['context_cmd'] = max(state.get('context_cmd', 1), cmds_since_start)
- self.session_state['context_cmd'] = state['context_cmd']
-
- step = mission.get('step', 1)
- max_steps = mission.get('max_steps', 10)
-
- if step > max_steps:
- ext_session = PromptSession(input=self.pt_input, output=self.pt_output)
- c_warn = self._get_theme_color("warning", "yellow")
- import html
- p_warn = html.escape(f"[Mission Limit Reached ({max_steps} steps)] Extend mission for 10 more steps? (y/n) [y]: ")
- try:
- ext_ans = await ext_session.prompt_async(HTML(f'<style fg="{c_warn}" bold="true">{p_warn}</style>'))
- except (KeyboardInterrupt, EOFError):
- ext_ans = 'n'
-
- if (ext_ans or 'y').lower().strip() in ('y', 'yes'):
- mission['max_steps'] += 10
- else:
- goal = mission.get('goal', '')
- question = f"[MISSION SUMMARY]: Step limit reached ({max_steps} steps). Provide a concise summary of all findings and current status for: {goal}"
- clean_question = question
- mission['active'] = False
- is_mission = False
- self.console.print(f"\n[bold cyan]🤖 Generating Final Mission Summary ({max_steps} steps reached)...[/bold cyan]")
-
- if is_mission:
- goal = mission.get('goal', '')
- step = mission.get('step', 1)
- question = f"[MISSION STEP {step}]: Continue analysis of: {goal}"
-
- scratchpad = mission.get('scratchpad_notes', [])
- if scratchpad:
- notes_text = "\n".join(f"- {n}" for n in scratchpad)
- question += f"\n\nPast Mission Notes:\n{notes_text}"
-
- clean_question = question
- self.console.print(f"\n[bold cyan]🤖 Executing Mission Step {step}: {goal}[/bold cyan]")
- elif not is_mission and 'clean_question' in locals() and clean_question.startswith("[MISSION SUMMARY]"):
- # Pass-through to AI execution for generating final summary
- pass
- else:
- # 2. Ask question
- from prompt_toolkit.styles import Style
- c_contrast = self._get_theme_color("contrast", "gray")
- ui_style = Style.from_dict({
- 'bottom-toolbar': f'fg:{c_contrast}',
- })
-
- session = PromptSession(
- history=self.history,
- input=self.pt_input,
- output=self.pt_output,
- completer=copilot_completer,
- reserve_space_for_menu=0,
- style=ui_style
- )
- try:
- question = await session.prompt_async(
- get_prompt_text,
- key_bindings=bindings,
- bottom_toolbar=get_toolbar,
- multiline=True
- )
- except (KeyboardInterrupt, EOFError):
- state['cancelled'] = True
- question = ""
-
- if state['cancelled'] or not question.strip() or question.strip().lower() in ['cancel', 'exit', 'quit']:
- _finalize_mission("user_cancelled")
- return "cancel", None, None
-
- # 3. Process Input via AIService
- directive = self.ai_service.process_copilot_input(question, self.session_state)
-
- if directive["action"] == "mission_start":
- mission = self.session_state.get('mission', {})
- mission['start_block_idx'] = state['total_cmds']
- state['context_mode'] = self.mode_range
- self.session_state['context_mode'] = self.mode_range
- state['context_cmd'] = 1
- self.session_state['context_cmd'] = 1
- clean_question = f"[MISSION STEP 1]: {directive['clean_prompt']}"
- overrides = directive.get("overrides", {})
- self.console.print(f"\n[bold cyan]🤖 Starting Mission: {directive['clean_prompt']}[/bold cyan]")
- elif directive["action"] == "mission_cancel":
- _finalize_mission("user_cancelled")
- state['toolbar_msg'] = 'Mission cancelled'
- continue
- elif directive["action"] == "state_update":
- msg = directive['message']
- state['toolbar_msg'] = msg
- state['msg_expiry'] = time.time() + 3 # 3 seconds timeout
-
- async def delayed_refresh():
- await asyncio.sleep(3.1)
- if state.get('toolbar_msg') == msg:
- state['toolbar_msg'] = ''
- try:
- from prompt_toolkit.application.current import get_app
- app = get_app()
- if app: app.invalidate()
- except: pass
- asyncio.create_task(delayed_refresh())
-
- sys.stdout.write('\x1b[1A\x1b[2K')
- sys.stdout.flush()
- continue
- else:
- state['toolbar_msg'] = ''
- if mission.get('active', False):
- mission['paused'] = False
- step = mission.get('step', 1)
- goal = mission.get('goal', '')
- clean_question = f"[MISSION FEEDBACK (Step {step})]: User provided guidance: {question}. Continue the mission for goal: {goal}"
- self.console.print(f"\n[bold cyan]🤖 Continuing Mission with User Feedback: {question}[/bold cyan]")
- overrides = directive.get("overrides", {})
- else:
- clean_question = directive.get("clean_prompt", question)
- overrides = directive.get("overrides", {})
-
- # Merge node_info with session_state and overrides
- merged_node_info = node_info.copy()
- if self.session_state['os']: merged_node_info['os'] = self.session_state['os']
- if self.session_state['prompt']: merged_node_info['prompt'] = self.session_state['prompt']
- merged_node_info['persona'] = self.session_state['persona']
- merged_node_info['trust'] = self.session_state['trust_mode']
- merged_node_info['memories'] = list(self.session_state['memories'])
- merged_node_info['chat_history'] = list(self.session_state.get('copilot_chat_history', []))
-
- for k, v in overrides.items():
- merged_node_info[k] = v
-
- # 3. AI Execution
- active_persona = merged_node_info.get('persona', self.session_state.get('persona', 'engineer'))
- persona_color = self._get_theme_color(active_persona, fallback="cyan")
- persona_title = "Network Architect" if active_persona == "architect" else "Network Engineer"
-
- active_buffer = get_active_buffer()
-
- live_text = ""
- first_chunk = True
-
- from rich.rule import Rule
- from rich.status import Status
- from connpy.printer import IncrementalMarkdownParser
-
- md_parser = IncrementalMarkdownParser(console=self.console)
-
- status_spinner = Status(
- f"[bold {persona_color}]{persona_title}:[/bold {persona_color}] [dim]Thinking...[/dim]",
- console=self.console,
- spinner="dots"
- )
- status_spinner.start()
-
- def on_chunk(text):
- nonlocal live_text, first_chunk
- if first_chunk:
- status_spinner.stop()
- self.console.print(Rule(
- f"[bold {persona_color}]{persona_title}[/bold {persona_color}]",
- style=persona_color
- ))
- first_chunk = False
- live_text += text
- md_parser.feed(text)
-
- ai_task = asyncio.create_task(on_ai_call(active_buffer, clean_question, on_chunk, merged_node_info))
-
- try:
- while not ai_task.done():
- await asyncio.sleep(0.05)
- result = await ai_task
- except asyncio.CancelledError:
- status_spinner.stop()
- _finalize_mission("user_cancelled")
- return "cancel", None, None
-
- if first_chunk:
- status_spinner.stop()
-
- if not first_chunk:
- md_parser.flush()
- self.console.print(Rule(style=persona_color))
-
- if not result or result.get("error"):
- if first_chunk and result and result.get("error"):
- self.console.print(f"[red]Error: {result['error']}[/red]")
- _finalize_mission("user_cancelled")
- return "cancel", None, None
-
- if first_chunk and result and result.get("guide"):
- from rich.markdown import Markdown
- self.console.print(Panel(Markdown(result["guide"]), title=f"[bold {persona_color}]{persona_title}[/bold {persona_color}]", border_style=persona_color))
-
- # Update copilot_chat_history or mission scratchpad
- if result and not result.get("error"):
- guide = result.get("guide", "")
- notes = result.get("notes", "")
- mission = self.session_state.get('mission', {})
- if mission.get('active', False):
- if notes:
- mission.setdefault('scratchpad_notes', []).append(notes)
- if guide:
- mission['last_guide'] = guide
- else:
- if guide or notes:
- asst_msg = f"Notes: {notes}\nGuide: {guide}" if notes else guide
- hist = self.session_state.setdefault("copilot_chat_history", [])
- hist.append({"role": "user", "content": clean_question})
- hist.append({"role": "assistant", "content": asst_msg})
- self.session_state["copilot_chat_history"] = hist[-10:]
- commands = result.get("commands", [])
- mission = self.session_state.get('mission', {})
- if not commands:
- if mission.get('active', False):
- _finalize_mission("completed", result.get("guide", ""))
- self.console.print("")
- return "continue", None, None
-
- risk = result.get("risk_level", "low")
- risk_style = {"low": "success", "high": "warning", "destructive": "error"}.get(risk, "success")
- style_color = self._get_theme_color(risk_style, fallback="green")
-
- cmd_text = "\n".join(f" {i+1}. {c}" for i, c in enumerate(commands))
- self.console.print(Panel(cmd_text, title=f"[bold {style_color}]Suggested Commands [{risk.upper()}][/bold {style_color}]", border_style=f"bold {style_color}"))
-
- if merged_node_info.get('trust', False) and risk != "destructive":
- self.console.print(f"[dim]⚙️ Auto-executing (Trust Mode)[/dim]")
- if mission.get('active', False):
- mission['step'] = mission.get('step', 1) + 1
- return "send_all", commands, None
-
- confirm_session = PromptSession(input=self.pt_input, output=self.pt_output)
- c_bindings = KeyBindings()
- @c_bindings.add('escape', eager=True)
- @c_bindings.add('c-c')
- def _(ev): ev.app.exit(result='n')
-
- import html
- try:
- p_text = html.escape(f"Send? (y/n/e/range) [n]: ")
- action = await confirm_session.prompt_async(HTML(f'<style fg="{style_color}" bold="true">{p_text}</style>'), key_bindings=c_bindings)
- except (KeyboardInterrupt, EOFError):
- _finalize_mission("user_cancelled", result.get("guide", ""))
- self.console.print("")
- return "continue", None, None
-
- def parse_indices(text, max_len):
- indices = []
- parts = text.replace(',', ' ').split()
- for part in parts:
- if '-' in part:
- try:
- start, end = map(int, part.split('-'))
- indices.extend(range(start-1, end))
- except: continue
- elif part.isdigit():
- indices.append(int(part)-1)
- return [i for i in sorted(set(indices)) if 0 <= i < max_len]
-
- action_l = (action or "n").lower().strip()
- if action_l in ('y', 'yes', 'all'):
- if mission.get('active', False):
- mission['step'] = mission.get('step', 1) + 1
- return "send_all", commands, None
-
- if re.match(r'^[0-9,\-\s]+$', action_l):
- selected_idxs = parse_indices(action_l, len(commands))
- if selected_idxs:
- if mission.get('active', False):
- mission['step'] = mission.get('step', 1) + 1
- return "send_all", [commands[i] for i in selected_idxs], None
-
- elif action_l.startswith('e'):
- selection_str = action_l[1:].strip()
- if selection_str:
- idxs = parse_indices(selection_str, len(commands))
- cmds_to_edit = [commands[i] for i in idxs] if idxs else commands
- else:
- cmds_to_edit = commands
-
- target = "\n".join(cmds_to_edit)
- e_bindings = KeyBindings()
- @e_bindings.add('c-j')
- def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
- @e_bindings.add('escape', 'enter')
- def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
- @e_bindings.add('escape')
- def _(ev): ev.app.exit(result='')
-
- c_edit = self._get_theme_color("user_prompt", "cyan")
- import html
- e_text = html.escape("Edit (Ctrl+Enter or Esc+Enter to submit):\n")
- try:
- edited = await confirm_session.prompt_async(
- HTML(f'<style fg="{c_edit}">{e_text}</style>'),
- default=target, multiline=True, key_bindings=e_bindings
- )
- except (KeyboardInterrupt, EOFError):
- if mission.get('active', False):
- mission['paused'] = True
- self.console.print("\n[yellow]⏸️ Mission Paused — Provide feedback to redirect, or type /cancel to abort.[/yellow]")
- self.console.print("")
- return "continue", None, None
-
- if edited and edited.strip():
- lines = [l.strip() for l in edited.split('\n') if l.strip()]
- if mission.get('active', False):
- mission['step'] = mission.get('step', 1) + 1
- return "custom", None, lines
-
- # User rejected/cancelled the commands
- if mission.get('active', False):
- mission['paused'] = True
- self.console.print("\n[yellow]⏸️ Mission Paused — Provide feedback to redirect, or type /cancel to abort.[/yellow]")
-
- self.console.print("")
- return "continue", None, None
-
- return "cancel", None, None
-
- finally:
- state['cancelled'] = True
-
-async def run_session(self,
raw_bytes: bytes,
node_info: dict,
on_ai_call: Callable,
cmd_byte_positions: List[tuple] = None,
blocks: List[tuple] = None)
-async def run_session(self,
- raw_bytes: bytes,
- node_info: dict,
- on_ai_call: Callable,
- cmd_byte_positions: List[tuple] = None,
- blocks: List[tuple] = None):
- """
- Runs the interactive Copilot session.
- on_ai_call: async function(active_buffer, question) -> result_dict
- """
- from rich.rule import Rule
-
- try:
- # Prepare UI state
- buffer = log_cleaner(raw_bytes.decode(errors='replace'))
-
- # Use pre-calculated blocks if provided (remote mode), otherwise calculate locally (local mode)
- if blocks is None:
- last_line = buffer.split('\n')[-1].strip() if buffer.strip() else "(prompt)"
- blocks = self.ai_service.build_context_blocks(raw_bytes, cmd_byte_positions, node_info, last_line=last_line)
-
- total_cmds = len(blocks)
- total_lines = len(buffer.split('\n'))
-
- saved_mode = self.session_state.get('context_mode', self.mode_range)
- saved_cmd = self.session_state.get('context_cmd', 1)
- saved_lines = self.session_state.get('context_lines', min(50, total_lines))
- last_total_cmds = self.session_state.get('last_total_cmds', None)
- last_total_lines = self.session_state.get('last_total_lines', None)
-
- is_range = saved_mode in (self.mode_range, 0, 'RANGE', 'range')
- is_lines = saved_mode in (self.mode_lines, 2, 'LINES', 'lines')
- is_single = saved_mode in (self.mode_single, 1, 'SINGLE', 'single')
-
- if is_range or is_single:
- is_mission = self.session_state.get('mission', {}).get('active', False)
- if last_total_cmds is not None and total_cmds > last_total_cmds and (saved_cmd > 1 or is_mission):
- new_cmds = total_cmds - last_total_cmds
- initial_cmd = saved_cmd + new_cmds
- else:
- initial_cmd = saved_cmd
- initial_lines = saved_lines
- elif is_lines:
- if last_total_lines is not None and total_lines > last_total_lines and saved_lines > 50:
- new_lines = total_lines - last_total_lines
- initial_lines = saved_lines + new_lines
- else:
- initial_lines = saved_lines
- initial_cmd = saved_cmd
- else:
- initial_cmd = saved_cmd
- initial_lines = saved_lines
-
- state = {
- 'context_cmd': min(max(1, initial_cmd), max(1, total_cmds)),
- 'total_cmds': total_cmds,
- 'total_lines': total_lines,
- 'context_lines': min(max(1, initial_lines), max(1, total_lines)),
- 'context_mode': saved_mode,
- 'cancelled': False,
- 'toolbar_msg': '',
- 'msg_expiry': 0
- }
- self.session_state['context_mode'] = saved_mode
- self.session_state['context_cmd'] = max(1, initial_cmd)
- self.session_state['context_lines'] = max(1, initial_lines)
- self.session_state['last_total_cmds'] = total_cmds
- self.session_state['last_total_lines'] = total_lines
-
- # 1. Visual Separation (Only show help banner on initial entry)
- self.console.print("") # Real line break
- self.console.print(Rule(title="[bold cyan] AI TERMINAL COPILOT [/bold cyan]", style="cyan"))
- if not self.session_state.get('banner_shown', False):
- self.console.print(Panel(
- "[dim]Type your question. Enter to send, Escape/Ctrl+C to cancel. Type / for commands.\n"
- "Tab to change context mode. Ctrl+\u2191/\u2193 to adjust context. \u2191\u2193 for question history.[/dim]",
- border_style="cyan"
- ))
- self.session_state['banner_shown'] = True
- self.console.print("") # Small space before the copilot prompt
-
- bindings = KeyBindings()
- @bindings.add('c-up')
- def _(event):
- if state['context_mode'] == self.mode_lines:
- state['context_lines'] = min(state['context_lines'] + 50, state['total_lines'])
- else:
- state['context_cmd'] = min(state['context_cmd'] + 1, state['total_cmds'])
- self._sync_session_context(state)
- event.app.invalidate()
- @bindings.add('c-down')
- def _(event):
- if state['context_mode'] == self.mode_lines:
- state['context_lines'] = max(state['context_lines'] - 50, min(50, state['total_lines']))
- else:
- state['context_cmd'] = max(state['context_cmd'] - 1, 1)
- self._sync_session_context(state)
- event.app.invalidate()
- @bindings.add('tab')
- def _(event):
- buf = event.current_buffer
- # If typing a slash command (no spaces yet), use tab to autocomplete inline
- if buf.text.startswith('/') and ' ' not in buf.text:
- buf.complete_next()
- else:
- state['context_mode'] = (state['context_mode'] + 1) % 3
- self._sync_session_context(state)
- event.app.invalidate()
- @bindings.add('escape', eager=True)
- @bindings.add('c-c')
- def _(event):
- state['cancelled'] = True
- event.app.exit(result='')
-
- # Multiline keybindings: Enter to submit, Ctrl+Enter (c-j) or Alt+Enter to add a newline
- @bindings.add('enter', filter=~has_completions)
- def _(event):
- event.current_buffer.validate_and_handle()
-
- @bindings.add('c-j')
- @bindings.add('escape', 'enter')
- def _(event):
- event.current_buffer.insert_text('\n')
-
- def get_active_buffer():
- if state['context_mode'] == self.mode_lines:
- return '\n'.join(buffer.split('\n')[-state['context_lines']:])
- idx = max(0, state['total_cmds'] - state['context_cmd'])
- start, end, preview = blocks[idx]
- if state['context_mode'] == self.mode_single:
- active_raw = raw_bytes[start:end]
- else:
- # Concat only the bytes of valid blocks to skip intermediate empty/cancelled prompt noise
- active_raw = b"".join(raw_bytes[b[0]:b[1]] for b in blocks[idx:])
- return preview + "\n" + log_cleaner(active_raw.decode(errors='replace'))
-
- def get_prompt_text():
- import html
- # Always use user_prompt color for the Ask prompt
- color = self._get_theme_color("user_prompt", "cyan")
-
- if state['context_mode'] == self.mode_lines:
- text = html.escape(f"Ask [Ctx: {state['context_lines']}/{state['total_lines']}L]: ")
- return HTML(f'<style fg="{color}">{text}</style>')
- active = get_active_buffer()
- lines_count = len(active.split('\n'))
- mode_str = {self.mode_range: "Range", self.mode_single: "Cmd"}[state['context_mode']]
- text = html.escape(f"Ask [{mode_str} {state['context_cmd']} ~{lines_count}L]: ")
- return HTML(f'<style fg="{color}">{text}</style>')
-
- from prompt_toolkit.application.current import get_app
-
- def get_toolbar():
- import html
- app = get_app()
- c_warning = self._get_theme_color("warning", "yellow")
-
- if app and app.current_buffer:
- text = app.current_buffer.text
- # Only show command help if typing the first command and there are no spaces
- if text.startswith('/') and ' ' not in text:
- commands = ['/os', '/prompt', '/architect', '/engineer', '/trust', '/untrust', '/memorize', '/clear', '/mission', '/cancel']
- matches = [c for c in commands if c.startswith(text.lower())]
- if matches:
- m_text = html.escape(f"Available: {' '.join(matches)}")
- return HTML(f'<style fg="{c_warning}">{m_text}</style>' + " " * 20)
-
- m_label = {self.mode_range: "RANGE", self.mode_single: "SINGLE", self.mode_lines: "LINES"}[state['context_mode']]
- if state['context_mode'] == self.mode_lines:
- base_str = f'\u25b6 [Tab: {m_label}] {state["context_lines"]}/{state["total_lines"]}L (Ctrl+\u2191/\u2193 adjusts lines)'
- else:
- idx = max(0, state['total_cmds'] - state['context_cmd'])
-
- def clean_preview(text):
- # Clean newlines and the initial prompt (all up to #, > or $) to leave only the command
- original = text.strip().replace('\r', '').replace('\n', ' ')
- cleaned = re.sub(r'^.*?[#>\$]\s*', '', original)
- # If cleaning the prompt leaves us with an empty string (e.g. it was just "iol#"), return the original
- return cleaned if cleaned else original
-
- if state['context_mode'] == self.mode_range:
- range_blocks = blocks[idx:]
- # If there is more than one block, the last one is always the empty/current prompt. We omit it visually.
- if len(range_blocks) > 1:
- range_blocks = range_blocks[:-1]
-
- # Clean and truncate very long commands so they don't break the UI
- previews = []
- for b in range_blocks:
- p = clean_preview(b[2])
- if p:
- # Truncar comandos individuales largos
- if len(p) > 25: p = p[:22].rstrip(' .,-_') + "..."
- previews.append(p)
-
- if not previews:
- desc = clean_preview(blocks[idx][2])
- elif len(previews) <= 3:
- desc = " + ".join(previews)
- else:
- desc = f"{previews[0]} + {previews[1]} + {previews[2]} (+{len(previews)-3})"
- else:
- # Modo SINGLE original
- desc = clean_preview(blocks[idx][2])
-
- base_str = f'\u25b6 [Tab: {m_label}] {desc}'
-
- # Wrap base_str in a style to maintain consistency and avoid glitches
- # The fg color will be inherited from bottom-toolbar global style if not specified here
- base_html = f'<span>{html.escape(base_str)}</span>'
-
- res_html = base_html
- if state.get('toolbar_msg'):
- if time.time() < state.get('msg_expiry', 0):
- msg = html.escape(state['toolbar_msg'])
- res_html = f'<style fg="{c_warning}">⚙️ {msg}</style> | ' + base_html
- else:
- state['toolbar_msg'] = ''
-
- # Pad with spaces to ensure the line is cleared when the message disappears
- return HTML(res_html + " " * 20)
-
- from prompt_toolkit.completion import Completer, Completion
- class SlashCommandCompleter(Completer):
- def get_completions(self, document, complete_event):
- text = document.text_before_cursor
- if text.startswith('/'):
- parts = text.split()
- # Only autocomplete the first word
- if len(parts) <= 1 or (len(parts) == 1 and not text.endswith(' ')):
- cmd_part = parts[0] if parts else text
- commands = [
- ('/os', 'Set device OS (e.g. cisco_ios)'),
- ('/prompt', 'Override prompt regex'),
- ('/architect', 'Switch to Architect persona'),
- ('/engineer', 'Switch to Engineer persona'),
- ('/trust', 'Enable auto-execute'),
- ('/untrust', 'Disable auto-execute'),
- ('/memorize', 'Add fact to memory'),
- ('/clear', 'Clear memory'),
- ('/mission', 'Start autonomous mission'),
- ('/cancel', 'Cancel active mission')
- ]
- for cmd, desc in commands:
- if cmd.startswith(cmd_part.lower()):
- yield Completion(cmd, start_position=-len(cmd_part), display_meta=desc)
-
- copilot_completer = SlashCommandCompleter()
-
- def _finalize_mission(reason="completed", final_guide=""):
- mission = self.session_state.get('mission', {})
- if not mission or not mission.get('active', False):
- return
- mission['active'] = False
- if reason == "completed":
- self.console.print("\n[bold green]🎉 Mission Completed[/bold green]")
- elif reason == "user_cancelled":
- self.console.print("\n[yellow]Mission cancelled by user.[/yellow]")
- elif reason == "limit_reached":
- self.console.print("\n[yellow]Mission step limit reached.[/yellow]")
-
- final_notes = "\n".join(mission.get('scratchpad_notes', []))
- guide = final_guide or mission.get('last_guide', '')
- asst_msg = f"Notes: {final_notes}\nGuide: {guide}" if final_notes else guide
- hist = self.session_state.setdefault("copilot_chat_history", [])
- hist.append({"role": "user", "content": f"/mission {mission.get('goal', '')}"})
- hist.append({"role": "assistant", "content": asst_msg})
- self.session_state["copilot_chat_history"] = hist[-10:]
-
- while True:
- overrides = {}
- # Check for active mission auto-looping
- mission = self.session_state.get('mission', {})
- is_mission = mission.get('active', False) and not mission.get('paused', False)
-
- if is_mission:
- # Force mode_range for mission mode
- state['context_mode'] = self.mode_range
- self.session_state['context_mode'] = self.mode_range
-
- if mission.get('start_block_idx') is None:
- mission['start_block_idx'] = state['total_cmds']
-
- start_idx = mission.get('start_block_idx', state['total_cmds'])
- cmds_since_start = max(1, (state['total_cmds'] - start_idx) + 1)
- state['context_cmd'] = max(state.get('context_cmd', 1), cmds_since_start)
- self.session_state['context_cmd'] = state['context_cmd']
-
- step = mission.get('step', 1)
- max_steps = mission.get('max_steps', 10)
-
- if step > max_steps:
- ext_session = PromptSession(input=self.pt_input, output=self.pt_output)
- c_warn = self._get_theme_color("warning", "yellow")
- import html
- p_warn = html.escape(f"[Mission Limit Reached ({max_steps} steps)] Extend mission for 10 more steps? (y/n) [y]: ")
- try:
- ext_ans = await ext_session.prompt_async(HTML(f'<style fg="{c_warn}" bold="true">{p_warn}</style>'))
- except (KeyboardInterrupt, EOFError):
- ext_ans = 'n'
-
- if (ext_ans or 'y').lower().strip() in ('y', 'yes'):
- mission['max_steps'] += 10
- else:
- goal = mission.get('goal', '')
- question = f"[MISSION SUMMARY]: Step limit reached ({max_steps} steps). Provide a concise summary of all findings and current status for: {goal}"
- clean_question = question
- mission['active'] = False
- is_mission = False
- self.console.print(f"\n[bold cyan]🤖 Generating Final Mission Summary ({max_steps} steps reached)...[/bold cyan]")
-
- if is_mission:
- goal = mission.get('goal', '')
- step = mission.get('step', 1)
- question = f"[MISSION STEP {step}]: Continue analysis of: {goal}"
-
- scratchpad = mission.get('scratchpad_notes', [])
- if scratchpad:
- notes_text = "\n".join(f"- {n}" for n in scratchpad)
- question += f"\n\nPast Mission Notes:\n{notes_text}"
-
- clean_question = question
- self.console.print(f"\n[bold cyan]🤖 Executing Mission Step {step}: {goal}[/bold cyan]")
- elif not is_mission and 'clean_question' in locals() and clean_question.startswith("[MISSION SUMMARY]"):
- # Pass-through to AI execution for generating final summary
- pass
- else:
- # 2. Ask question
- from prompt_toolkit.styles import Style
- c_contrast = self._get_theme_color("contrast", "gray")
- ui_style = Style.from_dict({
- 'bottom-toolbar': f'fg:{c_contrast}',
- })
-
- session = PromptSession(
- history=self.history,
- input=self.pt_input,
- output=self.pt_output,
- completer=copilot_completer,
- reserve_space_for_menu=0,
- style=ui_style
- )
- try:
- question = await session.prompt_async(
- get_prompt_text,
- key_bindings=bindings,
- bottom_toolbar=get_toolbar,
- multiline=True
- )
- except (KeyboardInterrupt, EOFError):
- state['cancelled'] = True
- question = ""
-
- if state['cancelled'] or not question.strip() or question.strip().lower() in ['cancel', 'exit', 'quit']:
- _finalize_mission("user_cancelled")
- return "cancel", None, None
-
- # 3. Process Input via AIService
- directive = self.ai_service.process_copilot_input(question, self.session_state)
-
- if directive["action"] == "mission_start":
- mission = self.session_state.get('mission', {})
- mission['start_block_idx'] = state['total_cmds']
- state['context_mode'] = self.mode_range
- self.session_state['context_mode'] = self.mode_range
- state['context_cmd'] = 1
- self.session_state['context_cmd'] = 1
- clean_question = f"[MISSION STEP 1]: {directive['clean_prompt']}"
- overrides = directive.get("overrides", {})
- self.console.print(f"\n[bold cyan]🤖 Starting Mission: {directive['clean_prompt']}[/bold cyan]")
- elif directive["action"] == "mission_cancel":
- _finalize_mission("user_cancelled")
- state['toolbar_msg'] = 'Mission cancelled'
- continue
- elif directive["action"] == "state_update":
- msg = directive['message']
- state['toolbar_msg'] = msg
- state['msg_expiry'] = time.time() + 3 # 3 seconds timeout
-
- async def delayed_refresh():
- await asyncio.sleep(3.1)
- if state.get('toolbar_msg') == msg:
- state['toolbar_msg'] = ''
- try:
- from prompt_toolkit.application.current import get_app
- app = get_app()
- if app: app.invalidate()
- except: pass
- asyncio.create_task(delayed_refresh())
-
- sys.stdout.write('\x1b[1A\x1b[2K')
- sys.stdout.flush()
- continue
- else:
- state['toolbar_msg'] = ''
- if mission.get('active', False):
- mission['paused'] = False
- step = mission.get('step', 1)
- goal = mission.get('goal', '')
- clean_question = f"[MISSION FEEDBACK (Step {step})]: User provided guidance: {question}. Continue the mission for goal: {goal}"
- self.console.print(f"\n[bold cyan]🤖 Continuing Mission with User Feedback: {question}[/bold cyan]")
- overrides = directive.get("overrides", {})
- else:
- clean_question = directive.get("clean_prompt", question)
- overrides = directive.get("overrides", {})
-
- # Merge node_info with session_state and overrides
- merged_node_info = node_info.copy()
- if self.session_state['os']: merged_node_info['os'] = self.session_state['os']
- if self.session_state['prompt']: merged_node_info['prompt'] = self.session_state['prompt']
- merged_node_info['persona'] = self.session_state['persona']
- merged_node_info['trust'] = self.session_state['trust_mode']
- merged_node_info['memories'] = list(self.session_state['memories'])
- merged_node_info['chat_history'] = list(self.session_state.get('copilot_chat_history', []))
-
- for k, v in overrides.items():
- merged_node_info[k] = v
-
- # 3. AI Execution
- active_persona = merged_node_info.get('persona', self.session_state.get('persona', 'engineer'))
- persona_color = self._get_theme_color(active_persona, fallback="cyan")
- persona_title = "Network Architect" if active_persona == "architect" else "Network Engineer"
-
- active_buffer = get_active_buffer()
-
- live_text = ""
- first_chunk = True
-
- from rich.rule import Rule
- from rich.status import Status
- from connpy.printer import IncrementalMarkdownParser
-
- md_parser = IncrementalMarkdownParser(console=self.console)
-
- status_spinner = Status(
- f"[bold {persona_color}]{persona_title}:[/bold {persona_color}] [dim]Thinking...[/dim]",
- console=self.console,
- spinner="dots"
- )
- status_spinner.start()
-
- def on_chunk(text):
- nonlocal live_text, first_chunk
- if first_chunk:
- status_spinner.stop()
- self.console.print(Rule(
- f"[bold {persona_color}]{persona_title}[/bold {persona_color}]",
- style=persona_color
- ))
- first_chunk = False
- live_text += text
- md_parser.feed(text)
-
- ai_task = asyncio.create_task(on_ai_call(active_buffer, clean_question, on_chunk, merged_node_info))
-
- try:
- while not ai_task.done():
- await asyncio.sleep(0.05)
- result = await ai_task
- except asyncio.CancelledError:
- status_spinner.stop()
- _finalize_mission("user_cancelled")
- return "cancel", None, None
-
- if first_chunk:
- status_spinner.stop()
-
- if not first_chunk:
- md_parser.flush()
- self.console.print(Rule(style=persona_color))
-
- if not result or result.get("error"):
- if first_chunk and result and result.get("error"):
- self.console.print(f"[red]Error: {result['error']}[/red]")
- _finalize_mission("user_cancelled")
- return "cancel", None, None
-
- if first_chunk and result and result.get("guide"):
- from rich.markdown import Markdown
- self.console.print(Panel(Markdown(result["guide"]), title=f"[bold {persona_color}]{persona_title}[/bold {persona_color}]", border_style=persona_color))
-
- # Update copilot_chat_history or mission scratchpad
- if result and not result.get("error"):
- guide = result.get("guide", "")
- notes = result.get("notes", "")
- mission = self.session_state.get('mission', {})
- if mission.get('active', False):
- if notes:
- mission.setdefault('scratchpad_notes', []).append(notes)
- if guide:
- mission['last_guide'] = guide
- else:
- if guide or notes:
- asst_msg = f"Notes: {notes}\nGuide: {guide}" if notes else guide
- hist = self.session_state.setdefault("copilot_chat_history", [])
- hist.append({"role": "user", "content": clean_question})
- hist.append({"role": "assistant", "content": asst_msg})
- self.session_state["copilot_chat_history"] = hist[-10:]
- commands = result.get("commands", [])
- mission = self.session_state.get('mission', {})
- if not commands:
- if mission.get('active', False):
- _finalize_mission("completed", result.get("guide", ""))
- self.console.print("")
- return "continue", None, None
-
- risk = result.get("risk_level", "low")
- risk_style = {"low": "success", "high": "warning", "destructive": "error"}.get(risk, "success")
- style_color = self._get_theme_color(risk_style, fallback="green")
-
- cmd_text = "\n".join(f" {i+1}. {c}" for i, c in enumerate(commands))
- self.console.print(Panel(cmd_text, title=f"[bold {style_color}]Suggested Commands [{risk.upper()}][/bold {style_color}]", border_style=f"bold {style_color}"))
-
- if merged_node_info.get('trust', False) and risk != "destructive":
- self.console.print(f"[dim]⚙️ Auto-executing (Trust Mode)[/dim]")
- if mission.get('active', False):
- mission['step'] = mission.get('step', 1) + 1
- return "send_all", commands, None
-
- confirm_session = PromptSession(input=self.pt_input, output=self.pt_output)
- c_bindings = KeyBindings()
- @c_bindings.add('escape', eager=True)
- @c_bindings.add('c-c')
- def _(ev): ev.app.exit(result='n')
-
- import html
- try:
- p_text = html.escape(f"Send? (y/n/e/range) [n]: ")
- action = await confirm_session.prompt_async(HTML(f'<style fg="{style_color}" bold="true">{p_text}</style>'), key_bindings=c_bindings)
- except (KeyboardInterrupt, EOFError):
- _finalize_mission("user_cancelled", result.get("guide", ""))
- self.console.print("")
- return "continue", None, None
-
- def parse_indices(text, max_len):
- indices = []
- parts = text.replace(',', ' ').split()
- for part in parts:
- if '-' in part:
- try:
- start, end = map(int, part.split('-'))
- indices.extend(range(start-1, end))
- except: continue
- elif part.isdigit():
- indices.append(int(part)-1)
- return [i for i in sorted(set(indices)) if 0 <= i < max_len]
-
- action_l = (action or "n").lower().strip()
- if action_l in ('y', 'yes', 'all'):
- if mission.get('active', False):
- mission['step'] = mission.get('step', 1) + 1
- return "send_all", commands, None
-
- if re.match(r'^[0-9,\-\s]+$', action_l):
- selected_idxs = parse_indices(action_l, len(commands))
- if selected_idxs:
- if mission.get('active', False):
- mission['step'] = mission.get('step', 1) + 1
- return "send_all", [commands[i] for i in selected_idxs], None
-
- elif action_l.startswith('e'):
- selection_str = action_l[1:].strip()
- if selection_str:
- idxs = parse_indices(selection_str, len(commands))
- cmds_to_edit = [commands[i] for i in idxs] if idxs else commands
- else:
- cmds_to_edit = commands
-
- target = "\n".join(cmds_to_edit)
- e_bindings = KeyBindings()
- @e_bindings.add('c-j')
- def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
- @e_bindings.add('escape', 'enter')
- def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
- @e_bindings.add('escape')
- def _(ev): ev.app.exit(result='')
-
- c_edit = self._get_theme_color("user_prompt", "cyan")
- import html
- e_text = html.escape("Edit (Ctrl+Enter or Esc+Enter to submit):\n")
- try:
- edited = await confirm_session.prompt_async(
- HTML(f'<style fg="{c_edit}">{e_text}</style>'),
- default=target, multiline=True, key_bindings=e_bindings
- )
- except (KeyboardInterrupt, EOFError):
- if mission.get('active', False):
- mission['paused'] = True
- self.console.print("\n[yellow]⏸️ Mission Paused — Provide feedback to redirect, or type /cancel to abort.[/yellow]")
- self.console.print("")
- return "continue", None, None
-
- if edited and edited.strip():
- lines = [l.strip() for l in edited.split('\n') if l.strip()]
- if mission.get('active', False):
- mission['step'] = mission.get('step', 1) + 1
- return "custom", None, lines
-
- # User rejected/cancelled the commands
- if mission.get('active', False):
- mission['paused'] = True
- self.console.print("\n[yellow]⏸️ Mission Paused — Provide feedback to redirect, or type /cancel to abort.[/yellow]")
-
- self.console.print("")
- return "continue", None, None
-
- return "cancel", None, None
-
- finally:
- state['cancelled'] = True
-Runs the interactive Copilot session. -on_ai_call: async function(active_buffer, question) -> result_dict
connpy.cliCopilotInterfacerun_sessionMissing associated documentation comment in .proto file.
Constructor.
-channelMissing associated documentation comment in .proto file.
Constructor.
-channelMissing associated documentation comment in .proto file.
Constructor.
-channelMissing associated documentation comment in .proto file.
Constructor.
-channelMissing associated documentation comment in .proto file.
Constructor.
-channelMissing associated documentation comment in .proto file.
Constructor.
-channelMissing associated documentation comment in .proto file.
Constructor.
-channelMissing associated documentation comment in .proto file.
Constructor.
-channelMissing associated documentation comment in .proto file.
Constructor.
-channelvar DESCRIPTORThe type of the None singleton.
var DESCRIPTORThe type of the None singleton.
var DESCRIPTORThe type of the None singleton.
var DESCRIPTORThe type of the None singleton.
Missing associated documentation comment in .proto file.
Constructor.
-channelvar OPEN_METHODSThe type of the None singleton.
continuationhandler_call_detailsAn RpcMethodHandler with which the RPC may be serviced if the +
Returns +-----= +An RpcMethodHandler with which the RPC may be serviced if the interceptor chooses to service this RPC, or None otherwise.
@@ -1213,7 +1215,7 @@ def service(self): if request.value.startswith("---YAML---\n"): import yaml content = request.value[len("---YAML---\n"):] - data = yaml.load(content, Loader=yaml.FullLoader) + data = yaml.safe_load(content) self.service.import_from_dict(data) else: self.service.import_from_file(request.value) @@ -1340,8 +1342,9 @@ contextvars.Context, and the same Context is used for downstream interceptors and for the final handler call. Note that there are no guarantees that interceptors and handlers will be called from the same thread. -continuationhandler_call_detailsAn RpcMethodHandler with which the RPC may be serviced if the +
Returns +-----= +An RpcMethodHandler with which the RPC may be serviced if the interceptor chooses to service this RPC, or None otherwise.
diff --git a/docs/connpy/grpc_layer/stubs.html b/docs/connpy/grpc_layer/stubs.html index e446c7f..82f62f7 100644 --- a/docs/connpy/grpc_layer/stubs.html +++ b/docs/connpy/grpc_layer/stubs.html @@ -42,2812 +42,8 @@ el.replaceWith(d);
-def handle_errors(func)
-def handle_errors(func):
- @wraps(func)
- def wrapper(*args, **kwargs):
- try:
- return func(*args, **kwargs)
- except grpc.RpcError as e:
- # Re-raise gRPC errors as native ConnpyError to keep CLI handlers agnostic
- details = e.details()
-
- # Identify the host if available on the instance
- instance = args[0] if args else None
- host = getattr(instance, "remote_host", "remote host")
-
- # Make common gRPC errors more readable
- if "failed to connect to all addresses" in details:
- simplified = f"Failed to connect to remote host at {host} (Connection refused)"
- elif "Method not found" in details:
- simplified = f"Remote server at {host} is using an incompatible version"
- elif "Deadline Exceeded" in details:
- simplified = f"Request to {host} timed out"
- else:
- simplified = details
-
- raise ConnpyError(simplified)
- return wrapper
-
-class AIStub
-(channel, remote_host)
-class AIStub:
- def __init__(self, channel, remote_host):
- self.stub = connpy_pb2_grpc.AIServiceStub(channel)
- self.remote_host = remote_host
-
- def _ai_chat_stream(self, stub_method, input_text, dryrun=False, chat_history=None, session_id=None, debug=False, status=None, chunk_callback=None, **overrides):
- import queue
- from rich.prompt import Prompt
- from rich.text import Text
- from rich.panel import Panel
- from rich.markdown import Markdown
-
- req_queue = queue.Queue()
-
- initial_req = connpy_pb2.AskRequest(
- input_text=input_text,
- dryrun=dryrun,
- session_id=session_id or "",
- debug=debug,
- engineer_model=overrides.get("engineer_model", ""),
- engineer_api_key=overrides.get("engineer_api_key", ""),
- architect_model=overrides.get("architect_model", ""),
- architect_api_key=overrides.get("architect_api_key", ""),
- trust=overrides.get("trust", False)
- )
- if chat_history is not None:
- initial_req.chat_history.CopyFrom(to_value(chat_history))
- if "engineer_auth" in overrides and overrides["engineer_auth"]:
- initial_req.engineer_auth.CopyFrom(to_struct(overrides["engineer_auth"]))
- if "architect_auth" in overrides and overrides["architect_auth"]:
- initial_req.architect_auth.CopyFrom(to_struct(overrides["architect_auth"]))
-
- req_queue.put(initial_req)
-
- def request_generator():
- while True:
- req = req_queue.get()
- if req is None: break
- yield req
-
- responses = stub_method(request_generator())
-
- full_content = ""
- header_printed = False
- current_responder = "engineer"
- final_result = {"response": "", "chat_history": []}
-
- # Background thread to pull responses from gRPC into a local queue
- # This prevents KeyboardInterrupt from corrupting the gRPC iterator state
- response_queue = queue.Queue()
-
- def pull_responses():
- try:
- for response in responses:
- response_queue.put(("data", response))
- except Exception as e:
- response_queue.put(("error", e))
- finally:
- response_queue.put((None, None))
-
- threading.Thread(target=pull_responses, daemon=True).start()
-
- try:
- while True:
- try:
- # BLOCKING GET from local queue (interruptible by signal)
- msg_type, response = response_queue.get()
- except KeyboardInterrupt:
- # Signal interruption to the server
- if status:
- status.update("[error]Interrupted! Closing pending tasks...")
-
- # Send the interrupt signal to the server
- req_queue.put(connpy_pb2.AskRequest(interrupt=True))
-
- # CONTINUE the loop to receive remaining data and summary from the queue
- continue
-
- if msg_type is None: # Sentinel
- break
-
- if msg_type == "error":
- # Re-raise or handle gRPC error from background thread
- if isinstance(response, grpc.RpcError):
- raise response
- printer.warning(f"Stream interrupted: {response}")
- break
-
- if response.status_update:
- if response.status_update.startswith("__RESPONDER__:"):
- current_responder = response.status_update.split(":")[1].lower()
- continue
-
- if response.requires_confirmation:
- if status: status.stop()
-
- # Show prompt and wait for answer
- prompt_text = Text.from_ansi(response.status_update)
- ans = Prompt.ask(prompt_text)
-
- if status:
- status.update("[ai_status]Agent: Resuming...")
- status.start()
-
- req_queue.put(connpy_pb2.AskRequest(confirmation_answer=ans))
- continue
-
- if status:
- status.update(response.status_update)
- continue
-
- if response.debug_message:
- if debug:
- if status:
- try: status.stop()
- except: pass
- printer.console.print(Text.from_ansi(response.debug_message))
- if status:
- try: status.start()
- except: pass
- continue
-
- if response.important_message:
- if status:
- try: status.stop()
- except: pass
- printer.console.print(Text.from_ansi(response.important_message))
- if status:
- try: status.start()
- except: pass
- continue
-
- if not response.is_final:
- if response.text_chunk:
- if not header_printed:
- if status:
- try: status.stop()
- except: pass
-
- if chunk_callback:
- header_printed = True
- else:
- from rich.console import Console as RichConsole
- from rich.rule import Rule
- from ..printer import connpy_theme, get_original_stdout, IncrementalMarkdownParser
- stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
-
- # Print header on first chunk
- alias = "architect" if current_responder == "architect" else "engineer"
- role_label = "Network Architect" if current_responder == "architect" else "Network Engineer"
- stable_console.print(Rule(f"[bold {alias}]{role_label}[/bold {alias}]", style=alias))
- header_printed = True
-
- # Initialize parser
- md_parser = IncrementalMarkdownParser(console=stable_console)
-
- full_content += response.text_chunk
- if chunk_callback:
- chunk_callback(response.text_chunk)
- elif md_parser:
- md_parser.feed(response.text_chunk)
- continue
-
- if response.is_final:
- if not chunk_callback and header_printed:
- from rich.rule import Rule
- md_parser.flush()
-
- if status:
- try: status.stop()
- except: pass
-
- final_result = from_struct(response.full_result)
-
- if not chunk_callback and header_printed:
- from rich.console import Console as RichConsole
- from ..printer import connpy_theme, get_original_stdout
- stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
- stable_console.print(Rule(style=alias))
- break
- except Exception as e:
- # Check if it was a gRPC error that we should let handle_errors catch
- if isinstance(e, grpc.RpcError):
- raise
- printer.warning(f"Stream interrupted: {e}")
- finally:
- req_queue.put(None)
-
- if full_content:
- final_result["streamed"] = True
-
- return final_result
-
- @handle_errors
- def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debug=False, status=None, **overrides):
- return self._ai_chat_stream(self.stub.ask, input_text, dryrun=dryrun, chat_history=chat_history, session_id=session_id, debug=debug, status=status, **overrides)
-
- @handle_errors
- def build_playbook_chat(self, user_input, chat_history=None, status=None, chunk_callback=None):
- return self._ai_chat_stream(self.stub.build_playbook_chat, user_input, chat_history=chat_history, status=status, chunk_callback=chunk_callback)
-
- def _process_unary_stream(self, responses, status=None, chunk_callback=None):
- full_content = ""
- header_printed = False
- final_result = {"response": "", "chat_history": []}
- md_parser = None
-
- try:
- for response in responses:
- if response.status_update:
- if status:
- status.update(response.status_update)
- continue
-
- if response.important_message:
- if status:
- try: status.stop()
- except: pass
- printer.console.print(Text.from_ansi(response.important_message))
- if status:
- try: status.start()
- except: pass
- continue
-
- if not response.is_final:
- if response.text_chunk:
- if not header_printed:
- if status:
- try: status.stop()
- except: pass
-
- if chunk_callback:
- header_printed = True
- else:
- from rich.console import Console as RichConsole
- from rich.rule import Rule
- from ..printer import connpy_theme, get_original_stdout, IncrementalMarkdownParser
- stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
-
- # Print default header
- stable_console.print(Rule("[bold engineer]AI Analysis[/bold engineer]", style="engineer"))
- header_printed = True
- md_parser = IncrementalMarkdownParser(console=stable_console)
-
- full_content += response.text_chunk
- if chunk_callback:
- chunk_callback(response.text_chunk)
- elif md_parser:
- md_parser.feed(response.text_chunk)
- continue
-
- if response.is_final:
- if md_parser:
- md_parser.flush()
-
- if status:
- try: status.stop()
- except: pass
-
- final_result = from_struct(response.full_result)
-
- if md_parser:
- from rich.console import Console as RichConsole
- from rich.rule import Rule
- from ..printer import connpy_theme, get_original_stdout
- stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
- stable_console.print(Rule(style="engineer"))
- break
- except Exception as e:
- if isinstance(e, grpc.RpcError):
- raise
- printer.warning(f"Stream interrupted: {e}")
-
- if full_content:
- final_result["streamed"] = True
-
- return final_result
-
- @handle_errors
- def analyze_execution_results(self, results, query=None, status=None, chunk_callback=None):
- req = connpy_pb2.AnalyzeRequest(query=query or "")
- req.results.CopyFrom(to_struct(results))
- responses = self.stub.analyze_execution_results(req)
- return self._process_unary_stream(responses, status, chunk_callback)
-
- @handle_errors
- def predict_execution_results(self, target_nodes, commands, status=None, chunk_callback=None):
- req = connpy_pb2.PreflightRequest(target_nodes=target_nodes, commands=commands)
- responses = self.stub.predict_execution_results(req)
- return self._process_unary_stream(responses, status, chunk_callback)
-
- @handle_errors
- def confirm(self, input_text, console=None):
- return self.stub.confirm(connpy_pb2.StringRequest(value=input_text)).value
-
- @handle_errors
- def list_sessions(self, limit=None):
- from .utils import from_value
- res = self.stub.list_sessions(Empty())
- sessions = from_value(res.data) or []
- if limit and len(sessions) > limit:
- return sessions[:limit], len(sessions)
- return sessions, len(sessions)
-
- @handle_errors
- def delete_session(self, session_id):
- self.stub.delete_session(connpy_pb2.StringRequest(value=session_id))
-
- @handle_errors
- def configure_provider(self, provider, model=None, api_key=None, auth=None):
- req = connpy_pb2.ProviderRequest(provider=provider, model=model or "", api_key=api_key or "")
- if auth:
- req.auth.CopyFrom(to_struct(auth))
- self.stub.configure_provider(req)
-
- @handle_errors
- def configure_mcp(self, name, url=None, enabled=True, auto_load_on_os=None, remove=False):
- req = connpy_pb2.MCPRequest(
- name=name,
- url=url or "",
- enabled=enabled,
- auto_load_on_os=auto_load_on_os or "",
- remove=remove
- )
- self.stub.configure_mcp(req)
-
- @handle_errors
- def list_mcp_servers(self):
- res = self.stub.list_mcp_servers(Empty())
- return from_value(res.data) or {}
-
- @handle_errors
- def load_session_data(self, session_id):
- return from_struct(self.stub.load_session_data(connpy_pb2.StringRequest(value=session_id)).data)
-
-def analyze_execution_results(self, results, query=None, status=None, chunk_callback=None)
-@handle_errors
-def analyze_execution_results(self, results, query=None, status=None, chunk_callback=None):
- req = connpy_pb2.AnalyzeRequest(query=query or "")
- req.results.CopyFrom(to_struct(results))
- responses = self.stub.analyze_execution_results(req)
- return self._process_unary_stream(responses, status, chunk_callback)
-
-def ask(self,
input_text,
dryrun=False,
chat_history=None,
session_id=None,
debug=False,
status=None,
**overrides)
-@handle_errors
-def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debug=False, status=None, **overrides):
- return self._ai_chat_stream(self.stub.ask, input_text, dryrun=dryrun, chat_history=chat_history, session_id=session_id, debug=debug, status=status, **overrides)
-
-def build_playbook_chat(self, user_input, chat_history=None, status=None, chunk_callback=None)
-@handle_errors
-def build_playbook_chat(self, user_input, chat_history=None, status=None, chunk_callback=None):
- return self._ai_chat_stream(self.stub.build_playbook_chat, user_input, chat_history=chat_history, status=status, chunk_callback=chunk_callback)
-
-def configure_mcp(self, name, url=None, enabled=True, auto_load_on_os=None, remove=False)
-@handle_errors
-def configure_mcp(self, name, url=None, enabled=True, auto_load_on_os=None, remove=False):
- req = connpy_pb2.MCPRequest(
- name=name,
- url=url or "",
- enabled=enabled,
- auto_load_on_os=auto_load_on_os or "",
- remove=remove
- )
- self.stub.configure_mcp(req)
-
-def configure_provider(self, provider, model=None, api_key=None, auth=None)
-@handle_errors
-def configure_provider(self, provider, model=None, api_key=None, auth=None):
- req = connpy_pb2.ProviderRequest(provider=provider, model=model or "", api_key=api_key or "")
- if auth:
- req.auth.CopyFrom(to_struct(auth))
- self.stub.configure_provider(req)
-
-def confirm(self, input_text, console=None)
-@handle_errors
-def confirm(self, input_text, console=None):
- return self.stub.confirm(connpy_pb2.StringRequest(value=input_text)).value
-
-def delete_session(self, session_id)
-@handle_errors
-def delete_session(self, session_id):
- self.stub.delete_session(connpy_pb2.StringRequest(value=session_id))
-
-def list_mcp_servers(self)
-@handle_errors
-def list_mcp_servers(self):
- res = self.stub.list_mcp_servers(Empty())
- return from_value(res.data) or {}
-
-def list_sessions(self, limit=None)
-@handle_errors
-def list_sessions(self, limit=None):
- from .utils import from_value
- res = self.stub.list_sessions(Empty())
- sessions = from_value(res.data) or []
- if limit and len(sessions) > limit:
- return sessions[:limit], len(sessions)
- return sessions, len(sessions)
-
-def load_session_data(self, session_id)
-@handle_errors
-def load_session_data(self, session_id):
- return from_struct(self.stub.load_session_data(connpy_pb2.StringRequest(value=session_id)).data)
-
-def predict_execution_results(self, target_nodes, commands, status=None, chunk_callback=None)
-@handle_errors
-def predict_execution_results(self, target_nodes, commands, status=None, chunk_callback=None):
- req = connpy_pb2.PreflightRequest(target_nodes=target_nodes, commands=commands)
- responses = self.stub.predict_execution_results(req)
- return self._process_unary_stream(responses, status, chunk_callback)
-
-class AuthClientInterceptor
-(token_provider)
-class AuthClientInterceptor(grpc.UnaryUnaryClientInterceptor,
- grpc.UnaryStreamClientInterceptor,
- grpc.StreamUnaryClientInterceptor,
- grpc.StreamStreamClientInterceptor):
- def __init__(self, token_provider):
- self.token_provider = token_provider
-
- def _add_metadata(self, client_call_details):
- token = self.token_provider()
- if not token:
- return client_call_details
-
- metadata = []
- if client_call_details.metadata:
- metadata = list(client_call_details.metadata)
-
- # Check if already present to avoid duplicates
- if not any(k.lower() == "authorization" for k, v in metadata):
- metadata.append(("authorization", f"Bearer {token}"))
-
- return _ClientCallDetails(
- method=client_call_details.method,
- timeout=client_call_details.timeout,
- metadata=metadata,
- credentials=client_call_details.credentials,
- wait_for_ready=client_call_details.wait_for_ready,
- compression=client_call_details.compression,
- )
-
- def intercept_unary_unary(self, continuation, client_call_details, request):
- new_details = self._add_metadata(client_call_details)
- return continuation(new_details, request)
-
- def intercept_unary_stream(self, continuation, client_call_details, request):
- new_details = self._add_metadata(client_call_details)
- return continuation(new_details, request)
-
- def intercept_stream_unary(self, continuation, client_call_details, request_iterator):
- new_details = self._add_metadata(client_call_details)
- return continuation(new_details, request_iterator)
-
- def intercept_stream_stream(self, continuation, client_call_details, request_iterator):
- new_details = self._add_metadata(client_call_details)
- return continuation(new_details, request_iterator)
-Affords intercepting unary-unary invocations.
-def intercept_stream_stream(self, continuation, client_call_details, request_iterator)
-def intercept_stream_stream(self, continuation, client_call_details, request_iterator):
- new_details = self._add_metadata(client_call_details)
- return continuation(new_details, request_iterator)
-Intercepts a stream-stream invocation.
-continuationresponse_iterator = continuation(client_call_details, request_iterator)
-to continue with the RPC. continuation returns an object that is
-both a Call for the RPC and an iterator for response values.
-Drawing response values from the returned Call-iterator may
-raise RpcError indicating termination of the RPC with non-OK
-status.client_call_detailsrequest_iteratorAn object that is both a Call for the RPC and an iterator of -response values. Drawing response values from the returned -Call-iterator may raise RpcError indicating termination of -the RPC with non-OK status. This object should also fulfill the -Future interface, though it may not.
-def intercept_stream_unary(self, continuation, client_call_details, request_iterator)
-def intercept_stream_unary(self, continuation, client_call_details, request_iterator):
- new_details = self._add_metadata(client_call_details)
- return continuation(new_details, request_iterator)
-Intercepts a stream-unary invocation asynchronously.
-continuationresponse_future = continuation(client_call_details, request_iterator)
-to continue with the RPC. continuation returns an object that is
-both a Call for the RPC and a Future. In the event of RPC completion,
-the return Call-Future's result value will be the response message
-of the RPC. Should the event terminate with non-OK status, the
-returned Call-Future's exception value will be an RpcError.client_call_detailsrequest_iteratorAn object that is both a Call for the RPC and a Future. -In the event of RPC completion, the return Call-Future's -result value will be the response message of the RPC. -Should the event terminate with non-OK status, the returned -Call-Future's exception value will be an RpcError.
-def intercept_unary_stream(self, continuation, client_call_details, request)
-def intercept_unary_stream(self, continuation, client_call_details, request):
- new_details = self._add_metadata(client_call_details)
- return continuation(new_details, request)
-Intercepts a unary-stream invocation.
-continuationresponse_iterator = continuation(client_call_details, request)
-to continue with the RPC. continuation returns an object that is
-both a Call for the RPC and an iterator for response values.
-Drawing response values from the returned Call-iterator may
-raise RpcError indicating termination of the RPC with non-OK
-status.client_call_detailsrequestAn object that is both a Call for the RPC and an iterator of -response values. Drawing response values from the returned -Call-iterator may raise RpcError indicating termination of -the RPC with non-OK status. This object should also fulfill the -Future interface, though it may not.
-def intercept_unary_unary(self, continuation, client_call_details, request)
-def intercept_unary_unary(self, continuation, client_call_details, request):
- new_details = self._add_metadata(client_call_details)
- return continuation(new_details, request)
-Intercepts a unary-unary invocation asynchronously.
-continuationresponse_future = continuation(client_call_details, request)
-to continue with the RPC. continuation returns an object that is
-both a Call for the RPC and a Future. In the event of RPC
-completion, the return Call-Future's result value will be
-the response message of the RPC. Should the event terminate
-with non-OK status, the returned Call-Future's exception value
-will be an RpcError.client_call_detailsrequestAn object that is both a Call for the RPC and a Future. -In the event of RPC completion, the return Call-Future's -result value will be the response message of the RPC. -Should the event terminate with non-OK status, the returned -Call-Future's exception value will be an RpcError.
-class AuthStub
-(channel, remote_host)
-class AuthStub:
- def __init__(self, channel, remote_host):
- self.stub = connpy_pb2_grpc.AuthServiceStub(channel)
- self.remote_host = remote_host
-
- @handle_errors
- def login(self, username, password):
- req = connpy_pb2.LoginRequest(username=username, password=password)
- resp = self.stub.login(req)
- return {
- "token": resp.token,
- "username": resp.username,
- "expires_at": resp.expires_at
- }
-
- @handle_errors
- def change_password(self, old_password, new_password):
- req = connpy_pb2.ChangePasswordRequest(old_password=old_password, new_password=new_password)
- self.stub.change_password(req)
-
- @handle_errors
- def create_api_token(self, name, expires_in_days=0):
- req = connpy_pb2.CreateApiTokenRequest(name=name, expires_in_days=expires_in_days)
- resp = self.stub.create_api_token(req)
- return {
- "token_id": resp.token_id,
- "raw_token": resp.raw_token,
- "name": resp.name,
- }
-
- @handle_errors
- def list_api_tokens(self):
- resp = self.stub.list_api_tokens(Empty())
- return [
- {
- "token_id": t.token_id,
- "name": t.name,
- "token_prefix": t.token_prefix,
- "created_at": t.created_at,
- "last_used_at": t.last_used_at,
- "expires_at": t.expires_at,
- }
- for t in resp.tokens
- ]
-
- @handle_errors
- def revoke_api_token(self, token_id):
- req = connpy_pb2.RevokeApiTokenRequest(token_id=token_id)
- self.stub.revoke_api_token(req)
-
-def change_password(self, old_password, new_password)
-@handle_errors
-def change_password(self, old_password, new_password):
- req = connpy_pb2.ChangePasswordRequest(old_password=old_password, new_password=new_password)
- self.stub.change_password(req)
-
-def create_api_token(self, name, expires_in_days=0)
-@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)
-@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)
-@handle_errors
-def login(self, username, password):
- req = connpy_pb2.LoginRequest(username=username, password=password)
- resp = self.stub.login(req)
- return {
- "token": resp.token,
- "username": resp.username,
- "expires_at": resp.expires_at
- }
-
-def revoke_api_token(self, token_id)
-@handle_errors
-def revoke_api_token(self, token_id):
- req = connpy_pb2.RevokeApiTokenRequest(token_id=token_id)
- self.stub.revoke_api_token(req)
-
-class ConfigStub
-(channel, remote_host)
-class ConfigStub:
- def __init__(self, channel, remote_host):
- self.stub = connpy_pb2_grpc.ConfigServiceStub(channel)
- self.remote_host = remote_host
-
- @handle_errors
- def get_settings(self):
- return from_struct(self.stub.get_settings(Empty()).data)
-
- @handle_errors
- def update_setting(self, key, value):
- self.stub.update_setting(connpy_pb2.UpdateRequest(key=key, value=to_value(value)))
-
- @handle_errors
- def get_default_dir(self):
- return self.stub.get_default_dir(Empty()).value
-
- @handle_errors
- def set_config_folder(self, folder):
- self.stub.set_config_folder(connpy_pb2.StringRequest(value=folder))
-
- @handle_errors
- def encrypt_password(self, password):
- return self.stub.encrypt_password(connpy_pb2.StringRequest(value=password)).value
-
-def encrypt_password(self, password)
-@handle_errors
-def encrypt_password(self, password):
- return self.stub.encrypt_password(connpy_pb2.StringRequest(value=password)).value
-
-def get_default_dir(self)
-@handle_errors
-def get_default_dir(self):
- return self.stub.get_default_dir(Empty()).value
-
-def get_settings(self)
-@handle_errors
-def get_settings(self):
- return from_struct(self.stub.get_settings(Empty()).data)
-
-def set_config_folder(self, folder)
-@handle_errors
-def set_config_folder(self, folder):
- self.stub.set_config_folder(connpy_pb2.StringRequest(value=folder))
-
-def update_setting(self, key, value)
-@handle_errors
-def update_setting(self, key, value):
- self.stub.update_setting(connpy_pb2.UpdateRequest(key=key, value=to_value(value)))
-
-class ExecutionStub
-(channel, remote_host)
-class ExecutionStub:
- def __init__(self, channel, remote_host):
- self.stub = connpy_pb2_grpc.ExecutionServiceStub(channel)
- self.remote_host = remote_host
-
- @handle_errors
- def run_commands(self, nodes_filter, commands, variables=None, parallel=10, timeout=10, folder=None, prompt=None, **kwargs):
- nodes_list = [nodes_filter] if isinstance(nodes_filter, str) else list(nodes_filter)
- req = connpy_pb2.RunRequest(
- nodes=nodes_list,
- commands=commands,
- folder=folder or "",
- prompt=prompt or "",
- parallel=parallel,
- timeout=timeout,
- name=kwargs.get("name", "")
- )
- if variables is not None:
- req.vars.CopyFrom(to_struct(variables))
-
- final_results = {}
- on_complete = kwargs.get("on_node_complete")
-
- for response in self.stub.run_commands(req):
- if on_complete:
- on_complete(response.unique_id, response.output, response.status)
- final_results[response.unique_id] = {
- "output": response.output,
- "status": response.status
- }
-
- return final_results
-
- @handle_errors
- def test_commands(self, nodes_filter, commands, expected, variables=None, parallel=10, timeout=10, prompt=None, **kwargs):
- nodes_list = [nodes_filter] if isinstance(nodes_filter, str) else list(nodes_filter)
- req = connpy_pb2.TestRequest(
- nodes=nodes_list,
- commands=commands,
- expected=expected if isinstance(expected, list) else [expected],
- folder=kwargs.get("folder", ""),
- prompt=prompt or "",
- parallel=parallel,
- timeout=timeout,
- name=kwargs.get("name", "")
- )
- if variables is not None:
- req.vars.CopyFrom(to_struct(variables))
-
- final_results = {}
- on_complete = kwargs.get("on_node_complete")
-
- for response in self.stub.test_commands(req):
- result_dict = from_struct(response.test_result) if response.HasField("test_result") else {}
- if on_complete:
- on_complete(response.unique_id, response.output, response.status, result_dict)
- final_results[response.unique_id] = result_dict
-
- return final_results
-
- @handle_errors
- def run_cli_script(self, nodes_filter, script_path, parallel=10):
- req = connpy_pb2.ScriptRequest(param1=nodes_filter, param2=script_path, parallel=parallel)
- return from_struct(self.stub.run_cli_script(req).data)
-
-def run_cli_script(self, nodes_filter, script_path, parallel=10)
-@handle_errors
-def run_cli_script(self, nodes_filter, script_path, parallel=10):
- req = connpy_pb2.ScriptRequest(param1=nodes_filter, param2=script_path, parallel=parallel)
- return from_struct(self.stub.run_cli_script(req).data)
-
-def run_commands(self,
nodes_filter,
commands,
variables=None,
parallel=10,
timeout=10,
folder=None,
prompt=None,
**kwargs)
-@handle_errors
-def run_commands(self, nodes_filter, commands, variables=None, parallel=10, timeout=10, folder=None, prompt=None, **kwargs):
- nodes_list = [nodes_filter] if isinstance(nodes_filter, str) else list(nodes_filter)
- req = connpy_pb2.RunRequest(
- nodes=nodes_list,
- commands=commands,
- folder=folder or "",
- prompt=prompt or "",
- parallel=parallel,
- timeout=timeout,
- name=kwargs.get("name", "")
- )
- if variables is not None:
- req.vars.CopyFrom(to_struct(variables))
-
- final_results = {}
- on_complete = kwargs.get("on_node_complete")
-
- for response in self.stub.run_commands(req):
- if on_complete:
- on_complete(response.unique_id, response.output, response.status)
- final_results[response.unique_id] = {
- "output": response.output,
- "status": response.status
- }
-
- return final_results
-
-def test_commands(self,
nodes_filter,
commands,
expected,
variables=None,
parallel=10,
timeout=10,
prompt=None,
**kwargs)
-@handle_errors
-def test_commands(self, nodes_filter, commands, expected, variables=None, parallel=10, timeout=10, prompt=None, **kwargs):
- nodes_list = [nodes_filter] if isinstance(nodes_filter, str) else list(nodes_filter)
- req = connpy_pb2.TestRequest(
- nodes=nodes_list,
- commands=commands,
- expected=expected if isinstance(expected, list) else [expected],
- folder=kwargs.get("folder", ""),
- prompt=prompt or "",
- parallel=parallel,
- timeout=timeout,
- name=kwargs.get("name", "")
- )
- if variables is not None:
- req.vars.CopyFrom(to_struct(variables))
-
- final_results = {}
- on_complete = kwargs.get("on_node_complete")
-
- for response in self.stub.test_commands(req):
- result_dict = from_struct(response.test_result) if response.HasField("test_result") else {}
- if on_complete:
- on_complete(response.unique_id, response.output, response.status, result_dict)
- final_results[response.unique_id] = result_dict
-
- return final_results
-
-class ImportExportStub
-(channel, remote_host)
-class ImportExportStub:
- def __init__(self, channel, remote_host):
- self.stub = connpy_pb2_grpc.ImportExportServiceStub(channel)
- self.remote_host = remote_host
-
- @handle_errors
- def export_to_file(self, file_path, folders=None):
- req = connpy_pb2.ExportRequest(file_path=file_path, folders=folders or [])
- self.stub.export_to_file(req)
-
- @handle_errors
- def import_from_file(self, file_path):
- with open(file_path, "r") as f:
- content = f.read()
- # Marker to tell the server this is content, not a path
- marker_content = f"---YAML---\n{content}"
- self.stub.import_from_file(connpy_pb2.StringRequest(value=marker_content))
-
- @handle_errors
- def set_reserved_names(self, names):
- self.stub.set_reserved_names(connpy_pb2.ListRequest(items=names))
-
-def export_to_file(self, file_path, folders=None)
-@handle_errors
-def export_to_file(self, file_path, folders=None):
- req = connpy_pb2.ExportRequest(file_path=file_path, folders=folders or [])
- self.stub.export_to_file(req)
-
-def import_from_file(self, file_path)
-@handle_errors
-def import_from_file(self, file_path):
- with open(file_path, "r") as f:
- content = f.read()
- # Marker to tell the server this is content, not a path
- marker_content = f"---YAML---\n{content}"
- self.stub.import_from_file(connpy_pb2.StringRequest(value=marker_content))
-
-def set_reserved_names(self, names)
-@handle_errors
-def set_reserved_names(self, names):
- self.stub.set_reserved_names(connpy_pb2.ListRequest(items=names))
-
-class NodeStub
-(channel, remote_host, config=None)
-class NodeStub:
- def __init__(self, channel, remote_host, config=None):
- self.stub = connpy_pb2_grpc.NodeServiceStub(channel)
- self.remote_host = remote_host
- self.config = config
-
- def _handle_remote_copilot(self, res, request_queue, response_queue, client_buffer_bytes, pause_generator, resume_generator, old_tty):
- import json, asyncio, termios, sys, tty, queue, os
- from ..core import copilot_terminal_mode
- from . import connpy_pb2
-
- pause_generator()
-
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
-
- node_info = json.loads(res.copilot_node_info_json) if res.copilot_node_info_json else {}
- blocks = node_info.get("context_blocks", [])
-
- interface = CopilotInterface(
- self.config,
- history=getattr(self, 'copilot_history', None),
- session_state=getattr(self, 'copilot_state', None)
- )
- self.copilot_history = interface.history
- self.copilot_state = interface.session_state
- interface.session_state['banner_shown'] = False
-
- async def on_ai_call_remote(active_buffer, question, chunk_callback, merged_node_info):
- # Send request to server
- request_queue.put(connpy_pb2.InteractRequest(
- copilot_question=question,
- copilot_context_buffer=active_buffer,
- copilot_node_info_json=json.dumps(merged_node_info)
- ))
- # Wait for chunks from server
- while True:
- try:
- chunk_res = response_queue.get(timeout=0.1)
- if chunk_res is None: return {"error": "Server disconnected"}
- if chunk_res.copilot_stream_chunk:
- chunk_callback(chunk_res.copilot_stream_chunk)
- elif chunk_res.copilot_response_json:
- return json.loads(chunk_res.copilot_response_json)
- except queue.Empty:
- await asyncio.sleep(0.05)
-
- # Wrap in async loop
- async def run_remote_copilot():
- nonlocal blocks, node_info
- while True:
- action, commands, custom_cmd = await interface.run_session(
- raw_bytes=bytes(client_buffer_bytes),
- node_info=node_info,
- on_ai_call=on_ai_call_remote,
- blocks=blocks
- )
-
- if action == "continue":
- # Send continue signal to server to loop back for another question
- request_queue.put(connpy_pb2.InteractRequest(copilot_action="continue"))
- continue
-
- if action in ("send_all", "custom"):
- action_sent = "cancel"
- if action == "send_all" and commands:
- action_sent = f"custom:{chr(10).join(commands)}"
- elif action == "custom" and custom_cmd:
- action_sent = f"custom:{chr(10).join(custom_cmd)}"
- request_queue.put(connpy_pb2.InteractRequest(copilot_action=action_sent))
-
- print("\r\n\033[2m [Remote] Ejecutando comandos y esperando al prompt...\033[0m\r\n", flush=True)
- while True:
- try:
- prompt_res = response_queue.get(timeout=0.1)
- if prompt_res is None:
- return "cancel", None, None
- if prompt_res.stdout_data:
- os.write(sys.stdout.fileno(), prompt_res.stdout_data)
- client_buffer_bytes.extend(prompt_res.stdout_data)
- if prompt_res.copilot_prompt:
- if prompt_res.copilot_node_info_json:
- node_info = json.loads(prompt_res.copilot_node_info_json)
- blocks = node_info.get("context_blocks", [])
- break
- except queue.Empty:
- await asyncio.sleep(0.05)
- continue
-
- return action, commands, custom_cmd
-
- with copilot_terminal_mode():
- action, commands, custom_cmd = asyncio.run(run_remote_copilot())
-
- print("\033[2m Returning to session...\033[0m", flush=True)
- # Prepare final action for server
- request_queue.put(connpy_pb2.InteractRequest(copilot_action="cancel"))
- resume_generator()
- tty.setraw(sys.stdin.fileno())
-
- @handle_errors
- def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
- import sys
- import select
- import tty
- import termios
- import queue
- import os
- import threading
-
- request_queue = queue.Queue()
- client_buffer_bytes = bytearray()
- pause_stdin = [False]
- wake_r, wake_w = os.pipe()
-
- def pause_generator():
- pause_stdin[0] = True
- os.write(wake_w, b'\x00')
-
- def resume_generator():
- pause_stdin[0] = False
-
- def request_generator():
- cols, rows = 80, 24
- try:
- size = os.get_terminal_size()
- cols, rows = size.columns, size.lines
- except OSError:
- pass
-
- yield connpy_pb2.InteractRequest(
- id=unique_id, sftp=sftp, debug=debug, cols=cols, rows=rows
- )
-
- while True:
- try:
- while True:
- req = request_queue.get_nowait()
- if req is None:
- return
- yield req
- except queue.Empty:
- pass
-
- if pause_stdin[0]:
- import time
- time.sleep(0.05)
- continue
-
- r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
- if wake_r in r:
- os.read(wake_r, 1)
- continue
- if sys.stdin.fileno() in r and not pause_stdin[0]:
- try:
- data = os.read(sys.stdin.fileno(), 1024)
- if not data:
- break
- yield connpy_pb2.InteractRequest(stdin_data=data)
- except OSError:
- break
-
- # Fetch node details for the connection message
- try:
- node_details = self.get_node_details(unique_id)
- host = node_details.get("host", "unknown")
- port = str(node_details.get("port", ""))
- protocol = "sftp" if sftp else node_details.get("protocol", "ssh")
- port_str = f":{port}" if port and protocol not in ["ssm", "kubectl", "docker"] else ""
- conn_msg = f"Connected to {unique_id} at {host}{port_str} via: {protocol}"
- except Exception:
- conn_msg = f"Connected to {unique_id}"
-
- old_tty = termios.tcgetattr(sys.stdin)
- try:
- import time
- tty.setraw(sys.stdin.fileno())
- response_iterator = self.stub.interact_node(request_generator())
-
- import queue
- response_queue = queue.Queue()
-
- def response_consumer():
- try:
- for r in response_iterator:
- response_queue.put(r)
- except Exception:
- pass
- response_queue.put(None)
-
- t_consumer = threading.Thread(target=response_consumer, daemon=True)
- t_consumer.start()
-
- # First phase: Wait for connection status, print early data
- try:
- while True:
- res = response_queue.get()
- if res is None:
- return
- if res.stdout_data:
- data = res.stdout_data
- if debug:
- data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
- os.write(sys.stdout.fileno(), data)
-
- if res.success:
- # Connection established on server, show success message
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- printer.success(conn_msg)
- pause_stdin[0] = False
- tty.setraw(sys.stdin.fileno())
- break
-
- if res.error_message:
- # Connection failed on server
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- printer.error(f"Connection failed: {res.error_message}")
- return
- except queue.Empty:
- return
-
- # Second phase: Stream active session
- # Clear screen filter is only applied before success (Phase 1).
- # Once the user has a prompt, Ctrl+L must work normally.
- while True:
- res = response_queue.get()
- if res is None:
- break
- if res.copilot_prompt:
- self._handle_remote_copilot(
- res, request_queue, response_queue,
- client_buffer_bytes,
- pause_generator, resume_generator, old_tty
- )
- continue
-
- if res.stdout_data:
- os.write(sys.stdout.fileno(), res.stdout_data)
- client_buffer_bytes.extend(res.stdout_data)
- finally:
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- os.close(wake_r)
- os.close(wake_w)
-
- @handle_errors
- def connect_dynamic(self, connection_params, debug=False):
- import sys
- import select
- import tty
- import termios
- import queue
- import os
- import json
-
- params_json = json.dumps(connection_params)
- request_queue = queue.Queue()
- client_buffer_bytes = bytearray()
- pause_stdin = [False]
- wake_r, wake_w = os.pipe()
-
- def pause_generator():
- pause_stdin[0] = True
- os.write(wake_w, b'\x00')
-
- def resume_generator():
- pause_stdin[0] = False
-
- def request_generator():
- cols, rows = 80, 24
- try:
- size = os.get_terminal_size()
- cols, rows = size.columns, size.lines
- except OSError:
- pass
-
- yield connpy_pb2.InteractRequest(
- id="dynamic", debug=debug, cols=cols, rows=rows,
- connection_params_json=params_json
- )
-
- while True:
- try:
- while True:
- req = request_queue.get_nowait()
- if req is None:
- return
- yield req
- except queue.Empty:
- pass
-
- if pause_stdin[0]:
- import time
- time.sleep(0.05)
- continue
-
- r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
- if wake_r in r:
- os.read(wake_r, 1)
- continue
- if sys.stdin.fileno() in r and not pause_stdin[0]:
- try:
- data = os.read(sys.stdin.fileno(), 1024)
- if not data:
- break
- yield connpy_pb2.InteractRequest(stdin_data=data)
- except OSError:
- break
-
- # Prepare connection message
- try:
- node_name = connection_params.get("name", "dynamic@remote")
- host = connection_params.get("host", "dynamic")
- port = str(connection_params.get("port", ""))
- protocol = connection_params.get("protocol", "ssh")
- port_str = f":{port}" if port and protocol not in ["ssm", "kubectl", "docker"] else ""
- conn_msg = f"Connected to {node_name} at {host}{port_str} via: {protocol}"
- except Exception:
- node_name = connection_params.get("name", "dynamic@remote") if isinstance(connection_params, dict) else "dynamic@remote"
- conn_msg = f"Connected to {node_name}"
-
- old_tty = termios.tcgetattr(sys.stdin)
- try:
- import time
- tty.setraw(sys.stdin.fileno())
- response_iterator = self.stub.interact_node(request_generator())
-
- import queue
- response_queue = queue.Queue()
-
- def response_consumer():
- try:
- for r in response_iterator:
- response_queue.put(r)
- except Exception:
- pass
- response_queue.put(None)
-
- t_consumer = threading.Thread(target=response_consumer, daemon=True)
- t_consumer.start()
-
- # First phase: Wait for connection status, print early data
- try:
- while True:
- res = response_queue.get()
- if res is None:
- return
- if res.stdout_data:
- data = res.stdout_data
- if debug:
- data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
- os.write(sys.stdout.fileno(), data)
-
- if res.success:
- # Connection established on server, show success message
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- printer.success(conn_msg)
- pause_stdin[0] = False
- tty.setraw(sys.stdin.fileno())
- break
-
- if res.error_message:
- # Connection failed on server
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- printer.error(f"Connection failed: {res.error_message}")
- return
- except queue.Empty:
- return
-
- # Second phase: Stream active session
- while True:
- res = response_queue.get()
- if res is None:
- break
- if res.copilot_prompt:
- self._handle_remote_copilot(
- res, request_queue, response_queue,
- client_buffer_bytes,
- pause_generator, resume_generator, old_tty
- )
- continue
-
- if res.stdout_data:
- os.write(sys.stdout.fileno(), res.stdout_data)
- client_buffer_bytes.extend(res.stdout_data)
- finally:
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- os.close(wake_r)
- os.close(wake_w)
-
- @MethodHook
- @handle_errors
- def list_nodes(self, filter_str=None, format_str=None):
- req = connpy_pb2.FilterRequest(filter_str=filter_str or "", format_str=format_str or "")
- return from_value(self.stub.list_nodes(req).data) or []
-
- @MethodHook
- @handle_errors
- def list_folders(self, filter_str=None):
- req = connpy_pb2.FilterRequest(filter_str=filter_str or "")
- return from_value(self.stub.list_folders(req).data) or []
-
- @handle_errors
- def get_node_details(self, unique_id):
- return from_struct(self.stub.get_node_details(connpy_pb2.IdRequest(id=unique_id)).data)
-
- @handle_errors
- def explode_unique(self, unique_id):
- return from_value(self.stub.explode_unique(connpy_pb2.IdRequest(id=unique_id)).data)
-
- @handle_errors
- def validate_parent_folder(self, unique_id):
- self.stub.validate_parent_folder(connpy_pb2.IdRequest(id=unique_id))
-
- @handle_errors
- def generate_cache(self, nodes=None, folders=None, profiles=None):
- # 1. Update remote cache on server
- self.stub.generate_cache(Empty())
-
- # 2. Update local fzf/text cache files
- # If no data provided, we fetch it all from remote to sync local files
- if nodes is None and folders is None and profiles is None:
- nodes = self.list_nodes()
- folders = self.list_folders()
- # We don't have direct access to ProfileStub here, but usually
- # node cache is what matters for fzf. We'll fetch profiles if we can.
- # For now, let's sync what we have.
-
- if nodes is not None or folders is not None or profiles is not None:
- self.config._generate_nodes_cache(nodes=nodes, folders=folders, profiles=profiles)
-
- def _trigger_local_cache_sync(self):
- """Helper to fetch remote data and update local fzf cache files after a change."""
- try:
- nodes = self.list_nodes()
- folders = self.list_folders()
- self.generate_cache(nodes=nodes, folders=folders)
- except Exception:
- # Failure to sync cache shouldn't break the main operation's success feedback
- pass
-
- @handle_errors
- def add_node(self, unique_id, data, is_folder=False):
- req = connpy_pb2.NodeRequest(id=unique_id, data=to_struct(data), is_folder=is_folder)
- self.stub.add_node(req)
- self._trigger_local_cache_sync()
-
- @handle_errors
- def update_node(self, unique_id, data, save=True):
- req = connpy_pb2.NodeRequest(id=unique_id, data=to_struct(data), is_folder=False)
- self.stub.update_node(req)
- if save:
- self._trigger_local_cache_sync()
-
- @handle_errors
- def delete_node(self, unique_id, is_folder=False, save=True):
- req = connpy_pb2.DeleteRequest(id=unique_id, is_folder=is_folder)
- self.stub.delete_node(req)
- if save:
- self._trigger_local_cache_sync()
-
- @handle_errors
- def move_node(self, src_id, dst_id, copy=False):
- req = connpy_pb2.MoveRequest(src_id=src_id, dst_id=dst_id, copy=copy)
- self.stub.move_node(req)
- self._trigger_local_cache_sync()
-
- @handle_errors
- def bulk_add(self, ids, hosts, common_data):
- req = connpy_pb2.BulkRequest(ids=ids, hosts=hosts, common_data=to_struct(common_data))
- self.stub.bulk_add(req)
- self._trigger_local_cache_sync()
-
- @handle_errors
- def set_reserved_names(self, names):
- self.stub.set_reserved_names(connpy_pb2.ListRequest(items=names))
- self._trigger_local_cache_sync()
-
- @handle_errors
- def full_replace(self, connections, profiles):
- req = connpy_pb2.FullReplaceRequest(
- connections=to_struct(connections),
- profiles=to_struct(profiles)
- )
- self.stub.full_replace(req)
- self._trigger_local_cache_sync()
-
- @handle_errors
- def get_inventory(self):
- resp = self.stub.get_inventory(Empty())
- return {
- "connections": from_struct(resp.connections),
- "profiles": from_struct(resp.profiles)
- }
-
-def add_node(self, unique_id, data, is_folder=False)
-@handle_errors
-def add_node(self, unique_id, data, is_folder=False):
- req = connpy_pb2.NodeRequest(id=unique_id, data=to_struct(data), is_folder=is_folder)
- self.stub.add_node(req)
- self._trigger_local_cache_sync()
-
-def bulk_add(self, ids, hosts, common_data)
-@handle_errors
-def bulk_add(self, ids, hosts, common_data):
- req = connpy_pb2.BulkRequest(ids=ids, hosts=hosts, common_data=to_struct(common_data))
- self.stub.bulk_add(req)
- self._trigger_local_cache_sync()
-
-def connect_dynamic(self, connection_params, debug=False)
-@handle_errors
-def connect_dynamic(self, connection_params, debug=False):
- import sys
- import select
- import tty
- import termios
- import queue
- import os
- import json
-
- params_json = json.dumps(connection_params)
- request_queue = queue.Queue()
- client_buffer_bytes = bytearray()
- pause_stdin = [False]
- wake_r, wake_w = os.pipe()
-
- def pause_generator():
- pause_stdin[0] = True
- os.write(wake_w, b'\x00')
-
- def resume_generator():
- pause_stdin[0] = False
-
- def request_generator():
- cols, rows = 80, 24
- try:
- size = os.get_terminal_size()
- cols, rows = size.columns, size.lines
- except OSError:
- pass
-
- yield connpy_pb2.InteractRequest(
- id="dynamic", debug=debug, cols=cols, rows=rows,
- connection_params_json=params_json
- )
-
- while True:
- try:
- while True:
- req = request_queue.get_nowait()
- if req is None:
- return
- yield req
- except queue.Empty:
- pass
-
- if pause_stdin[0]:
- import time
- time.sleep(0.05)
- continue
-
- r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
- if wake_r in r:
- os.read(wake_r, 1)
- continue
- if sys.stdin.fileno() in r and not pause_stdin[0]:
- try:
- data = os.read(sys.stdin.fileno(), 1024)
- if not data:
- break
- yield connpy_pb2.InteractRequest(stdin_data=data)
- except OSError:
- break
-
- # Prepare connection message
- try:
- node_name = connection_params.get("name", "dynamic@remote")
- host = connection_params.get("host", "dynamic")
- port = str(connection_params.get("port", ""))
- protocol = connection_params.get("protocol", "ssh")
- port_str = f":{port}" if port and protocol not in ["ssm", "kubectl", "docker"] else ""
- conn_msg = f"Connected to {node_name} at {host}{port_str} via: {protocol}"
- except Exception:
- node_name = connection_params.get("name", "dynamic@remote") if isinstance(connection_params, dict) else "dynamic@remote"
- conn_msg = f"Connected to {node_name}"
-
- old_tty = termios.tcgetattr(sys.stdin)
- try:
- import time
- tty.setraw(sys.stdin.fileno())
- response_iterator = self.stub.interact_node(request_generator())
-
- import queue
- response_queue = queue.Queue()
-
- def response_consumer():
- try:
- for r in response_iterator:
- response_queue.put(r)
- except Exception:
- pass
- response_queue.put(None)
-
- t_consumer = threading.Thread(target=response_consumer, daemon=True)
- t_consumer.start()
-
- # First phase: Wait for connection status, print early data
- try:
- while True:
- res = response_queue.get()
- if res is None:
- return
- if res.stdout_data:
- data = res.stdout_data
- if debug:
- data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
- os.write(sys.stdout.fileno(), data)
-
- if res.success:
- # Connection established on server, show success message
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- printer.success(conn_msg)
- pause_stdin[0] = False
- tty.setraw(sys.stdin.fileno())
- break
-
- if res.error_message:
- # Connection failed on server
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- printer.error(f"Connection failed: {res.error_message}")
- return
- except queue.Empty:
- return
-
- # Second phase: Stream active session
- while True:
- res = response_queue.get()
- if res is None:
- break
- if res.copilot_prompt:
- self._handle_remote_copilot(
- res, request_queue, response_queue,
- client_buffer_bytes,
- pause_generator, resume_generator, old_tty
- )
- continue
-
- if res.stdout_data:
- os.write(sys.stdout.fileno(), res.stdout_data)
- client_buffer_bytes.extend(res.stdout_data)
- finally:
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- os.close(wake_r)
- os.close(wake_w)
-
-def connect_node(self, unique_id, sftp=False, debug=False, logger=None)
-@handle_errors
-def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
- import sys
- import select
- import tty
- import termios
- import queue
- import os
- import threading
-
- request_queue = queue.Queue()
- client_buffer_bytes = bytearray()
- pause_stdin = [False]
- wake_r, wake_w = os.pipe()
-
- def pause_generator():
- pause_stdin[0] = True
- os.write(wake_w, b'\x00')
-
- def resume_generator():
- pause_stdin[0] = False
-
- def request_generator():
- cols, rows = 80, 24
- try:
- size = os.get_terminal_size()
- cols, rows = size.columns, size.lines
- except OSError:
- pass
-
- yield connpy_pb2.InteractRequest(
- id=unique_id, sftp=sftp, debug=debug, cols=cols, rows=rows
- )
-
- while True:
- try:
- while True:
- req = request_queue.get_nowait()
- if req is None:
- return
- yield req
- except queue.Empty:
- pass
-
- if pause_stdin[0]:
- import time
- time.sleep(0.05)
- continue
-
- r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
- if wake_r in r:
- os.read(wake_r, 1)
- continue
- if sys.stdin.fileno() in r and not pause_stdin[0]:
- try:
- data = os.read(sys.stdin.fileno(), 1024)
- if not data:
- break
- yield connpy_pb2.InteractRequest(stdin_data=data)
- except OSError:
- break
-
- # Fetch node details for the connection message
- try:
- node_details = self.get_node_details(unique_id)
- host = node_details.get("host", "unknown")
- port = str(node_details.get("port", ""))
- protocol = "sftp" if sftp else node_details.get("protocol", "ssh")
- port_str = f":{port}" if port and protocol not in ["ssm", "kubectl", "docker"] else ""
- conn_msg = f"Connected to {unique_id} at {host}{port_str} via: {protocol}"
- except Exception:
- conn_msg = f"Connected to {unique_id}"
-
- old_tty = termios.tcgetattr(sys.stdin)
- try:
- import time
- tty.setraw(sys.stdin.fileno())
- response_iterator = self.stub.interact_node(request_generator())
-
- import queue
- response_queue = queue.Queue()
-
- def response_consumer():
- try:
- for r in response_iterator:
- response_queue.put(r)
- except Exception:
- pass
- response_queue.put(None)
-
- t_consumer = threading.Thread(target=response_consumer, daemon=True)
- t_consumer.start()
-
- # First phase: Wait for connection status, print early data
- try:
- while True:
- res = response_queue.get()
- if res is None:
- return
- if res.stdout_data:
- data = res.stdout_data
- if debug:
- data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
- os.write(sys.stdout.fileno(), data)
-
- if res.success:
- # Connection established on server, show success message
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- printer.success(conn_msg)
- pause_stdin[0] = False
- tty.setraw(sys.stdin.fileno())
- break
-
- if res.error_message:
- # Connection failed on server
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- printer.error(f"Connection failed: {res.error_message}")
- return
- except queue.Empty:
- return
-
- # Second phase: Stream active session
- # Clear screen filter is only applied before success (Phase 1).
- # Once the user has a prompt, Ctrl+L must work normally.
- while True:
- res = response_queue.get()
- if res is None:
- break
- if res.copilot_prompt:
- self._handle_remote_copilot(
- res, request_queue, response_queue,
- client_buffer_bytes,
- pause_generator, resume_generator, old_tty
- )
- continue
-
- if res.stdout_data:
- os.write(sys.stdout.fileno(), res.stdout_data)
- client_buffer_bytes.extend(res.stdout_data)
- finally:
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
- os.close(wake_r)
- os.close(wake_w)
-
-def delete_node(self, unique_id, is_folder=False, save=True)
-@handle_errors
-def delete_node(self, unique_id, is_folder=False, save=True):
- req = connpy_pb2.DeleteRequest(id=unique_id, is_folder=is_folder)
- self.stub.delete_node(req)
- if save:
- self._trigger_local_cache_sync()
-
-def explode_unique(self, unique_id)
-@handle_errors
-def explode_unique(self, unique_id):
- return from_value(self.stub.explode_unique(connpy_pb2.IdRequest(id=unique_id)).data)
-
-def full_replace(self, connections, profiles)
-@handle_errors
-def full_replace(self, connections, profiles):
- req = connpy_pb2.FullReplaceRequest(
- connections=to_struct(connections),
- profiles=to_struct(profiles)
- )
- self.stub.full_replace(req)
- self._trigger_local_cache_sync()
-
-def generate_cache(self, nodes=None, folders=None, profiles=None)
-@handle_errors
-def generate_cache(self, nodes=None, folders=None, profiles=None):
- # 1. Update remote cache on server
- self.stub.generate_cache(Empty())
-
- # 2. Update local fzf/text cache files
- # If no data provided, we fetch it all from remote to sync local files
- if nodes is None and folders is None and profiles is None:
- nodes = self.list_nodes()
- folders = self.list_folders()
- # We don't have direct access to ProfileStub here, but usually
- # node cache is what matters for fzf. We'll fetch profiles if we can.
- # For now, let's sync what we have.
-
- if nodes is not None or folders is not None or profiles is not None:
- self.config._generate_nodes_cache(nodes=nodes, folders=folders, profiles=profiles)
-
-def get_inventory(self)
-@handle_errors
-def get_inventory(self):
- resp = self.stub.get_inventory(Empty())
- return {
- "connections": from_struct(resp.connections),
- "profiles": from_struct(resp.profiles)
- }
-
-def get_node_details(self, unique_id)
-@handle_errors
-def get_node_details(self, unique_id):
- return from_struct(self.stub.get_node_details(connpy_pb2.IdRequest(id=unique_id)).data)
-
-def list_folders(self, filter_str=None)
-@MethodHook
-@handle_errors
-def list_folders(self, filter_str=None):
- req = connpy_pb2.FilterRequest(filter_str=filter_str or "")
- return from_value(self.stub.list_folders(req).data) or []
-
-def list_nodes(self, filter_str=None, format_str=None)
-@MethodHook
-@handle_errors
-def list_nodes(self, filter_str=None, format_str=None):
- req = connpy_pb2.FilterRequest(filter_str=filter_str or "", format_str=format_str or "")
- return from_value(self.stub.list_nodes(req).data) or []
-
-def move_node(self, src_id, dst_id, copy=False)
-@handle_errors
-def move_node(self, src_id, dst_id, copy=False):
- req = connpy_pb2.MoveRequest(src_id=src_id, dst_id=dst_id, copy=copy)
- self.stub.move_node(req)
- self._trigger_local_cache_sync()
-
-def set_reserved_names(self, names)
-@handle_errors
-def set_reserved_names(self, names):
- self.stub.set_reserved_names(connpy_pb2.ListRequest(items=names))
- self._trigger_local_cache_sync()
-
-def update_node(self, unique_id, data, save=True)
-@handle_errors
-def update_node(self, unique_id, data, save=True):
- req = connpy_pb2.NodeRequest(id=unique_id, data=to_struct(data), is_folder=False)
- self.stub.update_node(req)
- if save:
- self._trigger_local_cache_sync()
-
-def validate_parent_folder(self, unique_id)
-@handle_errors
-def validate_parent_folder(self, unique_id):
- self.stub.validate_parent_folder(connpy_pb2.IdRequest(id=unique_id))
-
-class PluginStub
-(channel, remote_host)
-class PluginStub:
- def __init__(self, channel, remote_host):
- self.stub = connpy_pb2_grpc.PluginServiceStub(channel)
- self.remote_stub = remote_plugin_pb2_grpc.RemotePluginServiceStub(channel)
- self.remote_host = remote_host
-
- @handle_errors
- def list_plugins(self):
- return from_value(self.stub.list_plugins(Empty()).data)
-
- @handle_errors
- def add_plugin(self, name, source_file, update=False):
- # Read the local file content to send it to the server
- with open(source_file, "r") as f:
- content = f.read()
-
- # Use source_file as a marker for "content-inside"
- marker_content = f"---CONTENT---\n{content}"
- req = connpy_pb2.PluginRequest(name=name, source_file=marker_content, update=update)
- self.stub.add_plugin(req)
-
- @handle_errors
- def delete_plugin(self, name):
- self.stub.delete_plugin(connpy_pb2.IdRequest(id=name))
-
- @handle_errors
- def enable_plugin(self, name):
- self.stub.enable_plugin(connpy_pb2.IdRequest(id=name))
-
- @handle_errors
- def disable_plugin(self, name):
- self.stub.disable_plugin(connpy_pb2.IdRequest(id=name))
-
- @handle_errors
- def get_plugin_source(self, name):
- resp = self.remote_stub.get_plugin_source(remote_plugin_pb2.IdRequest(id=name))
- return resp.value
-
- @handle_errors
- def invoke_plugin(self, name, args_namespace):
- import json
- args_dict = {k: v for k, v in vars(args_namespace).items()
- if isinstance(v, (str, int, float, bool, list, type(None)))}
- if hasattr(args_namespace, "func") and hasattr(args_namespace.func, "__name__"):
- args_dict["__func_name__"] = args_namespace.func.__name__
-
- req = remote_plugin_pb2.PluginInvokeRequest(name=name, args_json=json.dumps(args_dict))
- for chunk in self.remote_stub.invoke_plugin(req):
- yield chunk.text
-
-def add_plugin(self, name, source_file, update=False)
-@handle_errors
-def add_plugin(self, name, source_file, update=False):
- # Read the local file content to send it to the server
- with open(source_file, "r") as f:
- content = f.read()
-
- # Use source_file as a marker for "content-inside"
- marker_content = f"---CONTENT---\n{content}"
- req = connpy_pb2.PluginRequest(name=name, source_file=marker_content, update=update)
- self.stub.add_plugin(req)
-
-def delete_plugin(self, name)
-@handle_errors
-def delete_plugin(self, name):
- self.stub.delete_plugin(connpy_pb2.IdRequest(id=name))
-
-def disable_plugin(self, name)
-@handle_errors
-def disable_plugin(self, name):
- self.stub.disable_plugin(connpy_pb2.IdRequest(id=name))
-
-def enable_plugin(self, name)
-@handle_errors
-def enable_plugin(self, name):
- self.stub.enable_plugin(connpy_pb2.IdRequest(id=name))
-
-def get_plugin_source(self, name)
-@handle_errors
-def get_plugin_source(self, name):
- resp = self.remote_stub.get_plugin_source(remote_plugin_pb2.IdRequest(id=name))
- return resp.value
-
-def invoke_plugin(self, name, args_namespace)
-@handle_errors
-def invoke_plugin(self, name, args_namespace):
- import json
- args_dict = {k: v for k, v in vars(args_namespace).items()
- if isinstance(v, (str, int, float, bool, list, type(None)))}
- if hasattr(args_namespace, "func") and hasattr(args_namespace.func, "__name__"):
- args_dict["__func_name__"] = args_namespace.func.__name__
-
- req = remote_plugin_pb2.PluginInvokeRequest(name=name, args_json=json.dumps(args_dict))
- for chunk in self.remote_stub.invoke_plugin(req):
- yield chunk.text
-
-def list_plugins(self)
-@handle_errors
-def list_plugins(self):
- return from_value(self.stub.list_plugins(Empty()).data)
-
-class ProfileStub
-(channel, remote_host, node_stub=None)
-class ProfileStub:
- def __init__(self, channel, remote_host, node_stub=None):
- self.stub = connpy_pb2_grpc.ProfileServiceStub(channel)
- self.remote_host = remote_host
- self.node_stub = node_stub
-
- @handle_errors
- def list_profiles(self, filter_str=None):
- req = connpy_pb2.FilterRequest(filter_str=filter_str or "")
- return from_value(self.stub.list_profiles(req).data) or []
-
- @handle_errors
- def get_profile(self, name, resolve=True):
- req = connpy_pb2.ProfileRequest(name=name, resolve=resolve)
- return from_struct(self.stub.get_profile(req).data)
-
- @handle_errors
- def add_profile(self, name, data):
- req = connpy_pb2.NodeRequest(id=name, data=to_struct(data))
- self.stub.add_profile(req)
- if self.node_stub:
- self.node_stub._trigger_local_cache_sync()
-
- @handle_errors
- def resolve_node_data(self, node_data):
- req = connpy_pb2.StructRequest(data=to_struct(node_data))
- return from_struct(self.stub.resolve_node_data(req).data)
-
- @handle_errors
- def delete_profile(self, name):
- req = connpy_pb2.IdRequest(id=name)
- self.stub.delete_profile(req)
- if self.node_stub:
- self.node_stub._trigger_local_cache_sync()
-
- @handle_errors
- def update_profile(self, name, data):
- req = connpy_pb2.NodeRequest(id=name, data=to_struct(data))
- self.stub.update_profile(req)
- if self.node_stub:
- self.node_stub._trigger_local_cache_sync()
-
-def add_profile(self, name, data)
-@handle_errors
-def add_profile(self, name, data):
- req = connpy_pb2.NodeRequest(id=name, data=to_struct(data))
- self.stub.add_profile(req)
- if self.node_stub:
- self.node_stub._trigger_local_cache_sync()
-
-def delete_profile(self, name)
-@handle_errors
-def delete_profile(self, name):
- req = connpy_pb2.IdRequest(id=name)
- self.stub.delete_profile(req)
- if self.node_stub:
- self.node_stub._trigger_local_cache_sync()
-
-def get_profile(self, name, resolve=True)
-@handle_errors
-def get_profile(self, name, resolve=True):
- req = connpy_pb2.ProfileRequest(name=name, resolve=resolve)
- return from_struct(self.stub.get_profile(req).data)
-
-def list_profiles(self, filter_str=None)
-@handle_errors
-def list_profiles(self, filter_str=None):
- req = connpy_pb2.FilterRequest(filter_str=filter_str or "")
- return from_value(self.stub.list_profiles(req).data) or []
-
-def resolve_node_data(self, node_data)
-@handle_errors
-def resolve_node_data(self, node_data):
- req = connpy_pb2.StructRequest(data=to_struct(node_data))
- return from_struct(self.stub.resolve_node_data(req).data)
-
-def update_profile(self, name, data)
-@handle_errors
-def update_profile(self, name, data):
- req = connpy_pb2.NodeRequest(id=name, data=to_struct(data))
- self.stub.update_profile(req)
- if self.node_stub:
- self.node_stub._trigger_local_cache_sync()
-
-class SystemStub
-(channel, remote_host)
-class SystemStub:
- def __init__(self, channel, remote_host):
- self.stub = connpy_pb2_grpc.SystemServiceStub(channel)
- self.remote_host = remote_host
-
- @handle_errors
- def start_api(self, port=None):
- self.stub.start_api(connpy_pb2.IntRequest(value=port or 8048))
-
- @handle_errors
- def debug_api(self, port=None):
- self.stub.debug_api(connpy_pb2.IntRequest(value=port or 8048))
-
- @handle_errors
- def stop_api(self):
- self.stub.stop_api(Empty())
-
- @handle_errors
- def restart_api(self, port=None):
- self.stub.restart_api(connpy_pb2.IntRequest(value=port or 8048))
-
- @handle_errors
- def get_api_status(self):
- return self.stub.get_api_status(Empty()).value
-
-def debug_api(self, port=None)
-@handle_errors
-def debug_api(self, port=None):
- self.stub.debug_api(connpy_pb2.IntRequest(value=port or 8048))
-
-def get_api_status(self)
-@handle_errors
-def get_api_status(self):
- return self.stub.get_api_status(Empty()).value
-
-def restart_api(self, port=None)
-@handle_errors
-def restart_api(self, port=None):
- self.stub.restart_api(connpy_pb2.IntRequest(value=port or 8048))
-
-def start_api(self, port=None)
-@handle_errors
-def start_api(self, port=None):
- self.stub.start_api(connpy_pb2.IntRequest(value=port or 8048))
-
-def stop_api(self)
-@handle_errors
-def stop_api(self):
- self.stub.stop_api(Empty())
-
@@ -282,6 +282,10 @@ print(response)
connpy.mcp_serverconnpy.proto
class node
-(unique,
host,
options='',
logs='',
password='',
port='',
protocol='',
user='',
config='',
tags='',
jumphost='')
+(unique,
host,
options='',
logs='',
password='',
port='',
protocol='',
user='',
config='',
tags='',
jumphost='',
allow_unsafe_options=None)