Files
connpy/docs/connpy/index.html
T
fluzzi32 12543c683e 1. Persistence Setup: Optimized the dockerfile to manually create the /root/.config/conn/.folder file
pointing to /config. This avoids running the conn command during the build process and ensures a
      cleaner setup.
   2. Copilot UI Fix: Resolved a double-escaping bug in the terminal bottom bar. Device prompts (like
      6WIND-PE1>) will now render correctly instead of showing HTML entities like >.
   3. AI Model Update: Updated the default engineer model in connpy/ai.py to
      gemini/gemini-3.1-flash-lite, removing the deprecated -preview suffix.
   4. Standardized Timeouts: Unified all default timeouts to 20 seconds across the board. This includes
      direct execution (run/test), modern playbooks (v2), and classic task-based playbooks (v1).
   5. Documentation Update: Regenerated the full documentation site in the docs/ directory using pdoc to
      reflect the latest changes.
   6. Cleanup: Removed all debug prints from connpy/core.py and restored the docker/logs/.gitignore
      file.
2026-05-13 14:16:14 -03:00

6214 lines
315 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.5">
<title>connpy API documentation</title>
<meta name="description" content="&lt;p align=&#34;center&#34;&gt;
&lt;img src=&#34;https://nginx.gederico.dynu.net/images/CONNPY-resized.png&#34; alt=&#34;App Logo&#34;&gt;
&lt;/p&gt; …">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source > summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible;min-width:max-content}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin:1em 0}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
/* Collapse source docstrings */
setTimeout(() => {
[...document.querySelectorAll('.hljs.language-python > .hljs-string')]
.filter(el => el.innerHTML.length > 200 && ['"""', "'''"].includes(el.innerHTML.substring(0, 3)))
.forEach(el => {
let d = document.createElement('details');
d.classList.add('hljs-string');
d.innerHTML = '<summary>"""</summary>' + el.innerHTML.substring(3);
el.replaceWith(d);
});
}, 100);
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Package <code>connpy</code></h1>
</header>
<section id="section-intro">
<p align="center">
<img src="https://nginx.gederico.dynu.net/images/CONNPY-resized.png" alt="App Logo">
</p>
<h1 id="connpy">Connpy</h1>
<p><a href="https://pypi.org/pypi/connpy/"><img alt="" src="https://img.shields.io/pypi/v/connpy.svg?style=flat-square"></a>
<a href="https://pypi.org/pypi/connpy/"><img alt="" src="https://img.shields.io/pypi/pyversions/connpy.svg?style=flat-square"></a>
<a href="https://github.com/fluzzi/connpy/blob/main/LICENSE"><img alt="" src="https://img.shields.io/pypi/l/connpy.svg?style=flat-square"></a>
<a href="https://pypi.org/pypi/connpy/"><img alt="" src="https://img.shields.io/pypi/dm/connpy.svg?style=flat-square"></a></p>
<p><strong>Connpy</strong> is a powerful Connection Manager and Network Automation Platform for Linux, Mac, and Docker. It provides a unified interface for <strong>SSH, SFTP, Telnet, kubectl, Docker pods, and AWS SSM</strong>.</p>
<p>The v6 release introduces the <strong>AI Copilot</strong>, an interactive terminal assistant that understands your network context and helps you manage your infrastructure more intelligently.</p>
<h2 id="ai-copilot-new-in-v6">🤖 AI Copilot (New in v6)</h2>
<p>The AI Copilot is deeply integrated into your terminal workflow:
- <strong>Terminal Context Awareness</strong>: The Copilot can "see" your screen output, helping you diagnose errors or analyze command results in real-time.
- <strong>Hybrid Multi-Agent System</strong>: Automatically escalates complex tasks between the <strong>Network Engineer</strong> (execution) and the <strong>Network Architect</strong> (strategy).
- <strong>MCP Integration</strong>: Dynamically load tools from external providers (6WIND, AWS, etc.) via the Model Context Protocol.
- <strong>Interactive Chat</strong>: Launch with <code>conn <a title="connpy.ai" href="#connpy.ai">ai</a></code> for a collaborative troubleshooting session.</p>
<h2 id="core-features">Core Features</h2>
<ul>
<li><strong>Multi-Protocol</strong>: Native support for SSH, SFTP, Telnet, kubectl, Docker exec, and AWS SSM.</li>
<li><strong>Context Management</strong>: Set regex-based contexts to manage specific nodes across different environments (work, home, clients).</li>
<li><strong>Advanced Inventory</strong>:<ul>
<li>Organize nodes in folders (<code>@folder</code>) and subfolders (<code>@subfolder@folder</code>).</li>
<li>Use Global Profiles (<code>@profilename</code>) to manage shared credentials easily.</li>
<li>Bulk creation, copying, moving, and export/import of nodes.</li>
</ul>
</li>
<li><strong>Modern UI</strong>: High-performance terminal experience with <code>prompt-toolkit</code>, including:<ul>
<li>Fuzzy search integration with <code>fzf</code>.</li>
<li>Advanced tab completion.</li>
<li>Syntax highlighting and customizable themes.</li>
</ul>
</li>
<li><strong>Automation Engine</strong>: Run parallel tasks and playbooks on multiple devices with variable support.</li>
<li><strong>Plugin System</strong>: Build and execute custom Python scripts locally or on a remote gRPC server.</li>
<li><strong>gRPC Architecture</strong>: Fully decoupled Client/Server model for distributed management.</li>
<li><strong>Privacy &amp; Sync</strong>: Local-first encrypted storage (RSA/OAEP) with optional Google Drive backup.</li>
</ul>
<h2 id="installation">Installation</h2>
<pre><code class="language-bash">pip install connpy
</code></pre>
<h3 id="run-it-in-windowslinux-using-docker">Run it in Windows/Linux using Docker</h3>
<pre><code class="language-bash">git clone https://github.com/fluzzi/connpy
cd connpy
docker compose build
# Run it like a native app (completely silent)
docker compose --log-level ERROR run --rm --remove-orphans connpy-app [command]
# Pro Tip: Add this alias for a 100% native experience from any folder
alias conn='docker compose -f /path/to/connpy/docker-compose.yml --log-level ERROR run --rm --remove-orphans connpy-app'
</code></pre>
<hr>
<h2 id="privacy-integration">🔒 Privacy &amp; Integration</h2>
<h3 id="privacy-policy">Privacy Policy</h3>
<p>Connpy is committed to protecting your privacy:
- <strong>Local Storage</strong>: All server addresses, usernames, and passwords are encrypted and stored <strong>only</strong> on your machine. No data is transmitted to our servers.
- <strong>Data Access</strong>: Data is used solely for managing and automating your connections.</p>
<h3 id="google-integration">Google Integration</h3>
<p>Used strictly for backup:
- <strong>Backup</strong>: Sync your encrypted configuration with your Google Drive account.
- <strong>Scoped Access</strong>: Connpy only accesses its own backup files.</p>
<hr>
<h2 id="usage">Usage</h2>
<pre><code class="language-bash">usage: conn [-h] [--add | --del | --mod | --show | --debug] [node|folder] [--sftp]
conn {profile,move,copy,list,bulk,export,import,ai,run,api,plugin,config,sync,context} ...
</code></pre>
<h3 id="basic-examples">Basic Examples:</h3>
<pre><code class="language-bash"># Add a folder and subfolder
conn --add @office
conn --add @datacenter@office
# Add a node with a profile
conn --add server1@datacenter@office --profile @myuser
# Connect to a node (fuzzy match)
conn server1
# Start the AI Copilot
conn ai
# Run a command on all nodes in a folder
conn run @office &quot;uptime&quot;
</code></pre>
<hr>
<h2 id="plugin-requirements-for-connpy">Plugin Requirements for Connpy</h2>
<h3 id="remote-plugin-execution">Remote Plugin Execution</h3>
<p>When Connpy operates in remote mode, plugins are executed <strong>transparently on the server</strong>:
- The client automatically downloads the plugin source code (<code>Parser</code> class context) to generate the local <code>argparse</code> structure and provide autocompletion.
- The execution phase (<code>Entrypoint</code> class) is redirected via gRPC streams to execute in the server's memory.
- You can manage remote plugins using the <code>--remote</code> flag.</p>
<h3 id="general-structure">General Structure</h3>
<ul>
<li>The plugin script must define specific classes:</li>
<li><strong>Class <code>Parser</code></strong>: Handles <code>argparse.ArgumentParser</code> initialization.</li>
<li><strong>Class <code>Entrypoint</code></strong>: Main execution logic (receives <code>args</code>, <code>parser</code>, and <code>connapp</code>).</li>
<li><strong>Class <code>Preload</code></strong>: (Optional) For modifying core app behavior or registering hooks.</li>
</ul>
<h3 id="preload-modifications-and-hooks">Preload Modifications and Hooks</h3>
<p>You can customize the behavior of core classes using hooks:
- <strong><code>modify(method)</code></strong>: Alter class instances (e.g., <code>connapp.config</code>, <code>connapp.ai</code>).
- <strong><code>register_pre_hook(method)</code></strong>: Logic to run before a method execution.
- <strong><code>register_post_hook(method)</code></strong>: Logic to run after a method execution.</p>
<h3 id="command-completion-support">Command Completion Support</h3>
<p>Plugins can provide intelligent tab completion:
1. <strong>Tree-based Completion (Recommended)</strong>: Define <code>_connpy_tree(info)</code> returning a navigation dictionary.
2. <strong>Legacy Completion</strong>: Define <code>_connpy_completion(wordsnumber, words, info)</code>.</p>
<hr>
<h2 id="grpc-service-architecture">⚙️ gRPC Service Architecture</h2>
<p>Connpy can operate in a decoupled mode:
1. <strong>Start the API (Server)</strong>: <code>conn api -s 50051</code>
2. <strong>Configure the Client</strong>:
<code>bash
conn config --service-mode remote
conn config --remote-host localhost:50051</code>
All inventory management and execution will now happen on the server.</p>
<hr>
<h2 id="automation-module-api">🐍 Automation Module (API)</h2>
<p>You can use <code><a title="connpy" href="#connpy">connpy</a></code> as a Python library for your own scripts.</p>
<h3 id="basic-execution">Basic Execution</h3>
<pre><code class="language-python">import connpy
router = connpy.node(&quot;uniqueName&quot;, &quot;1.1.1.1&quot;, user=&quot;admin&quot;)
router.run([&quot;show ip int brief&quot;])
print(router.output)
</code></pre>
<h3 id="parallel-tasks-with-variables">Parallel Tasks with Variables</h3>
<pre><code class="language-python">import connpy
config = connpy.configfile()
nodes = config.getitem(&quot;@office&quot;, [&quot;router1&quot;, &quot;router2&quot;])
routers = connpy.nodes(nodes, config=config)
variables = {
&quot;router1@office&quot;: {&quot;id&quot;: &quot;1&quot;},
&quot;__global__&quot;: {&quot;mask&quot;: &quot;255.255.255.0&quot;}
}
routers.run([&quot;interface lo{id}&quot;, &quot;ip address 10.0.0.{id} {mask}&quot;], variables)
</code></pre>
<h3 id="ai-programmatic-use">AI Programmatic Use</h3>
<pre><code class="language-python">import connpy
myai = connpy.ai(connpy.configfile())
response = myai.ask(&quot;What is the status of the BGP neighbors in the office?&quot;)
</code></pre>
<hr>
<p><em>For detailed developer notes and plugin hooks documentation, see the <a href="https://fluzzi.github.io/connpy/">Documentation</a>.</em></p>
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="connpy.cli" href="cli/index.html">connpy.cli</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="connpy.grpc_layer" href="grpc_layer/index.html">connpy.grpc_layer</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="connpy.mcp_client" href="mcp_client.html">connpy.mcp_client</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="connpy.proto" href="proto/index.html">connpy.proto</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="connpy.services" href="services/index.html">connpy.services</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="connpy.tests" href="tests/index.html">connpy.tests</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="connpy.tunnels" href="tunnels.html">connpy.tunnels</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="connpy.utils" href="utils.html">connpy.utils</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="connpy.Plugins"><code class="flex name class">
<span>class <span class="ident">Plugins</span></span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class Plugins:
def __init__(self):
self.plugins = {}
self.plugin_parsers = {}
self.preloads = {}
self.remote_plugins = {}
self.preferences = {}
def _load_preferences(self, config_dir):
import json
path = os.path.join(config_dir, &#34;plugin_preferences.json&#34;)
try:
with open(path) as f:
self.preferences = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
self.preferences = {}
def _save_preferences(self, config_dir):
import json
path = os.path.join(config_dir, &#34;plugin_preferences.json&#34;)
try:
with open(path, &#34;w&#34;) as f:
json.dump(self.preferences, f, indent=4)
except OSError as e:
printer.error(f&#34;Failed to save plugin preferences: {e}&#34;)
def verify_script(self, file_path):
&#34;&#34;&#34;
Verifies that a given Python script meets specific structural requirements.
This function checks a Python script for compliance with predefined structural
rules. It ensures that the script contains only allowed top-level elements
(functions, classes, imports, pass statements, and a specific if __name__ block)
and that it includes mandatory classes with specific attributes and methods.
### Arguments:
- file_path (str): The file path of the Python script to be verified.
### Returns:
- str: A message indicating the type of violation if the script doesn&#39;t meet
the requirements, or False if all requirements are met.
### Verifications:
- The presence of only allowed top-level elements.
- The existence of two specific classes: &#39;Parser&#39; and &#39;Entrypoint&#39;. and/or specific class: Preload.
- &#39;Parser&#39; class must only have an &#39;__init__&#39; method and must assign &#39;self.parser&#39;.
- &#39;Entrypoint&#39; class must have an &#39;__init__&#39; method accepting specific arguments.
If any of these checks fail, the function returns an error message indicating
the reason. If the script passes all checks, the function returns False,
indicating successful verification.
### Exceptions:
- SyntaxError: If the script contains a syntax error, it is caught and
returned as a part of the error message.
&#34;&#34;&#34;
with open(file_path, &#39;r&#39;) as file:
source_code = file.read()
try:
tree = ast.parse(source_code)
except SyntaxError as e:
return f&#34;Syntax error in file: {e}&#34;
has_parser = False
has_entrypoint = False
has_preload = False
for node in tree.body:
# Allow only function definitions, class definitions, and pass statements at top-level
if isinstance(node, ast.If):
# Check for the &#39;if __name__ == &#34;__main__&#34;:&#39; block
if not (isinstance(node.test, ast.Compare) and
isinstance(node.test.left, ast.Name) and
node.test.left.id == &#39;__name__&#39; and
((hasattr(ast, &#39;Str&#39;) and isinstance(node.test.comparators[0], getattr(ast, &#39;Str&#39;)) and node.test.comparators[0].s == &#39;__main__&#39;) or
(hasattr(ast, &#39;Constant&#39;) and isinstance(node.test.comparators[0], getattr(ast, &#39;Constant&#39;)) and node.test.comparators[0].value == &#39;__main__&#39;))):
return &#34;Only __name__ == __main__ If is allowed&#34;
elif not isinstance(node, (ast.FunctionDef, ast.ClassDef, ast.Import, ast.ImportFrom, ast.Pass)):
return f&#34;Plugin can only have pass, functions, classes and imports. {node} is not allowed&#34; # Reject any other AST types
if isinstance(node, ast.ClassDef):
if node.name == &#39;Parser&#39;:
has_parser = True
# Ensure Parser class has only the __init__ method and assigns self.parser
if not all(isinstance(method, ast.FunctionDef) and method.name == &#39;__init__&#39; for method in node.body):
return &#34;Parser class should only have __init__ method&#34;
# Check if &#39;self.parser&#39; is assigned in __init__ method
init_method = node.body[0]
assigned_attrs = [target.attr for expr in init_method.body if isinstance(expr, ast.Assign) for target in expr.targets if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == &#39;self&#39;]
if &#39;parser&#39; not in assigned_attrs:
return &#34;Parser class should set self.parser&#34;
elif node.name == &#39;Entrypoint&#39;:
has_entrypoint = True
init_method = next((item for item in node.body if isinstance(item, ast.FunctionDef) and item.name == &#39;__init__&#39;), None)
if not init_method or len(init_method.args.args) != 4: # self, args, parser, conapp
return &#34;Entrypoint class should have method __init__ and accept only arguments: args, parser and connapp&#34; # &#39;Entrypoint&#39; __init__ does not have correct signature
elif node.name == &#39;Preload&#39;:
has_preload = True
init_method = next((item for item in node.body if isinstance(item, ast.FunctionDef) and item.name == &#39;__init__&#39;), None)
if not init_method or len(init_method.args.args) != 2: # self, connapp
return &#34;Preload class should have method __init__ and accept only argument: connapp&#34; # &#39;Preload&#39; __init__ does not have correct signature
# Applying the combination logic based on class presence
if has_parser and not has_entrypoint:
return &#34;Parser requires Entrypoint class to be present.&#34;
elif has_entrypoint and not has_parser:
return &#34;Entrypoint requires Parser class to be present.&#34;
if not (has_parser or has_entrypoint or has_preload):
return &#34;No valid class (Parser, Entrypoint, or Preload) found.&#34;
return False # All requirements met, no error
def _import_from_path(self, path):
spec = importlib.util.spec_from_file_location(&#34;module.name&#34;, path)
module = importlib.util.module_from_spec(spec)
sys.modules[&#34;module.name&#34;] = module
spec.loader.exec_module(module)
return module
def _import_plugins_to_argparse(self, directory, subparsers, remote_enabled=False):
if not os.path.exists(directory):
return
for filename in os.listdir(directory):
commands = subparsers.choices.keys()
if filename.endswith(&#34;.py&#34;):
root_filename = os.path.splitext(filename)[0]
if root_filename in commands:
continue
# Check preferences: if remote is preferred AND remote is enabled, skip local loading
if remote_enabled and self.preferences.get(root_filename) == &#34;remote&#34;:
continue
# Construct the full path
filepath = os.path.join(directory, filename)
check_file = self.verify_script(filepath)
if check_file:
printer.error(f&#34;Failed to load plugin: {filename}. Reason: {check_file}&#34;)
continue
else:
self.plugins[root_filename] = self._import_from_path(filepath)
if hasattr(self.plugins[root_filename], &#34;Parser&#34;):
self.plugin_parsers[root_filename] = self.plugins[root_filename].Parser()
plugin = self.plugin_parsers[root_filename]
# Default to RichHelpFormatter if plugin doesn&#39;t set one
try:
from rich_argparse import RichHelpFormatter as _RHF
fmt = plugin.parser.formatter_class
if fmt is argparse.HelpFormatter or fmt is argparse.RawTextHelpFormatter or fmt is argparse.RawDescriptionHelpFormatter:
fmt = _RHF
except ImportError:
fmt = plugin.parser.formatter_class
subparsers.add_parser(root_filename, parents=[self.plugin_parsers[root_filename].parser], add_help=False, help=plugin.parser.description, usage=plugin.parser.usage, description=plugin.parser.description, epilog=plugin.parser.epilog, formatter_class=fmt)
if hasattr(self.plugins[root_filename], &#34;Preload&#34;):
self.preloads[root_filename] = self.plugins[root_filename]
def _import_remote_plugins_to_argparse(self, plugin_stub, subparsers, cache_dir, force_sync=False):
import hashlib
os.makedirs(cache_dir, exist_ok=True)
try:
remote_plugins_info = plugin_stub.list_plugins()
except Exception:
return
# Pruning: Remove local cached files that are no longer on the server
for local_file in os.listdir(cache_dir):
if local_file.endswith(&#34;.py&#34;):
name = local_file[:-3]
if name not in remote_plugins_info:
try:
os.remove(os.path.join(cache_dir, local_file))
except Exception:
pass
for name, info in remote_plugins_info.items():
if not info.get(&#34;enabled&#34;, True):
continue
pref = self.preferences.get(name, &#34;local&#34;)
if pref != &#34;remote&#34; and name in self.plugins:
continue
if not force_sync and name in subparsers.choices:
continue
cache_path = os.path.join(cache_dir, f&#34;{name}.py&#34;)
# Hash comparison
remote_hash = info.get(&#34;hash&#34;, &#34;&#34;)
local_hash = &#34;&#34;
if os.path.exists(cache_path):
try:
with open(cache_path, &#34;rb&#34;) as f:
local_hash = hashlib.md5(f.read()).hexdigest()
except Exception:
pass
# Update only if hash differs or force_sync is True
if force_sync or remote_hash != local_hash or not os.path.exists(cache_path):
try:
source = plugin_stub.get_plugin_source(name)
with open(cache_path, &#34;w&#34;) as f:
f.write(source)
except Exception as e:
printer.warning(f&#34;Failed to sync remote plugin {name}: {e}&#34;)
continue
# Verify and load
check_file = self.verify_script(cache_path)
if check_file:
printer.warning(f&#34;Remote plugin {name} failed verification: {check_file}&#34;)
continue
module = self._import_from_path(cache_path)
if hasattr(module, &#34;Parser&#34;):
self.plugin_parsers[name] = module.Parser()
self.remote_plugins[name] = True
plugin = self.plugin_parsers[name]
try:
from rich_argparse import RichHelpFormatter as _RHF
fmt = plugin.parser.formatter_class
if fmt is argparse.HelpFormatter or fmt is argparse.RawTextHelpFormatter or fmt is argparse.RawDescriptionHelpFormatter:
fmt = _RHF
except ImportError:
fmt = plugin.parser.formatter_class
# If force_sync, we might be re-registering, but argparse subparsers.add_parser
# might fail if it exists. We check if it&#39;s already there.
if name not in subparsers.choices:
subparsers.add_parser(
name,
parents=[plugin.parser],
add_help=False,
help=f&#34;[remote] {plugin.parser.description}&#34;,
usage=plugin.parser.usage,
description=plugin.parser.description,
epilog=plugin.parser.epilog,
formatter_class=fmt
)</code></pre>
</details>
<div class="desc"></div>
<h3>Methods</h3>
<dl>
<dt id="connpy.Plugins.verify_script"><code class="name flex">
<span>def <span class="ident">verify_script</span></span>(<span>self, file_path)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def verify_script(self, file_path):
&#34;&#34;&#34;
Verifies that a given Python script meets specific structural requirements.
This function checks a Python script for compliance with predefined structural
rules. It ensures that the script contains only allowed top-level elements
(functions, classes, imports, pass statements, and a specific if __name__ block)
and that it includes mandatory classes with specific attributes and methods.
### Arguments:
- file_path (str): The file path of the Python script to be verified.
### Returns:
- str: A message indicating the type of violation if the script doesn&#39;t meet
the requirements, or False if all requirements are met.
### Verifications:
- The presence of only allowed top-level elements.
- The existence of two specific classes: &#39;Parser&#39; and &#39;Entrypoint&#39;. and/or specific class: Preload.
- &#39;Parser&#39; class must only have an &#39;__init__&#39; method and must assign &#39;self.parser&#39;.
- &#39;Entrypoint&#39; class must have an &#39;__init__&#39; method accepting specific arguments.
If any of these checks fail, the function returns an error message indicating
the reason. If the script passes all checks, the function returns False,
indicating successful verification.
### Exceptions:
- SyntaxError: If the script contains a syntax error, it is caught and
returned as a part of the error message.
&#34;&#34;&#34;
with open(file_path, &#39;r&#39;) as file:
source_code = file.read()
try:
tree = ast.parse(source_code)
except SyntaxError as e:
return f&#34;Syntax error in file: {e}&#34;
has_parser = False
has_entrypoint = False
has_preload = False
for node in tree.body:
# Allow only function definitions, class definitions, and pass statements at top-level
if isinstance(node, ast.If):
# Check for the &#39;if __name__ == &#34;__main__&#34;:&#39; block
if not (isinstance(node.test, ast.Compare) and
isinstance(node.test.left, ast.Name) and
node.test.left.id == &#39;__name__&#39; and
((hasattr(ast, &#39;Str&#39;) and isinstance(node.test.comparators[0], getattr(ast, &#39;Str&#39;)) and node.test.comparators[0].s == &#39;__main__&#39;) or
(hasattr(ast, &#39;Constant&#39;) and isinstance(node.test.comparators[0], getattr(ast, &#39;Constant&#39;)) and node.test.comparators[0].value == &#39;__main__&#39;))):
return &#34;Only __name__ == __main__ If is allowed&#34;
elif not isinstance(node, (ast.FunctionDef, ast.ClassDef, ast.Import, ast.ImportFrom, ast.Pass)):
return f&#34;Plugin can only have pass, functions, classes and imports. {node} is not allowed&#34; # Reject any other AST types
if isinstance(node, ast.ClassDef):
if node.name == &#39;Parser&#39;:
has_parser = True
# Ensure Parser class has only the __init__ method and assigns self.parser
if not all(isinstance(method, ast.FunctionDef) and method.name == &#39;__init__&#39; for method in node.body):
return &#34;Parser class should only have __init__ method&#34;
# Check if &#39;self.parser&#39; is assigned in __init__ method
init_method = node.body[0]
assigned_attrs = [target.attr for expr in init_method.body if isinstance(expr, ast.Assign) for target in expr.targets if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == &#39;self&#39;]
if &#39;parser&#39; not in assigned_attrs:
return &#34;Parser class should set self.parser&#34;
elif node.name == &#39;Entrypoint&#39;:
has_entrypoint = True
init_method = next((item for item in node.body if isinstance(item, ast.FunctionDef) and item.name == &#39;__init__&#39;), None)
if not init_method or len(init_method.args.args) != 4: # self, args, parser, conapp
return &#34;Entrypoint class should have method __init__ and accept only arguments: args, parser and connapp&#34; # &#39;Entrypoint&#39; __init__ does not have correct signature
elif node.name == &#39;Preload&#39;:
has_preload = True
init_method = next((item for item in node.body if isinstance(item, ast.FunctionDef) and item.name == &#39;__init__&#39;), None)
if not init_method or len(init_method.args.args) != 2: # self, connapp
return &#34;Preload class should have method __init__ and accept only argument: connapp&#34; # &#39;Preload&#39; __init__ does not have correct signature
# Applying the combination logic based on class presence
if has_parser and not has_entrypoint:
return &#34;Parser requires Entrypoint class to be present.&#34;
elif has_entrypoint and not has_parser:
return &#34;Entrypoint requires Parser class to be present.&#34;
if not (has_parser or has_entrypoint or has_preload):
return &#34;No valid class (Parser, Entrypoint, or Preload) found.&#34;
return False # All requirements met, no error</code></pre>
</details>
<div class="desc"><p>Verifies that a given Python script meets specific structural requirements.</p>
<p>This function checks a Python script for compliance with predefined structural
rules. It ensures that the script contains only allowed top-level elements
(functions, classes, imports, pass statements, and a specific if <strong>name</strong> block)
and that it includes mandatory classes with specific attributes and methods.</p>
<h3 id="arguments">Arguments:</h3>
<pre><code>- file_path (str): The file path of the Python script to be verified.
</code></pre>
<h3 id="returns">Returns:</h3>
<pre><code>- str: A message indicating the type of violation if the script doesn't meet
the requirements, or False if all requirements are met.
</code></pre>
<h3 id="verifications">Verifications:</h3>
<pre><code>- The presence of only allowed top-level elements.
- The existence of two specific classes: 'Parser' and 'Entrypoint'. and/or specific class: Preload.
- 'Parser' class must only have an '__init__' method and must assign 'self.parser'.
- 'Entrypoint' class must have an '__init__' method accepting specific arguments.
</code></pre>
<p>If any of these checks fail, the function returns an error message indicating
the reason. If the script passes all checks, the function returns False,
indicating successful verification.</p>
<h3 id="exceptions">Exceptions:</h3>
<pre><code> - SyntaxError: If the script contains a syntax error, it is caught and
returned as a part of the error message.
</code></pre></div>
</dd>
</dl>
</dd>
<dt id="connpy.ai"><code class="flex name class">
<span>class <span class="ident">ai</span></span>
<span>(</span><span>config,<br>org=None,<br>api_key=None,<br>engineer_model=None,<br>architect_model=None,<br>engineer_api_key=None,<br>architect_api_key=None,<br>console=None,<br>confirm_handler=None,<br>trust=False)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@ClassHook
class ai:
&#34;&#34;&#34;Hybrid Multi-Agent System: Selective Escalation with Role Persistence.&#34;&#34;&#34;
SAFE_COMMANDS = [
r&#39;^show\s+&#39;, r&#39;^ls\s*&#39;, r&#39;^cat\s+&#39;, r&#39;^ip\s+&#39;, r&#39;^pwd$&#39;, r&#39;^hostname$&#39;, r&#39;^uname&#39;,
r&#39;^df\s*&#39;, r&#39;^free\s*&#39;, r&#39;^ps\s*&#39;, r&#39;^ping\s+&#39;, r&#39;^traceroute\s+&#39;, r&#39;^whois\s+&#39;,
r&#39;^kubectl\s+(get|describe|version|logs|top|explain|cluster-info|api-resources|api-versions)\s+&#39;,
r&#39;^systemctl\s+status\s+&#39;, r&#39;^journalctl\s+&#39;
]
def __init__(self, config, org=None, api_key=None, engineer_model=None, architect_model=None, engineer_api_key=None, architect_api_key=None, console=None, confirm_handler=None, trust=False):
self.config = config
self.console = console or printer.console
self.confirm_handler = confirm_handler or self._local_confirm_handler
self.trusted_session = trust # Trust mode for the entire session
self.interrupted = False
# 1. Cargar configuración genérica
aiconfig = self.config.config.get(&#34;ai&#34;, {})
# Modelos (Prioridad: Argumento -&gt; Config -&gt; Default)
self.engineer_model = engineer_model or aiconfig.get(&#34;engineer_model&#34;) or &#34;gemini/gemini-3.1-flash-lite&#34;
self.architect_model = architect_model or aiconfig.get(&#34;architect_model&#34;) or &#34;anthropic/claude-sonnet-4-6&#34;
# API Keys (Prioridad: Argumento -&gt; Config)
self.engineer_key = engineer_api_key or aiconfig.get(&#34;engineer_api_key&#34;)
self.architect_key = architect_api_key or aiconfig.get(&#34;architect_api_key&#34;)
# Custom Trusted Commands Regexes
custom_trusted = aiconfig.get(&#34;trusted_commands&#34;, [])
if isinstance(custom_trusted, str):
custom_trusted = [c.strip() for c in custom_trusted.split(&#34;,&#34;) if c.strip()]
self.safe_commands = list(self.SAFE_COMMANDS) + (custom_trusted if isinstance(custom_trusted, list) else [])
# Límites
self.max_history = 30
self.max_truncate = 50000
self.soft_limit_iterations = 20 # Show warning and suggest Ctrl+C
self.hard_limit_iterations = 50 # Force stop
# External tool registry (populated by plugins via ClassHook.modify)
self.external_engineer_tools = [] # Tool defs for Engineer LLM
self.external_architect_tools = [] # Tool defs for Architect LLM
self.external_tool_handlers = {} # {&#34;tool_name&#34;: handler_callable}
self.tool_status_formatters = {} # {&#34;tool_name&#34;: formatter_callable}
self.engineer_prompt_extensions = [] # Extra text for engineer prompt
self.architect_prompt_extensions = [] # Extra text for architect prompt
# MCP Manager
self.mcp_manager = MCPClientManager(self.config)
# Long-term memory
self.memory_path = os.path.join(self.config.defaultdir, &#34;ai_memory.md&#34;)
self.long_term_memory = &#34;&#34;
if os.path.exists(self.memory_path):
try:
with open(self.memory_path, &#34;r&#34;) as f:
self.long_term_memory = f.read()
except FileNotFoundError:
self.long_term_memory = &#34;&#34;
except PermissionError as e:
self.console.print(f&#34;[warning]Warning: Cannot read AI memory file: {e}[/warning]&#34;)
except Exception as e:
self.console.print(f&#34;[warning]Warning: Failed to load AI memory: {e}[/warning]&#34;)
# Session Management
self.sessions_dir = os.path.join(self.config.defaultdir, &#34;ai_sessions&#34;)
os.makedirs(self.sessions_dir, exist_ok=True)
self.session_id = None
self.session_path = None
# Prompts base agnósticos
architect_instructions = &#34;&#34;
if self.architect_key:
architect_instructions = &#34;&#34;&#34;
CRITICAL - CONSULT vs ESCALATE:
- ALWAYS use &#39;consult_architect&#39; for: Configuration planning, design decisions, complex troubleshooting.
Examples: &#34;consultalo con el arquitecto&#34;, &#34;preguntale al arquitecto&#34;, &#34;que opina el arquitecto&#34;
You stay in control and present the advice to the user.
- ONLY use &#39;escalate_to_architect&#39; when user EXPLICITLY asks to TALK to the Architect:
Examples: &#34;quiero hablar con el arquitecto&#34;, &#34;pasame con el arquitecto&#34;, &#34;que me atienda el arquitecto&#34;
After escalation, you hand over control completely.
- DEFAULT: When in doubt, use &#39;consult_architect&#39;. Escalation is rare.
&#34;&#34;&#34;
else:
architect_instructions = &#34;&#34;&#34;
CRITICAL - ARCHITECT UNAVAILABLE:
- The Strategic Reasoning Engine (Architect) is currently UNAVAILABLE because its API key is not configured.
- DO NOT attempt to consult or escalate to the architect.
- If the user asks to consult the architect, inform them that the Architect is offline and offer to help them directly to the best of your abilities.
&#34;&#34;&#34;
self._engineer_base_prompt = dedent(f&#34;&#34;&#34;
Role: TECHNICAL EXECUTION ENGINE.
Expertise: Universal Networking (Cisco, Nokia, Juniper, 6wind, etc.).
Rules:
- BE FAST AND EXTREMELY CONCISE: Provide direct answers. No filler words, no decorative language, no polite pleasantries. Save output tokens at all costs.
- KNOWLEDGE FIRST: For general networking questions (AS numbers, protocol details, standards, generic commands), use your internal knowledge. ONLY use tools when the user&#39;s specific infrastructure data is required.
- INVENTORY ONLY: &#39;run_commands&#39;, &#39;list_nodes&#39;, and &#39;get_node_info&#39; are ONLY for interacting with the user&#39;s inventory.
- BROADCAST RESTRICTION: Avoid using filter &#39;.*&#39; in &#39;run_commands&#39; unless the user explicitly requests a global action. Try to target specific nodes or groups based on the conversation.
- AUTONOMY: Proactively use iterative tool calls to find the root cause of infrastructure issues.
- BATCH OPERATIONS: When working on multiple devices, call tools in parallel.
- COMPLETE MISSIONS: Execute ALL steps of a mission before reporting back.
- DIAGRAM: Use ASCII art or Unicode box-drawing characters directly in your responses to visualize topologies or paths when helpful.
- EVIDENCE: Include &#39;Key Snippets&#39; from tool outputs. Be token-efficient.
- NO WANDERING: Do not speculate. If stuck, report attempts.
- SAFETY: When you use &#39;run_commands&#39; with configuration commands, the system automatically prompts the user for confirmation. Just execute - don&#39;t ask permission first.
{architect_instructions}
Network Context: {{self.long_term_memory if self.long_term_memory else &#34;Empty.&#34;}}
&#34;&#34;&#34;).strip()
self._architect_base_prompt = dedent(f&#34;&#34;&#34;
Role: STRATEGIC REASONING ENGINE.
Expertise: Network Architecture, Complex Troubleshooting, and Design Validation.
Rules:
- CONCISENESS IS MANDATORY: Strip out fluff, decorative language, and filler words. Provide direct, tactical instructions and analysis to save output tokens.
- STRATEGY: Define technical missions for the Engineer.
- DIAGRAM: Use ASCII art or Unicode box-drawing characters in your responses to visualize topologies, traffic paths, or logic flows.
- ENGINEER CAPABILITIES: Your Engineer can:
* Filter nodes (list_nodes), Run CLI commands (run_commands), Get metadata (get_node_info).
- ANALYSIS: Review technical findings to identify patterns or design failures.
- MEMORY: Update long-term facts ONLY when the user explicitly requests it.
CRITICAL - EFFICIENT DELEGATION:
- Plan ALL tasks upfront before delegating.
- Delegate ONCE with a complete, detailed mission including ALL steps.
- Example: &#34;List all routers matching &#39;border.*&#39;, then run &#39;show ip bgp summary&#39; and &#39;show ip route&#39; on each, then analyze the outputs.&#34;
- DO NOT delegate multiple times for the same goal. Batch everything into ONE mission.
- Wait for Engineer&#39;s complete report before responding to user.
CRITICAL - RETURNING CONTROL:
- When your strategic analysis is complete and no further architectural decisions are needed, use &#39;return_to_engineer&#39; to hand control back.
- The Engineer is better suited for ongoing technical execution and troubleshooting.
- Only stay in control if the user explicitly needs strategic oversight for multiple interactions.
Network Context: {self.long_term_memory if self.long_term_memory else &#34;Empty.&#34;}
&#34;&#34;&#34;).strip()
def _local_confirm_handler(self, prompt, default=&#34;n&#34;):
&#34;&#34;&#34;Default confirmation handler using rich.prompt.&#34;&#34;&#34;
from rich.prompt import Prompt
return Prompt.ask(prompt, default=default)
@property
def engineer_system_prompt(self):
&#34;&#34;&#34;Build engineer system prompt with plugin extensions.&#34;&#34;&#34;
if self.engineer_prompt_extensions:
extensions = &#34;\n&#34;.join(self.engineer_prompt_extensions)
return self._engineer_base_prompt + f&#34;\n\nPlugin Capabilities:\n{extensions}&#34;
return self._engineer_base_prompt
@property
def architect_system_prompt(self):
&#34;&#34;&#34;Build architect system prompt with plugin extensions.&#34;&#34;&#34;
if self.architect_prompt_extensions:
extensions = &#34;\n&#34;.join(self.architect_prompt_extensions)
return self._architect_base_prompt + f&#34;\n\nPlugin Capabilities:\n{extensions}&#34;
return self._architect_base_prompt
def register_ai_tool(self, tool_definition, handler, target=&#34;engineer&#34;, engineer_prompt=None, architect_prompt=None, status_formatter=None):
&#34;&#34;&#34;Register an external tool for the AI system.
Args:
tool_definition (dict): OpenAI-compatible tool definition.
handler (callable): Function(ai_instance, **tool_args) -&gt; str.
target (str): &#39;engineer&#39;, &#39;architect&#39;, or &#39;both&#39;.
engineer_prompt (str): Extra text for engineer system prompt.
architect_prompt (str): Extra text for architect system prompt.
status_formatter (callable): Function(args_dict) -&gt; status string.
&#34;&#34;&#34;
name = tool_definition[&#34;function&#34;][&#34;name&#34;]
# Check if already registered to prevent duplicates
if target in (&#34;engineer&#34;, &#34;both&#34;):
if not any(t[&#34;function&#34;][&#34;name&#34;] == name for t in self.external_engineer_tools):
self.external_engineer_tools.append(tool_definition)
if target in (&#34;architect&#34;, &#34;both&#34;):
if not any(t[&#34;function&#34;][&#34;name&#34;] == name for t in self.external_architect_tools):
self.external_architect_tools.append(tool_definition)
self.external_tool_handlers[name] = handler
if engineer_prompt and engineer_prompt not in self.engineer_prompt_extensions:
self.engineer_prompt_extensions.append(engineer_prompt)
if architect_prompt and architect_prompt not in self.architect_prompt_extensions:
self.architect_prompt_extensions.append(architect_prompt)
if status_formatter:
self.tool_status_formatters[name] = status_formatter
def _stream_completion(self, model, messages, tools, api_key, status=None, label=&#34;&#34;, debug=False, chunk_callback=None, **kwargs):
&#34;&#34;&#34;Stream a completion call, rendering styled Markdown in real-time.
Returns (response, streamed) where:
- response: reconstructed ModelResponse (same as non-streaming)
- streamed: True if text was rendered to console during streaming
&#34;&#34;&#34;
from rich.live import Live
stream_resp = completion(model=model, messages=messages, tools=tools, api_key=api_key, stream=True, **kwargs)
chunks = []
full_content = &#34;&#34;
is_streaming_text = False
has_tool_calls = False
live_display = None
# Determine styling based on current brain
role_label = &#34;Network Architect&#34; if &#34;architect&#34; in label.lower() else &#34;Network Engineer&#34;
alias = &#34;architect&#34; if &#34;architect&#34; in label.lower() else &#34;engineer&#34;
title = f&#34;[bold {alias}]{role_label}[/bold {alias}]&#34;
border = alias
try:
for chunk in stream_resp:
chunks.append(chunk)
delta = chunk.choices[0].delta
# Detect tool calls
if hasattr(delta, &#39;tool_calls&#39;) and delta.tool_calls:
has_tool_calls = True
# Stream text content with styled rendering
if hasattr(delta, &#39;content&#39;) and delta.content:
full_content += delta.content
if chunk and chunk_callback:
# Check for remote interruption during streaming
if hasattr(self, &#34;interrupted&#34;) and self.interrupted:
raise KeyboardInterrupt
chunk_callback(delta.content)
if not chunk_callback:
if not is_streaming_text:
# Stop spinner definitively
if status:
try:
status.stop()
except Exception:
pass
# Create a stable, direct Console to bypass _ConsoleProxy recreation bugs
from rich.console import Console as RichConsole
from .printer import connpy_theme, get_original_stdout
stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
live_display = Live(
Panel(Markdown(full_content), title=title, border_style=border, expand=False),
console=stable_console,
refresh_per_second=8,
transient=False
)
live_display.start()
is_streaming_text = True
else:
live_display.update(
Panel(Markdown(full_content), title=title, border_style=border, expand=False)
)
except Exception as e:
if not chunks:
raise
finally:
if live_display:
# Render final state with complete content
try:
live_display.update(
Panel(Markdown(full_content), title=title, border_style=border, expand=False)
)
except Exception:
pass
try:
live_display.stop()
except Exception:
pass
# Rebuild complete response from chunks
try:
response = stream_chunk_builder(chunks, messages=messages)
except Exception:
# Fallback: manual reconstruction if stream_chunk_builder fails
full_content_rebuilt = &#34;&#34;
tool_calls_map = {}
for c in chunks:
d = c.choices[0].delta
if hasattr(d, &#39;content&#39;) and d.content:
full_content_rebuilt += d.content
if hasattr(d, &#39;tool_calls&#39;) and d.tool_calls:
for tc in d.tool_calls:
idx = tc.index
if idx not in tool_calls_map:
tool_calls_map[idx] = {&#34;id&#34;: tc.id or &#34;&#34;, &#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: getattr(tc.function, &#39;name&#39;, &#39;&#39;) or &#39;&#39;, &#34;arguments&#34;: getattr(tc.function, &#39;arguments&#39;, &#39;&#39;) or &#39;&#39;}}
else:
if tc.id: tool_calls_map[idx][&#34;id&#34;] = tc.id
if tc.function:
if tc.function.name: tool_calls_map[idx][&#34;function&#34;][&#34;name&#34;] = tc.function.name
if tc.function.arguments: tool_calls_map[idx][&#34;function&#34;][&#34;arguments&#34;] += tc.function.arguments
# Build a minimal response-like object
class FakeFunc:
def __init__(self, name, arguments): self.name = name; self.arguments = arguments
class FakeTC:
def __init__(self, d): self.id = d[&#34;id&#34;]; self.function = FakeFunc(d[&#34;function&#34;][&#34;name&#34;], d[&#34;function&#34;][&#34;arguments&#34;])
def model_dump(self, **kw): return {&#34;id&#34;: self.id, &#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: self.function.name, &#34;arguments&#34;: self.function.arguments}}
class FakeMsg:
def __init__(self, content, tcs): self.content = content or None; self.tool_calls = tcs if tcs else None; self.role = &#34;assistant&#34;
def model_dump(self, **kw):
d = {&#34;role&#34;: &#34;assistant&#34;, &#34;content&#34;: self.content}
if self.tool_calls: d[&#34;tool_calls&#34;] = [tc.model_dump() for tc in self.tool_calls]
return d
class FakeChoice:
def __init__(self, msg): self.message = msg
class FakeResp:
def __init__(self, choice): self.choices = [choice]; self.usage = None
tcs = [FakeTC(tool_calls_map[i]) for i in sorted(tool_calls_map)] if tool_calls_map else None
response = FakeResp(FakeChoice(FakeMsg(full_content_rebuilt or full_content, tcs)))
# Only count as &#34;streamed&#34; if we rendered text AND it was the final response (no tool calls)
streamed = is_streaming_text and not has_tool_calls
return response, streamed
def _sanitize_messages(self, messages):
&#34;&#34;&#34;Sanitize message list for strict providers like Gemini.
Ensures that:
1. Every assistant message with tool_calls is followed by ALL its tool responses
2. No user/system messages appear between tool_calls and tool responses
3. Orphaned tool_calls at the end are removed
4. Orphaned tool responses without a preceding tool_call are removed
5. Incompatible metadata like cache_control is stripped for non-Anthropic models
6. Enforces strict alternating history to prevent BadRequestError on Gemini.
&#34;&#34;&#34;
if not messages:
return messages
# Pre-process messages to pull text from list contents (Anthropic cache format)
# and remove explicit cache keys.
pre_sanitized = []
for msg in messages:
m = msg.copy() if isinstance(msg, dict) else msg.model_dump(exclude_none=True)
# Convert content list to plain string if it&#39;s a system message with caching metadata
if m.get(&#39;role&#39;) == &#39;system&#39; and isinstance(m.get(&#39;content&#39;), list):
if m[&#39;content&#39;] and isinstance(m[&#39;content&#39;][0], dict) and m[&#39;content&#39;][0].get(&#39;text&#39;):
m[&#39;content&#39;] = m[&#39;content&#39;][0][&#39;text&#39;]
else:
m[&#39;content&#39;] = &#34;&#34;
# Remove any explicit cache_control key anywhere
if &#39;cache_control&#39; in m: del m[&#39;cache_control&#39;]
if isinstance(m.get(&#39;content&#39;), list):
for item in m[&#39;content&#39;]:
if isinstance(item, dict) and &#39;cache_control&#39; in item: del item[&#39;cache_control&#39;]
pre_sanitized.append(m)
sanitized = []
last_role = None
i = 0
while i &lt; len(pre_sanitized):
msg = pre_sanitized[i]
role = msg.get(&#39;role&#39;, &#39;&#39;)
if role == &#39;system&#39;:
sanitized.append(msg)
last_role = &#39;system&#39;
i += 1
elif role == &#39;user&#39;:
if last_role == &#39;user&#39; and sanitized:
# Combine consecutive user messages
sanitized[-1][&#39;content&#39;] = str(sanitized[-1].get(&#39;content&#39;, &#39;&#39;) or &#39;&#39;) + &#39;\n&#39; + str(msg.get(&#39;content&#39;, &#39;&#39;) or &#39;&#39;)
else:
sanitized.append(msg)
last_role = &#39;user&#39;
i += 1
elif role == &#39;assistant&#39;:
has_tools = bool(msg.get(&#39;tool_calls&#39;))
# Gemini strict sequence: Assistant MUST be preceded by user or tool.
# If preceded by system, assistant, or if it&#39;s the very first message...
if last_role not in (&#39;user&#39;, &#39;tool&#39;):
sanitized.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: &#34;[System sequence separator: History Truncated/Merged]&#34;})
last_role = &#39;user&#39;
if has_tools:
# Look ahead for matching tool responses
tool_responses = []
j = i + 1
while j &lt; len(pre_sanitized):
next_msg = pre_sanitized[j]
if next_msg.get(&#39;role&#39;) == &#39;tool&#39;:
tool_responses.append(next_msg)
j += 1
else:
break
if tool_responses:
sanitized.append(msg)
sanitized.extend(tool_responses)
last_role = &#39;tool&#39;
i = j
else:
# Orphaned tool_calls with no responses - skip the assistant message
# If we just added a dummy user message for this assistant, remove it too
if sanitized and sanitized[-1].get(&#39;content&#39;) == &#34;[System sequence separator: History Truncated/Merged]&#34;:
sanitized.pop()
last_role = sanitized[-1].get(&#39;role&#39;, &#39;&#39;) if sanitized else None
i += 1
else:
sanitized.append(msg)
last_role = &#39;assistant&#39;
i += 1
elif role == &#39;tool&#39;:
# Orphaned tool response (no preceding assistant with tool_calls) - skip
i += 1
else:
sanitized.append(msg)
last_role = role
i += 1
return sanitized
def _truncate(self, text, limit=None):
&#34;&#34;&#34;Truncate text to specified limit, keeping head (60%) and tail (40%).&#34;&#34;&#34;
if not isinstance(text, str): return str(text)
final_limit = limit or self.max_truncate
if len(text) &lt;= final_limit: return text
head_limit = int(final_limit * 0.6)
tail_limit = int(final_limit * 0.4)
return (text[:head_limit] + f&#34;\n\n[... OUTPUT TRUNCATED ...]\n\n&#34; + text[-tail_limit:])
def _print_debug_observation(self, fn, obs, status=None):
&#34;&#34;&#34;Prints a tool observation in a readable way during debug mode.&#34;&#34;&#34;
# Try to parse as JSON if it&#39;s a string
if isinstance(obs, str):
try:
obs_data = json.loads(obs)
except Exception:
obs_data = obs
else:
obs_data = obs
if isinstance(obs_data, dict):
elements = []
for k, v in obs_data.items():
elements.append(Text(f&#34;• {k}:&#34;, style=&#34;key&#34;))
# Use Text for values to ensure newlines are rendered
val = str(v)
# If it&#39;s a multiline string from a delegation task, keep it clean
elements.append(Text(val))
if not elements:
content = Text(&#34;Empty data set&#34;)
else:
# Add a small spacer instead of a Rule for cleaner look
from rich.console import Group
content = Group(*elements)
elif isinstance(obs_data, list):
content = Text(&#34;\n&#34;.join(f&#34;• {item}&#34; for item in obs_data))
else:
content = Text(str(obs_data))
title = f&#34;[bold]{fn}[/bold]&#34;
# Stop status before printing panel to avoid ghosting
if status:
try: status.stop()
except: pass
self.console.print(Panel(content, title=title, border_style=&#34;ai_status&#34;))
# Resume status
if status:
try: status.start()
except: pass
def manage_memory_tool(self, content, action=&#34;append&#34;):
&#34;&#34;&#34;Save or update long-term memory. Only use when user explicitly requests it.&#34;&#34;&#34;
if not content or not content.strip():
return &#34;Error: Cannot save empty content to memory.&#34;
try:
mode = &#34;a&#34; if action == &#34;append&#34; else &#34;w&#34;
os.makedirs(os.path.dirname(self.memory_path), exist_ok=True)
with open(self.memory_path, mode) as f:
timestamp = datetime.datetime.now().strftime(&#39;%Y-%m-%d %H:%M&#39;)
f.write(f&#34;\n\n## {timestamp}\n{content.strip()}\n&#34; if action == &#34;append&#34; else content)
# Reload memory after update
with open(self.memory_path, &#34;r&#34;) as f:
self.long_term_memory = f.read()
return &#34;Memory updated successfully.&#34;
except PermissionError as e:
return f&#34;Error: Permission denied writing to memory file: {e}&#34;
except Exception as e:
return f&#34;Error updating memory: {str(e)}&#34;
def list_nodes_tool(self, filter_pattern=&#34;.*&#34;):
&#34;&#34;&#34;List nodes matching the filter pattern. Returns metadata for &lt;=5 nodes, names only for more.&#34;&#34;&#34;
try:
matched_names = self.config._getallnodes(filter_pattern)
if not matched_names: return &#34;No nodes found.&#34;
if len(matched_names) &lt;= 5:
matched_data = self.config.getitems(matched_names, extract=True)
res = {}
for name, data in matched_data.items():
os_tag = &#34;unknown&#34;
if isinstance(data, dict):
ts = data.get(&#34;tags&#34;)
if isinstance(ts, dict): os_tag = ts.get(&#34;os&#34;, &#34;unknown&#34;)
res[name] = {&#34;os&#34;: os_tag}
return res
return {&#34;count&#34;: len(matched_names), &#34;nodes&#34;: matched_names, &#34;note&#34;: &#34;Use &#39;get_node_info&#39; for details.&#34;}
except Exception as e:
return f&#34;Error listing nodes: {str(e)}&#34;
def _is_safe_command(self, cmd):
&#34;&#34;&#34;Check if a command matches safe patterns.&#34;&#34;&#34;
return any(re.match(pattern, cmd.strip(), re.IGNORECASE) for pattern in self.safe_commands)
def run_commands_tool(self, nodes_filter, commands, status=None):
&#34;&#34;&#34;Execute commands on nodes matching the filter. Native interactive confirmation for unsafe commands.&#34;&#34;&#34;
# Handle if commands is a JSON string
if isinstance(commands, str):
try:
commands = json.loads(commands)
except ValueError:
commands = [c.strip() for c in commands.split(&#39;\n&#39;) if c.strip()]
# Expand multi-line commands within a list (in case the AI packs them)
if isinstance(commands, list):
expanded_commands = []
for cmd in commands:
expanded_commands.extend([c.strip() for c in str(cmd).split(&#39;\n&#39;) if c.strip()])
commands = expanded_commands
else:
commands = [str(commands)]
# Check command safety natively
if not self.trusted_session:
unsafe_commands = [cmd for cmd in commands if not self._is_safe_command(cmd)]
if unsafe_commands:
# Stop the spinner so prompt doesn&#39;t get messed up
if status: status.stop()
# Show ALL commands with unsafe ones highlighted
formatted_cmds = []
for cmd in commands:
if cmd in unsafe_commands:
formatted_cmds.append(f&#34; • [warning]{cmd}[/warning]&#34;)
else:
formatted_cmds.append(f&#34; • {cmd}&#34;)
panel_content = f&#34;Target: {nodes_filter}\nCommands:\n&#34; + &#34;\n&#34;.join(formatted_cmds)
# Use print_important if available (for remote bridges) fallback to standard print
print_fn = getattr(self.console, &#34;print_important&#34;, self.console.print)
print_fn(Panel(panel_content, title=&#34;[bold warning]⚠️ UNSAFE COMMANDS DETECTED[/bold warning]&#34;, border_style=&#34;warning&#34;))
try:
user_resp = self.confirm_handler(&#34;[bold warning]Execute? (y: yes / n: no / a: allow all this session / &lt;text&gt;: feedback)[/bold warning]&#34;, default=&#34;n&#34;)
except KeyboardInterrupt:
if status: status.update(&#34;[ai_status]Engineer: Resuming...&#34;)
self.console.print(&#34;[fail]✗ Aborted by user (Ctrl+C).[/fail]&#34;)
raise
# Resume the spinner
if status: status.update(&#34;[ai_status]Engineer: Processing user response...&#34;)
user_resp_lower = user_resp.strip().lower()
if user_resp_lower in [&#39;a&#39;, &#39;allow&#39;]:
self.trusted_session = True
self.console.print(&#34;[pass]✓ Trust Mode Enabled. All future commands in this session will execute without confirmation.[/pass]&#34;)
elif user_resp_lower in [&#39;y&#39;, &#39;yes&#39;]:
self.console.print(&#34;[pass]✓ Executing...[/pass]&#34;)
elif user_resp_lower in [&#39;n&#39;, &#39;no&#39;, &#39;&#39;, &#39;cancel&#39;]:
self.console.print(&#34;[fail]✗ Execution rejected by user.[/fail]&#34;)
return &#34;Error: User rejected execution.&#34;
else:
self.console.print(f&#34;[user_prompt]User feedback: [/user_prompt]{user_resp}&#34;)
return f&#34;User requested changes: {user_resp}. Please adjust the commands based on this feedback and try again.&#34;
try:
matched_names = self.config._getallnodes(nodes_filter)
if not matched_names: return &#34;No nodes found matching filter.&#34;
thisnodes_dict = self.config.getitems(matched_names, extract=True)
result = nodes(thisnodes_dict, config=self.config).run(commands)
return result
except Exception as e:
return f&#34;Error executing commands: {str(e)}&#34;
def get_node_info_tool(self, node_name):
&#34;&#34;&#34;Get detailed metadata for a specific node. Passwords are masked.&#34;&#34;&#34;
try:
d = self.config.getitem(node_name, extract=True)
if &#39;password&#39; in d: d[&#39;password&#39;] = &#39;***&#39;
return d
except Exception as e:
return f&#34;Error getting node info: {str(e)}&#34;
def _engineer_loop(self, task, status=None, debug=False, chat_history=None):
&#34;&#34;&#34;Internal loop where the Engineer executes technical tasks for the Architect.&#34;&#34;&#34;
# Optimización de caché para el Ingeniero (Solo para Anthropic directo, Vertex tiene reglas distintas)
if &#34;claude&#34; in self.engineer_model.lower() and &#34;vertex&#34; not in self.engineer_model.lower():
messages = [{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: [{&#34;type&#34;: &#34;text&#34;, &#34;text&#34;: self.engineer_system_prompt, &#34;cache_control&#34;: {&#34;type&#34;: &#34;ephemeral&#34;}}]}]
else:
messages = [{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: self.engineer_system_prompt}]
if chat_history:
# Clean chat history from caching metadata if engineer is not a compatible Claude model
if &#34;claude&#34; not in self.engineer_model.lower() or &#34;vertex&#34; in self.engineer_model.lower():
messages.extend(self._sanitize_messages(chat_history[-5:]))
else:
messages.extend(chat_history[-5:])
messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: f&#34;MISSION: {task}&#34;})
tools = self._get_engineer_tools()
usage = {&#34;input&#34;: 0, &#34;output&#34;: 0, &#34;total&#34;: 0}
iteration = 0
soft_limit_warned = False
try:
# Set up remote interrupt callback if bridge is provided
if status and hasattr(status, &#34;on_interrupt&#34;):
status.on_interrupt = lambda: setattr(self, &#34;interrupted&#34;, True)
while iteration &lt; self.hard_limit_iterations:
iteration += 1
# Check for interruption
if self.interrupted:
raise KeyboardInterrupt
# Soft limit warning
if iteration == self.soft_limit_iterations and not soft_limit_warned:
self.console.print(f&#34;[warning]⚠ Engineer has performed {iteration} steps. This is taking longer than expected.[/warning]&#34;)
self.console.print(f&#34;[warning] You can press Ctrl+C to interrupt and get a summary.[/warning]&#34;)
soft_limit_warned = True
if status and not chat_history: status.update(f&#34;[ai_status]Engineer: Analyzing mission... (step {iteration})&#34;)
try:
safe_messages = self._sanitize_messages(messages)
response = completion(model=self.engineer_model, messages=safe_messages, tools=tools, api_key=self.engineer_key)
except Exception as e:
if status: status.stop()
raise ValueError(f&#34;Engineer failed to connect: {str(e)}&#34;)
if hasattr(response, &#34;usage&#34;) and response.usage:
usage[&#34;input&#34;] += getattr(response.usage, &#34;prompt_tokens&#34;, 0)
usage[&#34;output&#34;] += getattr(response.usage, &#34;completion_tokens&#34;, 0)
usage[&#34;total&#34;] += getattr(response.usage, &#34;total_tokens&#34;, 0)
resp_msg = response.choices[0].message
msg_dict = resp_msg.model_dump(exclude_none=True)
if msg_dict.get(&#34;tool_calls&#34;) and msg_dict.get(&#34;content&#34;) == &#34;&#34;: msg_dict[&#34;content&#34;] = None
messages.append(msg_dict)
if not resp_msg.tool_calls: break
for tc in resp_msg.tool_calls:
fn, args = tc.function.name, json.loads(tc.function.arguments)
# Notificación en tiempo real de la tarea técnica (Only if not in Architect loop)
if status and not chat_history:
if fn == &#34;list_nodes&#34;: status.update(f&#34;[ai_status]Engineer: [SEARCH] {args.get(&#39;filter_pattern&#39;,&#39;.*&#39;)}&#34;)
elif fn == &#34;run_commands&#34;:
cmds = args.get(&#39;commands&#39;, [])
cmd_str = cmds[0] if cmds else &#34;&#34;
status.update(f&#34;[ai_status]Engineer: [CMD] {cmd_str}&#34;)
elif fn == &#34;get_node_info&#34;: status.update(f&#34;[ai_status]Engineer: [INSPECT] {args.get(&#39;node_name&#39;,&#39;&#39;)}&#34;)
elif fn.startswith(&#34;mcp_&#34;):
server = fn.split(&#34;__&#34;)[0].replace(&#34;mcp_&#34;, &#34;&#34;)
tool = fn.split(&#34;__&#34;)[1] if &#34;__&#34; in fn else fn
status.update(f&#34;[ai_status]Engineer: [MCP:{server}] {tool}&#34;)
elif fn in self.tool_status_formatters: status.update(self.tool_status_formatters[fn](args))
if debug:
self._print_debug_observation(f&#34;Decision: {fn}&#34;, args, status=status)
if fn == &#34;list_nodes&#34;: obs = self.list_nodes_tool(**args)
elif fn == &#34;run_commands&#34;: obs = self.run_commands_tool(**args, status=status)
elif fn == &#34;get_node_info&#34;: obs = self.get_node_info_tool(**args)
elif fn.startswith(&#34;mcp_&#34;):
obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
else: obs = f&#34;Error: Unknown tool &#39;{fn}&#39;.&#34;
if debug:
self._print_debug_observation(f&#34;Observation: {fn}&#34;, obs, status=status)
# Ensure observation is a string and truncated for the LLM
obs_str = obs if isinstance(obs, str) else json.dumps(obs)
messages.append({&#34;tool_call_id&#34;: tc.id, &#34;role&#34;: &#34;tool&#34;, &#34;name&#34;: fn, &#34;content&#34;: self._truncate(obs_str)})
if iteration &gt;= self.hard_limit_iterations:
self.console.print(f&#34;[error]⛔ Engineer reached hard limit ({self.hard_limit_iterations} steps). Forcing stop.[/error]&#34;)
if debug and resp_msg.content:
self.console.print(Panel(Text(resp_msg.content), title=&#34;[bold engineer]Engineer Final Report to Architect[/bold engineer]&#34;, border_style=&#34;engineer&#34;))
return resp_msg.content, usage
except Exception as e:
return f&#34;Engineer failed: {str(e)}&#34;, usage
def _get_engineer_tools(self, os_filter: str = None):
&#34;&#34;&#34;Define tools available to the Engineer.&#34;&#34;&#34;
base_tools = [
{&#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: &#34;list_nodes&#34;, &#34;description&#34;: &#34;[Universal Platform] Lists available nodes in the inventory.&#34;, &#34;parameters&#34;: {&#34;type&#34;: &#34;object&#34;, &#34;properties&#34;: {&#34;filter_pattern&#34;: {&#34;type&#34;: &#34;string&#34;, &#34;description&#34;: &#34;Regex to filter nodes (e.g. &#39;.*&#39;, &#39;border.*&#39;).&#34;}}}}},
{&#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: &#34;run_commands&#34;, &#34;description&#34;: &#34;[Universal Platform] Runs one or more commands on matched nodes. MANDATORY: You MUST call &#39;list_nodes&#39; first to verify the target list.&#34;, &#34;parameters&#34;: {&#34;type&#34;: &#34;object&#34;, &#34;properties&#34;: {&#34;nodes_filter&#34;: {&#34;type&#34;: &#34;string&#34;, &#34;description&#34;: &#34;Exact node name or verified filter pattern.&#34;}, &#34;commands&#34;: {&#34;type&#34;: &#34;array&#34;, &#34;items&#34;: {&#34;type&#34;: &#34;string&#34;}, &#34;description&#34;: &#34;List of commands (e.g. [&#39;show ip route&#39;, &#39;show int desc&#39;]).&#34;}}, &#34;required&#34;: [&#34;nodes_filter&#34;, &#34;commands&#34;]}}},
{&#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: &#34;get_node_info&#34;, &#34;description&#34;: &#34;[Universal Platform] Gets full metadata for a specific node.&#34;, &#34;parameters&#34;: {&#34;type&#34;: &#34;object&#34;, &#34;properties&#34;: {&#34;node_name&#34;: {&#34;type&#34;: &#34;string&#34;}}, &#34;required&#34;: [&#34;node_name&#34;]}}}
]
# Add dynamic tools from MCP
try:
mcp_tools = run_ai_async(self.mcp_manager.get_tools_for_llm(os_filter=os_filter)).result(timeout=10)
base_tools.extend(mcp_tools)
except Exception as e:
# Silently fail for LLM tools
pass
if self.architect_key:
base_tools.extend([
{&#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: &#34;consult_architect&#34;, &#34;description&#34;: &#34;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.&#34;, &#34;parameters&#34;: {&#34;type&#34;: &#34;object&#34;, &#34;properties&#34;: {&#34;question&#34;: {&#34;type&#34;: &#34;string&#34;, &#34;description&#34;: &#34;Strategic question or decision needed.&#34;}, &#34;technical_summary&#34;: {&#34;type&#34;: &#34;string&#34;, &#34;description&#34;: &#34;Technical findings and context gathered so far.&#34;}}, &#34;required&#34;: [&#34;question&#34;, &#34;technical_summary&#34;]}}},
{&#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: &#34;escalate_to_architect&#34;, &#34;description&#34;: &#34;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.&#34;, &#34;parameters&#34;: {&#34;type&#34;: &#34;object&#34;, &#34;properties&#34;: {&#34;reason&#34;: {&#34;type&#34;: &#34;string&#34;, &#34;description&#34;: &#34;Why you&#39;re escalating (e.g. &#39;User requested Architect&#39;, &#39;Complex multi-site design needed&#39;).&#34;}, &#34;context&#34;: {&#34;type&#34;: &#34;string&#34;, &#34;description&#34;: &#34;Full context and findings to hand over.&#34;}}, &#34;required&#34;: [&#34;reason&#34;, &#34;context&#34;]}}}
])
# Deduplicate by name to prevent Gemini BadRequestError
all_tools = base_tools + self.external_engineer_tools
seen_names = set()
unique_tools = []
for t in all_tools:
name = t[&#34;function&#34;][&#34;name&#34;]
if name not in seen_names:
unique_tools.append(t)
seen_names.add(name)
return unique_tools
def _get_architect_tools(self):
&#34;&#34;&#34;Define tools available to the Strategic Reasoning Engine.&#34;&#34;&#34;
base_tools = [
{&#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: &#34;delegate_to_engineer&#34;, &#34;description&#34;: &#34;Delegates a technical mission to the Engineer.&#34;, &#34;parameters&#34;: {&#34;type&#34;: &#34;object&#34;, &#34;properties&#34;: {&#34;task&#34;: {&#34;type&#34;: &#34;string&#34;, &#34;description&#34;: &#34;Detailed technical mission or goal.&#34;}}, &#34;required&#34;: [&#34;task&#34;]}}},
{&#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: &#34;return_to_engineer&#34;, &#34;description&#34;: &#34;Return control to the Engineer. Use this when your strategic analysis is complete and the Engineer should handle the rest of the conversation.&#34;, &#34;parameters&#34;: {&#34;type&#34;: &#34;object&#34;, &#34;properties&#34;: {&#34;summary&#34;: {&#34;type&#34;: &#34;string&#34;, &#34;description&#34;: &#34;Brief summary of your analysis to hand over to the Engineer.&#34;}}, &#34;required&#34;: [&#34;summary&#34;]}}},
{&#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: &#34;manage_memory_tool&#34;, &#34;description&#34;: &#34;Saves information to long-term memory. MANDATORY: Only use this if the user explicitly asks to remember or save something.&#34;, &#34;parameters&#34;: {&#34;type&#34;: &#34;object&#34;, &#34;properties&#34;: {&#34;content&#34;: {&#34;type&#34;: &#34;string&#34;}, &#34;action&#34;: {&#34;type&#34;: &#34;string&#34;, &#34;enum&#34;: [&#34;append&#34;, &#34;replace&#34;]}}, &#34;required&#34;: [&#34;content&#34;]}}}
]
all_tools = base_tools + self.external_architect_tools
seen_names = set()
unique_tools = []
for t in all_tools:
name = t[&#34;function&#34;][&#34;name&#34;]
if name not in seen_names:
unique_tools.append(t)
seen_names.add(name)
return unique_tools
def _get_sessions(self):
&#34;&#34;&#34;Returns a list of session metadata sorted by date.&#34;&#34;&#34;
sessions = []
if not os.path.exists(self.sessions_dir):
return []
for f in os.listdir(self.sessions_dir):
if f.endswith(&#34;.json&#34;):
path = os.path.join(self.sessions_dir, f)
try:
with open(path, &#34;r&#34;) as fs:
data = json.load(fs)
sessions.append({
&#34;id&#34;: f[:-5],
&#34;title&#34;: data.get(&#34;title&#34;, &#34;Untitled Session&#34;),
&#34;created_at&#34;: data.get(&#34;created_at&#34;, &#34;Unknown&#34;),
&#34;model&#34;: data.get(&#34;model&#34;, &#34;Unknown&#34;),
&#34;path&#34;: path
})
except Exception:
continue
return sorted(sessions, key=lambda x: x[&#34;created_at&#34;], reverse=True)
def list_sessions(self):
&#34;&#34;&#34;Prints a list of sessions using printer.table.&#34;&#34;&#34;
sessions = self._get_sessions()
if not sessions:
printer.info(&#34;No saved AI sessions found.&#34;)
return
columns = [&#34;ID&#34;, &#34;Title&#34;, &#34;Created At&#34;, &#34;Model&#34;]
rows = [[s[&#34;id&#34;], s[&#34;title&#34;], s[&#34;created_at&#34;], s[&#34;model&#34;]] for s in sessions]
printer.table(&#34;AI Persisted Sessions&#34;, columns, rows)
def load_session_data(self, session_id):
&#34;&#34;&#34;Loads a session&#39;s raw data by ID.&#34;&#34;&#34;
path = os.path.join(self.sessions_dir, f&#34;{session_id}.json&#34;)
if os.path.exists(path):
try:
with open(path, &#34;r&#34;) as f:
data = json.load(f)
self.session_id = session_id
self.session_path = path
return data
except Exception as e:
printer.error(f&#34;Failed to load session {session_id}: {e}&#34;)
return None
def delete_session(self, session_id):
&#34;&#34;&#34;Deletes a session by ID.&#34;&#34;&#34;
path = os.path.join(self.sessions_dir, f&#34;{session_id}.json&#34;)
if os.path.exists(path):
os.remove(path)
printer.success(f&#34;Session {session_id} deleted.&#34;)
else:
printer.error(f&#34;Session {session_id} not found.&#34;)
def get_last_session_id(self):
&#34;&#34;&#34;Returns the ID of the most recent session.&#34;&#34;&#34;
sessions = self._get_sessions()
return sessions[0][&#34;id&#34;] if sessions else None
def _generate_session_id(self, query):
&#34;&#34;&#34;Generates a unique session ID based on timestamp.&#34;&#34;&#34;
return datetime.datetime.now().strftime(&#34;%Y%m%d-%H%M%S&#34;)
def save_session(self, history, title=None, model=None):
&#34;&#34;&#34;Saves current history to the session file.&#34;&#34;&#34;
if not self.session_id:
# Generate ID from first user query if available
first_user_msg = next((m[&#34;content&#34;] for m in history if m[&#34;role&#34;] == &#34;user&#34;), &#34;new-session&#34;)
self.session_id = self._generate_session_id(first_user_msg)
self.session_path = os.path.join(self.sessions_dir, f&#34;{self.session_id}.json&#34;)
# If it&#39;s a new file, we might want to set a better title
if not os.path.exists(self.session_path) and not title:
raw_title = next((m[&#34;content&#34;] for m in history if m[&#34;role&#34;] == &#34;user&#34;), &#34;New Session&#34;)
# Clean title: remove newlines, multiple spaces
clean_title = &#34; &#34;.join(raw_title.split())
if len(clean_title) &gt; 40:
title = clean_title[:37].strip() + &#34;...&#34;
else:
title = clean_title
try:
# Read existing metadata if it exists
metadata = {}
if os.path.exists(self.session_path):
with open(self.session_path, &#34;r&#34;) as f:
metadata = json.load(f)
metadata.update({
&#34;id&#34;: self.session_id,
&#34;title&#34;: title or metadata.get(&#34;title&#34;, &#34;New Session&#34;),
&#34;created_at&#34;: metadata.get(&#34;created_at&#34;, datetime.datetime.now().isoformat()),
&#34;updated_at&#34;: datetime.datetime.now().isoformat(),
&#34;model&#34;: model or metadata.get(&#34;model&#34;, self.engineer_model),
&#34;history&#34;: history
})
with open(self.session_path, &#34;w&#34;) as f:
json.dump(metadata, f, indent=4)
except Exception as e:
printer.error(f&#34;Failed to save session: {e}&#34;)
except Exception as e:
printer.error(f&#34;Failed to save session: {e}&#34;)
@MethodHook
def ask(self, user_input, dryrun=False, chat_history=None, status=None, debug=False, stream=True, session_id=None, chunk_callback=None):
if not self.engineer_key:
raise ValueError(&#34;Engineer API key not configured. Use &#39;connpy config --engineer-api-key &lt;key&gt;&#39; to set it.&#34;)
if chat_history is None: chat_history = []
# Load session if provided and history is empty
if session_id and not chat_history:
session_data = self.load_session_data(session_id)
if session_data:
chat_history = session_data.get(&#34;history&#34;, [])
# If we loaded history, the caller might need it back
# But typically ask() is called in a loop with an external history object
usage = {&#34;input&#34;: 0, &#34;output&#34;: 0, &#34;total&#34;: 0}
# 1. Selector de Rol inicial (Sticky Brain)
explicit_architect = re.match(r&#39;^(architect|arquitecto|@architect)[:\s]&#39;, user_input, re.I)
explicit_engineer = re.match(r&#39;^(engineer|ingeniero|@engineer)[:\s]&#39;, user_input, re.I)
if explicit_architect:
current_brain = &#34;architect&#34;
elif explicit_engineer:
current_brain = &#34;engineer&#34;
else:
# Sticky Brain: Detectar si el Arquitecto estaba al mando en el historial reciente
is_architect_active = False
for msg in reversed(chat_history[-5:]):
tcs = msg.get(&#39;tool_calls&#39;) if isinstance(msg, dict) else getattr(msg, &#39;tool_calls&#39;, None)
if tcs:
for tc in tcs:
fn = tc.get(&#39;function&#39;, {}).get(&#39;name&#39;) if isinstance(tc, dict) else getattr(getattr(tc, &#39;function&#39;, None), &#39;name&#39;, &#39;&#39;)
# Architect stays in control if delegating tasks or if Engineer escalated to them
# consult_architect is just Engineer asking for advice - Engineer keeps control
if fn in [&#39;delegate_to_engineer&#39;, &#39;escalate_to_architect&#39;]:
is_architect_active = True; break
if is_architect_active: break
current_brain = &#34;architect&#34; if is_architect_active else &#34;engineer&#34;
# 2. Preparación de mensajes y limpieza
clean_input = re.sub(r&#39;^(architect|arquitecto|engineer|ingeniero|@architect|@engineer)[:\s]+&#39;, &#39;&#39;, user_input, flags=re.IGNORECASE).strip()
system_prompt = self.architect_system_prompt if current_brain == &#34;architect&#34; else self.engineer_system_prompt
tools = self._get_architect_tools() if current_brain == &#34;architect&#34; else self._get_engineer_tools()
model = self.architect_model if current_brain == &#34;architect&#34; else self.engineer_model
key = self.architect_key if current_brain == &#34;architect&#34; else self.engineer_key
# Estructura optimizada para Prompt Caching (Solo para Anthropic directo, Vertex tiene reglas distintas)
if &#34;claude&#34; in model.lower() and &#34;vertex&#34; not in model.lower():
messages = [{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: [{&#34;type&#34;: &#34;text&#34;, &#34;text&#34;: system_prompt, &#34;cache_control&#34;: {&#34;type&#34;: &#34;ephemeral&#34;}}]}]
else:
messages = [{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: system_prompt}]
# Interleaving de historial
last_role = &#34;system&#34;
# Sanitize history if the current target model is not compatible with cache_control
history_to_process = chat_history[-self.max_history:]
if &#34;claude&#34; not in model.lower() or &#34;vertex&#34; in model.lower():
history_to_process = self._sanitize_messages(history_to_process)
for msg in history_to_process:
m = msg if isinstance(msg, dict) else msg.model_dump(exclude_none=True)
role = m.get(&#39;role&#39;)
if role == last_role and role == &#39;user&#39;:
messages[-1][&#39;content&#39;] += &#34;\n&#34; + (m.get(&#39;content&#39;) or &#34;&#34;)
continue
if role == &#39;assistant&#39; and m.get(&#39;tool_calls&#39;) and m.get(&#39;content&#39;) == &#34;&#34;: m[&#39;content&#39;] = None
messages.append(m)
last_role = role
if last_role == &#39;user&#39;: messages[-1][&#39;content&#39;] += &#34;\n&#34; + clean_input
else: messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: clean_input})
# 3. Bucle de ejecución
iteration = 0
try:
# Set up remote interrupt callback if bridge is provided
if status and hasattr(status, &#34;on_interrupt&#34;):
status.on_interrupt = lambda: setattr(self, &#34;interrupted&#34;, True)
while iteration &lt; self.hard_limit_iterations:
iteration += 1
# Check for interruption
if self.interrupted:
raise KeyboardInterrupt
# Soft limit warning
if iteration == self.soft_limit_iterations and not soft_limit_warned:
self.console.print(f&#34;[warning]⚠ Agent has performed {iteration} steps. This is taking longer than expected.[/warning]&#34;)
self.console.print(f&#34;[warning] You can press Ctrl+C to interrupt and get a summary of progress.[/warning]&#34;)
soft_limit_warned = True
label = &#34;[architect][bold]Architect[/bold][/architect]&#34; if current_brain == &#34;architect&#34; else &#34;[engineer][bold]Engineer[/bold][/engineer]&#34;
if status:
# Notify responder identity ONLY for web/remote clients (StatusBridge has is_web)
if getattr(status, &#34;is_web&#34;, False):
status.update(f&#34;__RESPONDER__:{current_brain}&#34;)
status.update(f&#34;{label} is thinking... (step {iteration})&#34;)
streamed_response = False
try:
safe_messages = self._sanitize_messages(messages)
if stream:
response, streamed_response = self._stream_completion(
model=model, messages=safe_messages, tools=tools, api_key=key,
status=status, label=label, debug=debug, num_retries=3,
chunk_callback=chunk_callback
)
else:
response = completion(model=model, messages=safe_messages, tools=tools, api_key=key, num_retries=3)
except Exception as e:
if current_brain == &#34;architect&#34;:
if status: status.update(&#34;[unavailable]Architect unavailable! Falling back to Engineer...&#34;)
# Preserve context when falling back - use clean_input directly
current_brain = &#34;engineer&#34;
model = self.engineer_model
tools = self._get_engineer_tools()
key = self.engineer_key
# Rebuild messages with Engineer system prompt and original user request
messages = [{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: self.engineer_system_prompt}]
# Add chat history if exists (excluding system prompt)
if chat_history:
for msg in chat_history[-self.max_history:]:
if msg.get(&#39;role&#39;) != &#39;system&#39;:
messages.append(msg)
# Add current user request
messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: clean_input})
continue
else:
return {&#34;response&#34;: f&#34;Error: Both engines failed. {str(e)}&#34;, &#34;chat_history&#34;: messages[1:], &#34;usage&#34;: usage}
if hasattr(response, &#34;usage&#34;) and response.usage:
usage[&#34;input&#34;] += getattr(response.usage, &#34;prompt_tokens&#34;, 0)
usage[&#34;output&#34;] += getattr(response.usage, &#34;completion_tokens&#34;, 0)
usage[&#34;total&#34;] += getattr(response.usage, &#34;total_tokens&#34;, 0)
resp_msg = response.choices[0].message
msg_dict = resp_msg.model_dump(exclude_none=True)
if msg_dict.get(&#34;tool_calls&#34;) and msg_dict.get(&#34;content&#34;) == &#34;&#34;: msg_dict[&#34;content&#34;] = None
messages.append(msg_dict)
if debug and resp_msg.content and not streamed_response:
# In CLI debug mode, only print intermediate reasoning if there are tool calls AND it wasn&#39;t already streamed.
# If there are no tool calls, this content is the final answer and will be printed by the caller.
if resp_msg.tool_calls:
if status:
try: status.stop()
except: pass
self.console.print(Panel(Markdown(resp_msg.content), title=f&#34;[{current_brain}][bold]{label} Reasoning[/bold][/{current_brain}]&#34;, border_style=&#34;architect&#34; if current_brain == &#34;architect&#34; else &#34;engineer&#34;))
if status:
try: status.start()
except: pass
if not resp_msg.tool_calls: break
# Track if we need to inject a user message after all tool responses
pending_user_message = None
for tc in resp_msg.tool_calls:
fn, args = tc.function.name, json.loads(tc.function.arguments)
# Validate tool access based on current brain
if fn in [&#39;delegate_to_engineer&#39;] and current_brain != &#34;architect&#34;:
obs = f&#34;Error: Tool &#39;{fn}&#39; is only available to the Architect (Architect). You are the Engineer (Engineer). Use &#39;run_commands&#39; directly to execute configuration.&#34;
messages.append({&#34;tool_call_id&#34;: tc.id, &#34;role&#34;: &#34;tool&#34;, &#34;name&#34;: fn, &#34;content&#34;: obs})
continue
if status:
if fn == &#34;delegate_to_engineer&#34;: status.update(f&#34;[architect]Architect: [DELEGATING MISSION] {args.get(&#39;task&#39;,&#39;&#39;)[:40]}...&#34;)
elif fn == &#34;manage_memory_tool&#34;: status.update(f&#34;[architect]Architect: [UPDATING MEMORY]&#34;)
if debug:
self._print_debug_observation(f&#34;Decision: {fn}&#34;, args, status=status)
if fn == &#34;delegate_to_engineer&#34;:
obs, eng_usage = self._engineer_loop(args[&#34;task&#34;], status=status, debug=debug, chat_history=messages[:-1])
usage[&#34;input&#34;] += eng_usage[&#34;input&#34;]; usage[&#34;output&#34;] += eng_usage[&#34;output&#34;]; usage[&#34;total&#34;] += eng_usage[&#34;total&#34;]
elif fn == &#34;consult_architect&#34;:
if status: status.update(&#34;[architect]Engineer consulting Architect...&#34;)
try:
# Consultation only - Engineer stays in control
claude_resp = completion(
model=self.architect_model,
messages=[
{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: self.architect_system_prompt},
{&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: f&#34;The Engineer needs your strategic advice.\n\nTECHNICAL SUMMARY: {args[&#39;technical_summary&#39;]}\n\nQUESTION: {args[&#39;question&#39;]}\n\nProvide strategic guidance. The Engineer will continue handling the user.&#34;}
],
api_key=self.architect_key,
num_retries=3
)
obs = claude_resp.choices[0].message.content
if debug:
if status:
try: status.stop()
except: pass
self.console.print(Panel(Markdown(obs), title=&#34;[architect]Architect Consultation[/architect]&#34;, border_style=&#34;architect&#34;))
if status:
try: status.start()
except: pass
except Exception as e:
if status: status.update(&#34;[unavailable]Architect unavailable! Engineer continuing alone...&#34;)
obs = f&#34;Architect unavailable ({str(e)}). Proceeding with your best technical judgment.&#34;
elif fn == &#34;escalate_to_architect&#34;:
if status: status.update(&#34;[architect]Transferring control to Architect...&#34;)
# Full escalation - Architect takes over
current_brain = &#34;architect&#34;
model = self.architect_model
tools = self._get_architect_tools()
key = self.architect_key
messages[0] = {&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: self.architect_system_prompt}
# Prepare handover context to inject AFTER all tool responses
handover_msg = f&#34;HANDOVER FROM EXECUTION ENGINE\n\nReason: {args[&#39;reason&#39;]}\n\nContext: {args[&#39;context&#39;]}\n\nYou are now in control of this conversation.&#34;
pending_user_message = handover_msg
obs = &#34;Control transferred to Architect. Handover context will be provided.&#34;
if debug:
if status:
try: status.stop()
except: pass
self.console.print(Panel(Text(handover_msg), title=&#34;[architect]Escalation to Architect[/architect]&#34;, border_style=&#34;architect&#34;))
if status:
try: status.start()
except: pass
elif fn == &#34;return_to_engineer&#34;:
if status: status.update(&#34;[engineer]Transferring control back to Engineer...&#34;)
# Architect returns control to Engineer
current_brain = &#34;engineer&#34;
model = self.engineer_model
tools = self._get_engineer_tools()
key = self.engineer_key
messages[0] = {&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: self.engineer_system_prompt}
# Prepare handover context to inject AFTER all tool responses
handover_msg = f&#34;HANDOVER FROM ARCHITECT\n\nSummary: {args[&#39;summary&#39;]}\n\nYou are now back in control. Continue handling the user&#39;s requests.&#34;
pending_user_message = handover_msg
obs = &#34;Control returned to Engineer. Handover summary will be provided.&#34;
if debug:
if status:
try: status.stop()
except: pass
self.console.print(Panel(Text(handover_msg), title=&#34;[engineer]Return to Engineer[/engineer]&#34;, border_style=&#34;engineer&#34;))
if status:
try: status.start()
except: pass
elif fn == &#34;list_nodes&#34;: obs = self.list_nodes_tool(**args)
elif fn == &#34;run_commands&#34;: obs = self.run_commands_tool(**args, status=status)
elif fn == &#34;get_node_info&#34;: obs = self.get_node_info_tool(**args)
elif fn == &#34;manage_memory_tool&#34;: obs = self.manage_memory_tool(**args)
elif fn.startswith(&#34;mcp_&#34;):
obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
else: obs = f&#34;Error: {fn} unknown.&#34;
if debug and fn not in [&#34;delegate_to_engineer&#34;, &#34;consult_architect&#34;, &#34;escalate_to_architect&#34;, &#34;return_to_engineer&#34;]:
self._print_debug_observation(f&#34;Observation: {fn}&#34;, obs, status=status)
# Ensure observation is a string and truncated for the LLM
obs_str = obs if isinstance(obs, str) else json.dumps(obs)
messages.append({&#34;tool_call_id&#34;: tc.id, &#34;role&#34;: &#34;tool&#34;, &#34;name&#34;: fn, &#34;content&#34;: self._truncate(obs_str)})
# Inject pending user message AFTER all tool responses are added
if pending_user_message:
messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: pending_user_message})
if iteration &gt;= self.hard_limit_iterations:
self.console.print(f&#34;[error]⛔ Agent reached hard limit ({self.hard_limit_iterations} steps). Forcing stop to prevent infinite loop.[/error]&#34;)
# Only inject user message if we&#39;re not in the middle of tool calls
last_msg = messages[-1] if messages else {}
if last_msg.get(&#34;role&#34;) != &#34;assistant&#34; or not last_msg.get(&#34;tool_calls&#34;):
messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: &#34;Hard iteration limit reached. Please provide a summary of your findings so far.&#34;})
try:
safe_messages = self._sanitize_messages(messages)
response = completion(model=model, messages=safe_messages, tools=[], api_key=key)
resp_msg = response.choices[0].message
messages.append(resp_msg.model_dump(exclude_none=True))
except Exception as e:
if status:
status.update(f&#34;[error]Error fetching summary: {e}[/error]&#34;)
printer.warning(f&#34;Failed to fetch final summary from LLM: {e}&#34;)
except KeyboardInterrupt:
if status: status.update(&#34;[error]Interrupted! Closing pending tasks...&#34;)
last_msg = messages[-1]
if last_msg.get(&#34;tool_calls&#34;):
for tc in last_msg[&#34;tool_calls&#34;]:
messages.append({&#34;tool_call_id&#34;: tc.get(&#34;id&#34;), &#34;role&#34;: &#34;tool&#34;, &#34;name&#34;: tc.get(&#34;function&#34;, {}).get(&#34;name&#34;), &#34;content&#34;: &#34;Operation cancelled by user.&#34;})
# Use a fresh list for the summary call to avoid history corruption
summary_messages = list(messages)
summary_messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: &#34;USER INTERRUPTED. Briefly summarize what you were doing and stop.&#34;})
try:
safe_messages = self._sanitize_messages(summary_messages)
# Use tools=None to force a text summary during interruption
response = completion(model=model, messages=safe_messages, tools=None, api_key=key)
resp_msg = response.choices[0].message
messages.append(resp_msg.model_dump(exclude_none=True))
# IMPORTANT: Manually trigger callback for the summary so Web UI sees it
if chunk_callback and resp_msg.content:
chunk_callback(resp_msg.content)
except Exception:
error_msg = &#34;Operation interrupted by user. Summary unavailable.&#34;
messages.append({&#34;role&#34;: &#34;assistant&#34;, &#34;content&#34;: error_msg})
if chunk_callback:
chunk_callback(error_msg)
finally:
# Auto-save session
self.save_session(messages, model=model)
return {
&#34;response&#34;: messages[-1].get(&#34;content&#34;),
&#34;chat_history&#34;: messages[1:],
&#34;app_related&#34;: True,
&#34;usage&#34;: usage,
&#34;responder&#34;: current_brain, # &#34;architect&#34; or &#34;engineer&#34;
&#34;streamed&#34;: streamed_response
}
@MethodHook
async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
import json
import re
from litellm import acompletion
import asyncio
import warnings
import aiohttp
# Suppress unawaited coroutine warnings from LiteLLM&#39;s internal streaming logic during sudden cancellation
warnings.filterwarnings(&#34;ignore&#34;, message=&#34;coroutine &#39;.*async_streaming.*&#39; was never awaited&#34;, category=RuntimeWarning)
node_info = node_info or {}
os_info = node_info.get(&#34;os&#34;, &#34;unknown&#34;)
node_name = node_info.get(&#34;name&#34;, &#34;unknown&#34;)
persona = node_info.get(&#34;persona&#34;, &#34;engineer&#34;)
memories = node_info.get(&#34;memories&#34;, [])
vendor_reference = &#34;&#34;
if os_info and os_info != &#34;unknown&#34;:
try:
os_filename = os_info.lower().replace(&#34; &#34;, &#34;_&#34;)
ref_path = os.path.join(self.config.defaultdir, &#34;ai_references&#34;, f&#34;{os_filename}.md&#34;)
if os.path.exists(ref_path):
with open(ref_path, &#34;r&#34;) as f:
vendor_reference = f.read().strip()
except Exception:
pass
if persona == &#34;architect&#34;:
system_prompt = f&#34;&#34;&#34;Role: NETWORK ARCHITECT. You act as a senior strategic advisor during a live SSH session.
Rules:
1. Answer the user&#39;s question directly based on the Terminal Context.
2. Focus on the &#34;why&#34; and &#34;how&#34;. Analyze topologies, design patterns, and validate configurations.
3. Do NOT provide commands to execute unless specifically requested. Instead, explain the consequences and best practices.
4. Keep your guide concise and authoritative.
5. You MUST output your response in the following strict format:
&lt;guide&gt;
Your brief tactical guide in markdown.
&lt;/guide&gt;
&lt;commands&gt;
&lt;/commands&gt;
&lt;risk&gt;
low
&lt;/risk&gt;
6. Risk level is usually &#34;low&#34; for read-only/no commands.
Terminal Context:
{terminal_buffer}
Device OS: {os_info}
Node: {node_name}&#34;&#34;&#34;
else:
system_prompt = f&#34;&#34;&#34;Role: TERMINAL COPILOT. You assist a network engineer during a live SSH session.
Rules:
1. Answer the user&#39;s question directly based on the Terminal Context.
2. If the user asks you to analyze, parse, or extract data from the Terminal Context, DO IT directly in the &lt;guide&gt; section (you can use markdown tables or lists). Do NOT just give them a command to do it themselves.
3. If the user wants to execute an action, provide the required CLI commands inside a &lt;commands&gt; block, one command per line. If no commands are needed, leave it empty or omit the block.
4. ULTRA-CONCISE. Keep your guide to the point.
5. You MUST output your response in the following strict format:
&lt;guide&gt;
Your brief tactical guide in markdown. 3-4 sentences max.
&lt;/guide&gt;
&lt;commands&gt;
command 1
command 2
&lt;/commands&gt;
&lt;risk&gt;
low, high, or destructive
&lt;/risk&gt;
6. Risk level: &#34;low&#34; for read-only/no commands, &#34;high&#34; for config changes, &#34;destructive&#34; for potentially dangerous ops.
Terminal Context:
{terminal_buffer}
Device OS: {os_info}
Node: {node_name}&#34;&#34;&#34;
if vendor_reference:
system_prompt += f&#34;\n\nVendor Command Reference:\n{vendor_reference}&#34;
if memories:
system_prompt += &#34;\n\nSession Memory (Important Facts):\n&#34;
for m in memories:
system_prompt += f&#34;- {m}\n&#34;
# Fetch MCP tools for the current OS
mcp_tools = []
try:
mcp_tools = await self.mcp_manager.get_tools_for_llm(os_filter=os_info)
except Exception:
pass
if mcp_tools:
system_prompt += f&#34;\n\nAvailable MCP Tools: {&#39;, &#39;.join([t[&#39;function&#39;][&#39;name&#39;] for t in mcp_tools])}&#34;
system_prompt += &#34;\nUse these tools to validate syntax or find exact commands if needed before providing the final guide.&#34;
messages = [
{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: system_prompt},
{&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: user_question}
]
iteration = 0
max_iterations = 5 # Allow up to 5 iterations for tool usage
# Use models based on persona
current_model = self.architect_model if persona == &#34;architect&#34; else self.engineer_model
current_key = self.architect_key if persona == &#34;architect&#34; else self.engineer_key
try:
while iteration &lt; max_iterations:
iteration += 1
response = await acompletion(
model=current_model,
messages=messages,
tools=mcp_tools if mcp_tools else None,
api_key=current_key,
stream=True
)
full_content = &#34;&#34;
streamed_guide = &#34;&#34;
tool_calls = []
async for chunk in response:
delta = chunk.choices[0].delta
# Accumulate tool calls
if hasattr(delta, &#39;tool_calls&#39;) and delta.tool_calls:
for tc in delta.tool_calls:
idx = tc.index
if idx &gt;= len(tool_calls):
tool_calls.append({&#34;id&#34;: tc.id, &#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: tc.function.name or &#34;&#34;, &#34;arguments&#34;: tc.function.arguments or &#34;&#34;}})
else:
if tc.id: tool_calls[idx][&#34;id&#34;] = tc.id
if tc.function.name: tool_calls[idx][&#34;function&#34;][&#34;name&#34;] = tc.function.name
if tc.function.arguments: tool_calls[idx][&#34;function&#34;][&#34;arguments&#34;] += tc.function.arguments
if hasattr(delta, &#39;content&#39;) and delta.content:
full_content += delta.content
if chunk_callback and not tool_calls: # Only stream if not using tools
start_idx = full_content.find(&#34;&lt;guide&gt;&#34;)
if start_idx != -1:
after_start = full_content[start_idx + 7:]
end_idx = after_start.find(&#34;&lt;/guide&gt;&#34;)
if end_idx != -1:
current_guide = after_start[:end_idx]
else:
current_guide = after_start
if current_guide.endswith(&#34;&lt;&#34;): current_guide = current_guide[:-1]
elif current_guide.endswith(&#34;&lt;/&#34;): current_guide = current_guide[:-2]
elif current_guide.endswith(&#34;&lt;/g&#34;): current_guide = current_guide[:-3]
elif current_guide.endswith(&#34;&lt;/gu&#34;): current_guide = current_guide[:-4]
elif current_guide.endswith(&#34;&lt;/gui&#34;): current_guide = current_guide[:-5]
elif current_guide.endswith(&#34;&lt;/guid&#34;): current_guide = current_guide[:-6]
elif current_guide.endswith(&#34;&lt;/guide&#34;): current_guide = current_guide[:-7]
new_text = current_guide[len(streamed_guide):]
if new_text:
chunk_callback(new_text)
streamed_guide += new_text
if not tool_calls:
break
# Execute tool calls
messages.append({&#34;role&#34;: &#34;assistant&#34;, &#34;content&#34;: full_content or None, &#34;tool_calls&#34;: tool_calls})
for tc in tool_calls:
fn = tc[&#34;function&#34;][&#34;name&#34;]
args = json.loads(tc[&#34;function&#34;][&#34;arguments&#34;])
if &#34;mcp_&#34; in fn:
try:
obs = await asyncio.wait_for(self.mcp_manager.call_tool(fn, args), timeout=30.0)
except Exception as e:
obs = f&#34;Error calling MCP tool: {e}&#34;
else:
obs = f&#34;Error: Tool {fn} not allowed in Copilot.&#34;
messages.append({&#34;tool_call_id&#34;: tc[&#34;id&#34;], &#34;role&#34;: &#34;tool&#34;, &#34;name&#34;: fn, &#34;content&#34;: self._truncate(str(obs))})
# If we hit the limit and it was still using tools, force a final answer
if tool_calls and iteration &gt;= max_iterations:
messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: &#34;Tool limit reached. Provide your final tactical guide now based on the findings.&#34;})
response = await acompletion(
model=self.engineer_model,
messages=messages,
tools=None,
api_key=self.engineer_key,
stream=True
)
full_content = &#34;&#34;
streamed_guide = &#34;&#34;
async for chunk in response:
delta = chunk.choices[0].delta
if hasattr(delta, &#39;content&#39;) and delta.content:
full_content += delta.content
if chunk_callback:
start_idx = full_content.find(&#34;&lt;guide&gt;&#34;)
if start_idx != -1:
after_start = full_content[start_idx + 7:]
end_idx = after_start.find(&#34;&lt;/guide&gt;&#34;)
if end_idx != -1:
current_guide = after_start[:end_idx]
else:
current_guide = after_start
if current_guide.endswith(&#34;&lt;&#34;): current_guide = current_guide[:-1]
elif current_guide.endswith(&#34;&lt;/&#34;): current_guide = current_guide[:-2]
elif current_guide.endswith(&#34;&lt;/g&#34;): current_guide = current_guide[:-3]
elif current_guide.endswith(&#34;&lt;/gu&#34;): current_guide = current_guide[:-4]
elif current_guide.endswith(&#34;&lt;/gui&#34;): current_guide = current_guide[:-5]
elif current_guide.endswith(&#34;&lt;/guid&#34;): current_guide = current_guide[:-6]
elif current_guide.endswith(&#34;&lt;/guide&#34;): current_guide = current_guide[:-7]
new_text = current_guide[len(streamed_guide):]
if new_text:
chunk_callback(new_text)
streamed_guide += new_text
guide = &#34;&#34;
commands = []
risk_level = &#34;low&#34;
guide_match = re.search(r&#34;&lt;guide&gt;(.*?)&lt;/guide&gt;&#34;, full_content, re.DOTALL)
if guide_match:
guide = guide_match.group(1).strip()
cmd_match = re.search(r&#34;&lt;commands&gt;(.*?)&lt;/commands&gt;&#34;, full_content, re.DOTALL)
if cmd_match:
cmds_raw = cmd_match.group(1).strip()
if cmds_raw:
commands = [c.strip() for c in cmds_raw.split(&#39;\n&#39;) if c.strip()]
risk_match = re.search(r&#34;&lt;risk&gt;(.*?)&lt;/risk&gt;&#34;, full_content, re.DOTALL)
if risk_match:
risk_level = risk_match.group(1).strip().lower()
if not guide and full_content and not (&#34;&lt;guide&gt;&#34; in full_content):
guide = full_content.strip()
return {
&#34;commands&#34;: commands,
&#34;guide&#34;: guide,
&#34;risk_level&#34;: risk_level,
&#34;error&#34;: None
}
except asyncio.CancelledError:
# Client cancelled the request via gRPC or local interrupt
if &#39;response&#39; in locals():
try:
if hasattr(response, &#39;aclose&#39;):
# Fire and forget the close to avoid blocking the cancel
asyncio.create_task(response.aclose())
elif hasattr(response, &#39;close&#39;):
response.close()
except Exception:
pass
return None
except Exception as e:
return {
&#34;commands&#34;: [],
&#34;guide&#34;: &#34;&#34;,
&#34;risk_level&#34;: &#34;low&#34;,
&#34;error&#34;: str(e)
}
@MethodHook
def confirm(self, user_input): return True</code></pre>
</details>
<div class="desc"><p>Hybrid Multi-Agent System: Selective Escalation with Role Persistence.</p></div>
<h3>Class variables</h3>
<dl>
<dt id="connpy.ai.SAFE_COMMANDS"><code class="name">var <span class="ident">SAFE_COMMANDS</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
<h3>Instance variables</h3>
<dl>
<dt id="connpy.ai.architect_system_prompt"><code class="name">prop <span class="ident">architect_system_prompt</span></code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def architect_system_prompt(self):
&#34;&#34;&#34;Build architect system prompt with plugin extensions.&#34;&#34;&#34;
if self.architect_prompt_extensions:
extensions = &#34;\n&#34;.join(self.architect_prompt_extensions)
return self._architect_base_prompt + f&#34;\n\nPlugin Capabilities:\n{extensions}&#34;
return self._architect_base_prompt</code></pre>
</details>
<div class="desc"><p>Build architect system prompt with plugin extensions.</p></div>
</dd>
<dt id="connpy.ai.engineer_system_prompt"><code class="name">prop <span class="ident">engineer_system_prompt</span></code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def engineer_system_prompt(self):
&#34;&#34;&#34;Build engineer system prompt with plugin extensions.&#34;&#34;&#34;
if self.engineer_prompt_extensions:
extensions = &#34;\n&#34;.join(self.engineer_prompt_extensions)
return self._engineer_base_prompt + f&#34;\n\nPlugin Capabilities:\n{extensions}&#34;
return self._engineer_base_prompt</code></pre>
</details>
<div class="desc"><p>Build engineer system prompt with plugin extensions.</p></div>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="connpy.ai.aask_copilot"><code class="name flex">
<span>async def <span class="ident">aask_copilot</span></span>(<span>self, terminal_buffer, user_question, node_info=None, chunk_callback=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python"> @MethodHook
async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
import json
import re
from litellm import acompletion
import asyncio
import warnings
import aiohttp
# Suppress unawaited coroutine warnings from LiteLLM&#39;s internal streaming logic during sudden cancellation
warnings.filterwarnings(&#34;ignore&#34;, message=&#34;coroutine &#39;.*async_streaming.*&#39; was never awaited&#34;, category=RuntimeWarning)
node_info = node_info or {}
os_info = node_info.get(&#34;os&#34;, &#34;unknown&#34;)
node_name = node_info.get(&#34;name&#34;, &#34;unknown&#34;)
persona = node_info.get(&#34;persona&#34;, &#34;engineer&#34;)
memories = node_info.get(&#34;memories&#34;, [])
vendor_reference = &#34;&#34;
if os_info and os_info != &#34;unknown&#34;:
try:
os_filename = os_info.lower().replace(&#34; &#34;, &#34;_&#34;)
ref_path = os.path.join(self.config.defaultdir, &#34;ai_references&#34;, f&#34;{os_filename}.md&#34;)
if os.path.exists(ref_path):
with open(ref_path, &#34;r&#34;) as f:
vendor_reference = f.read().strip()
except Exception:
pass
if persona == &#34;architect&#34;:
system_prompt = f&#34;&#34;&#34;Role: NETWORK ARCHITECT. You act as a senior strategic advisor during a live SSH session.
Rules:
1. Answer the user&#39;s question directly based on the Terminal Context.
2. Focus on the &#34;why&#34; and &#34;how&#34;. Analyze topologies, design patterns, and validate configurations.
3. Do NOT provide commands to execute unless specifically requested. Instead, explain the consequences and best practices.
4. Keep your guide concise and authoritative.
5. You MUST output your response in the following strict format:
&lt;guide&gt;
Your brief tactical guide in markdown.
&lt;/guide&gt;
&lt;commands&gt;
&lt;/commands&gt;
&lt;risk&gt;
low
&lt;/risk&gt;
6. Risk level is usually &#34;low&#34; for read-only/no commands.
Terminal Context:
{terminal_buffer}
Device OS: {os_info}
Node: {node_name}&#34;&#34;&#34;
else:
system_prompt = f&#34;&#34;&#34;Role: TERMINAL COPILOT. You assist a network engineer during a live SSH session.
Rules:
1. Answer the user&#39;s question directly based on the Terminal Context.
2. If the user asks you to analyze, parse, or extract data from the Terminal Context, DO IT directly in the &lt;guide&gt; section (you can use markdown tables or lists). Do NOT just give them a command to do it themselves.
3. If the user wants to execute an action, provide the required CLI commands inside a &lt;commands&gt; block, one command per line. If no commands are needed, leave it empty or omit the block.
4. ULTRA-CONCISE. Keep your guide to the point.
5. You MUST output your response in the following strict format:
&lt;guide&gt;
Your brief tactical guide in markdown. 3-4 sentences max.
&lt;/guide&gt;
&lt;commands&gt;
command 1
command 2
&lt;/commands&gt;
&lt;risk&gt;
low, high, or destructive
&lt;/risk&gt;
6. Risk level: &#34;low&#34; for read-only/no commands, &#34;high&#34; for config changes, &#34;destructive&#34; for potentially dangerous ops.
Terminal Context:
{terminal_buffer}
Device OS: {os_info}
Node: {node_name}&#34;&#34;&#34;
if vendor_reference:
system_prompt += f&#34;\n\nVendor Command Reference:\n{vendor_reference}&#34;
if memories:
system_prompt += &#34;\n\nSession Memory (Important Facts):\n&#34;
for m in memories:
system_prompt += f&#34;- {m}\n&#34;
# Fetch MCP tools for the current OS
mcp_tools = []
try:
mcp_tools = await self.mcp_manager.get_tools_for_llm(os_filter=os_info)
except Exception:
pass
if mcp_tools:
system_prompt += f&#34;\n\nAvailable MCP Tools: {&#39;, &#39;.join([t[&#39;function&#39;][&#39;name&#39;] for t in mcp_tools])}&#34;
system_prompt += &#34;\nUse these tools to validate syntax or find exact commands if needed before providing the final guide.&#34;
messages = [
{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: system_prompt},
{&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: user_question}
]
iteration = 0
max_iterations = 5 # Allow up to 5 iterations for tool usage
# Use models based on persona
current_model = self.architect_model if persona == &#34;architect&#34; else self.engineer_model
current_key = self.architect_key if persona == &#34;architect&#34; else self.engineer_key
try:
while iteration &lt; max_iterations:
iteration += 1
response = await acompletion(
model=current_model,
messages=messages,
tools=mcp_tools if mcp_tools else None,
api_key=current_key,
stream=True
)
full_content = &#34;&#34;
streamed_guide = &#34;&#34;
tool_calls = []
async for chunk in response:
delta = chunk.choices[0].delta
# Accumulate tool calls
if hasattr(delta, &#39;tool_calls&#39;) and delta.tool_calls:
for tc in delta.tool_calls:
idx = tc.index
if idx &gt;= len(tool_calls):
tool_calls.append({&#34;id&#34;: tc.id, &#34;type&#34;: &#34;function&#34;, &#34;function&#34;: {&#34;name&#34;: tc.function.name or &#34;&#34;, &#34;arguments&#34;: tc.function.arguments or &#34;&#34;}})
else:
if tc.id: tool_calls[idx][&#34;id&#34;] = tc.id
if tc.function.name: tool_calls[idx][&#34;function&#34;][&#34;name&#34;] = tc.function.name
if tc.function.arguments: tool_calls[idx][&#34;function&#34;][&#34;arguments&#34;] += tc.function.arguments
if hasattr(delta, &#39;content&#39;) and delta.content:
full_content += delta.content
if chunk_callback and not tool_calls: # Only stream if not using tools
start_idx = full_content.find(&#34;&lt;guide&gt;&#34;)
if start_idx != -1:
after_start = full_content[start_idx + 7:]
end_idx = after_start.find(&#34;&lt;/guide&gt;&#34;)
if end_idx != -1:
current_guide = after_start[:end_idx]
else:
current_guide = after_start
if current_guide.endswith(&#34;&lt;&#34;): current_guide = current_guide[:-1]
elif current_guide.endswith(&#34;&lt;/&#34;): current_guide = current_guide[:-2]
elif current_guide.endswith(&#34;&lt;/g&#34;): current_guide = current_guide[:-3]
elif current_guide.endswith(&#34;&lt;/gu&#34;): current_guide = current_guide[:-4]
elif current_guide.endswith(&#34;&lt;/gui&#34;): current_guide = current_guide[:-5]
elif current_guide.endswith(&#34;&lt;/guid&#34;): current_guide = current_guide[:-6]
elif current_guide.endswith(&#34;&lt;/guide&#34;): current_guide = current_guide[:-7]
new_text = current_guide[len(streamed_guide):]
if new_text:
chunk_callback(new_text)
streamed_guide += new_text
if not tool_calls:
break
# Execute tool calls
messages.append({&#34;role&#34;: &#34;assistant&#34;, &#34;content&#34;: full_content or None, &#34;tool_calls&#34;: tool_calls})
for tc in tool_calls:
fn = tc[&#34;function&#34;][&#34;name&#34;]
args = json.loads(tc[&#34;function&#34;][&#34;arguments&#34;])
if &#34;mcp_&#34; in fn:
try:
obs = await asyncio.wait_for(self.mcp_manager.call_tool(fn, args), timeout=30.0)
except Exception as e:
obs = f&#34;Error calling MCP tool: {e}&#34;
else:
obs = f&#34;Error: Tool {fn} not allowed in Copilot.&#34;
messages.append({&#34;tool_call_id&#34;: tc[&#34;id&#34;], &#34;role&#34;: &#34;tool&#34;, &#34;name&#34;: fn, &#34;content&#34;: self._truncate(str(obs))})
# If we hit the limit and it was still using tools, force a final answer
if tool_calls and iteration &gt;= max_iterations:
messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: &#34;Tool limit reached. Provide your final tactical guide now based on the findings.&#34;})
response = await acompletion(
model=self.engineer_model,
messages=messages,
tools=None,
api_key=self.engineer_key,
stream=True
)
full_content = &#34;&#34;
streamed_guide = &#34;&#34;
async for chunk in response:
delta = chunk.choices[0].delta
if hasattr(delta, &#39;content&#39;) and delta.content:
full_content += delta.content
if chunk_callback:
start_idx = full_content.find(&#34;&lt;guide&gt;&#34;)
if start_idx != -1:
after_start = full_content[start_idx + 7:]
end_idx = after_start.find(&#34;&lt;/guide&gt;&#34;)
if end_idx != -1:
current_guide = after_start[:end_idx]
else:
current_guide = after_start
if current_guide.endswith(&#34;&lt;&#34;): current_guide = current_guide[:-1]
elif current_guide.endswith(&#34;&lt;/&#34;): current_guide = current_guide[:-2]
elif current_guide.endswith(&#34;&lt;/g&#34;): current_guide = current_guide[:-3]
elif current_guide.endswith(&#34;&lt;/gu&#34;): current_guide = current_guide[:-4]
elif current_guide.endswith(&#34;&lt;/gui&#34;): current_guide = current_guide[:-5]
elif current_guide.endswith(&#34;&lt;/guid&#34;): current_guide = current_guide[:-6]
elif current_guide.endswith(&#34;&lt;/guide&#34;): current_guide = current_guide[:-7]
new_text = current_guide[len(streamed_guide):]
if new_text:
chunk_callback(new_text)
streamed_guide += new_text
guide = &#34;&#34;
commands = []
risk_level = &#34;low&#34;
guide_match = re.search(r&#34;&lt;guide&gt;(.*?)&lt;/guide&gt;&#34;, full_content, re.DOTALL)
if guide_match:
guide = guide_match.group(1).strip()
cmd_match = re.search(r&#34;&lt;commands&gt;(.*?)&lt;/commands&gt;&#34;, full_content, re.DOTALL)
if cmd_match:
cmds_raw = cmd_match.group(1).strip()
if cmds_raw:
commands = [c.strip() for c in cmds_raw.split(&#39;\n&#39;) if c.strip()]
risk_match = re.search(r&#34;&lt;risk&gt;(.*?)&lt;/risk&gt;&#34;, full_content, re.DOTALL)
if risk_match:
risk_level = risk_match.group(1).strip().lower()
if not guide and full_content and not (&#34;&lt;guide&gt;&#34; in full_content):
guide = full_content.strip()
return {
&#34;commands&#34;: commands,
&#34;guide&#34;: guide,
&#34;risk_level&#34;: risk_level,
&#34;error&#34;: None
}
except asyncio.CancelledError:
# Client cancelled the request via gRPC or local interrupt
if &#39;response&#39; in locals():
try:
if hasattr(response, &#39;aclose&#39;):
# Fire and forget the close to avoid blocking the cancel
asyncio.create_task(response.aclose())
elif hasattr(response, &#39;close&#39;):
response.close()
except Exception:
pass
return None
except Exception as e:
return {
&#34;commands&#34;: [],
&#34;guide&#34;: &#34;&#34;,
&#34;risk_level&#34;: &#34;low&#34;,
&#34;error&#34;: str(e)
}</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.ai.ask"><code class="name flex">
<span>def <span class="ident">ask</span></span>(<span>self,<br>user_input,<br>dryrun=False,<br>chat_history=None,<br>status=None,<br>debug=False,<br>stream=True,<br>session_id=None,<br>chunk_callback=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def ask(self, user_input, dryrun=False, chat_history=None, status=None, debug=False, stream=True, session_id=None, chunk_callback=None):
if not self.engineer_key:
raise ValueError(&#34;Engineer API key not configured. Use &#39;connpy config --engineer-api-key &lt;key&gt;&#39; to set it.&#34;)
if chat_history is None: chat_history = []
# Load session if provided and history is empty
if session_id and not chat_history:
session_data = self.load_session_data(session_id)
if session_data:
chat_history = session_data.get(&#34;history&#34;, [])
# If we loaded history, the caller might need it back
# But typically ask() is called in a loop with an external history object
usage = {&#34;input&#34;: 0, &#34;output&#34;: 0, &#34;total&#34;: 0}
# 1. Selector de Rol inicial (Sticky Brain)
explicit_architect = re.match(r&#39;^(architect|arquitecto|@architect)[:\s]&#39;, user_input, re.I)
explicit_engineer = re.match(r&#39;^(engineer|ingeniero|@engineer)[:\s]&#39;, user_input, re.I)
if explicit_architect:
current_brain = &#34;architect&#34;
elif explicit_engineer:
current_brain = &#34;engineer&#34;
else:
# Sticky Brain: Detectar si el Arquitecto estaba al mando en el historial reciente
is_architect_active = False
for msg in reversed(chat_history[-5:]):
tcs = msg.get(&#39;tool_calls&#39;) if isinstance(msg, dict) else getattr(msg, &#39;tool_calls&#39;, None)
if tcs:
for tc in tcs:
fn = tc.get(&#39;function&#39;, {}).get(&#39;name&#39;) if isinstance(tc, dict) else getattr(getattr(tc, &#39;function&#39;, None), &#39;name&#39;, &#39;&#39;)
# Architect stays in control if delegating tasks or if Engineer escalated to them
# consult_architect is just Engineer asking for advice - Engineer keeps control
if fn in [&#39;delegate_to_engineer&#39;, &#39;escalate_to_architect&#39;]:
is_architect_active = True; break
if is_architect_active: break
current_brain = &#34;architect&#34; if is_architect_active else &#34;engineer&#34;
# 2. Preparación de mensajes y limpieza
clean_input = re.sub(r&#39;^(architect|arquitecto|engineer|ingeniero|@architect|@engineer)[:\s]+&#39;, &#39;&#39;, user_input, flags=re.IGNORECASE).strip()
system_prompt = self.architect_system_prompt if current_brain == &#34;architect&#34; else self.engineer_system_prompt
tools = self._get_architect_tools() if current_brain == &#34;architect&#34; else self._get_engineer_tools()
model = self.architect_model if current_brain == &#34;architect&#34; else self.engineer_model
key = self.architect_key if current_brain == &#34;architect&#34; else self.engineer_key
# Estructura optimizada para Prompt Caching (Solo para Anthropic directo, Vertex tiene reglas distintas)
if &#34;claude&#34; in model.lower() and &#34;vertex&#34; not in model.lower():
messages = [{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: [{&#34;type&#34;: &#34;text&#34;, &#34;text&#34;: system_prompt, &#34;cache_control&#34;: {&#34;type&#34;: &#34;ephemeral&#34;}}]}]
else:
messages = [{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: system_prompt}]
# Interleaving de historial
last_role = &#34;system&#34;
# Sanitize history if the current target model is not compatible with cache_control
history_to_process = chat_history[-self.max_history:]
if &#34;claude&#34; not in model.lower() or &#34;vertex&#34; in model.lower():
history_to_process = self._sanitize_messages(history_to_process)
for msg in history_to_process:
m = msg if isinstance(msg, dict) else msg.model_dump(exclude_none=True)
role = m.get(&#39;role&#39;)
if role == last_role and role == &#39;user&#39;:
messages[-1][&#39;content&#39;] += &#34;\n&#34; + (m.get(&#39;content&#39;) or &#34;&#34;)
continue
if role == &#39;assistant&#39; and m.get(&#39;tool_calls&#39;) and m.get(&#39;content&#39;) == &#34;&#34;: m[&#39;content&#39;] = None
messages.append(m)
last_role = role
if last_role == &#39;user&#39;: messages[-1][&#39;content&#39;] += &#34;\n&#34; + clean_input
else: messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: clean_input})
# 3. Bucle de ejecución
iteration = 0
try:
# Set up remote interrupt callback if bridge is provided
if status and hasattr(status, &#34;on_interrupt&#34;):
status.on_interrupt = lambda: setattr(self, &#34;interrupted&#34;, True)
while iteration &lt; self.hard_limit_iterations:
iteration += 1
# Check for interruption
if self.interrupted:
raise KeyboardInterrupt
# Soft limit warning
if iteration == self.soft_limit_iterations and not soft_limit_warned:
self.console.print(f&#34;[warning]⚠ Agent has performed {iteration} steps. This is taking longer than expected.[/warning]&#34;)
self.console.print(f&#34;[warning] You can press Ctrl+C to interrupt and get a summary of progress.[/warning]&#34;)
soft_limit_warned = True
label = &#34;[architect][bold]Architect[/bold][/architect]&#34; if current_brain == &#34;architect&#34; else &#34;[engineer][bold]Engineer[/bold][/engineer]&#34;
if status:
# Notify responder identity ONLY for web/remote clients (StatusBridge has is_web)
if getattr(status, &#34;is_web&#34;, False):
status.update(f&#34;__RESPONDER__:{current_brain}&#34;)
status.update(f&#34;{label} is thinking... (step {iteration})&#34;)
streamed_response = False
try:
safe_messages = self._sanitize_messages(messages)
if stream:
response, streamed_response = self._stream_completion(
model=model, messages=safe_messages, tools=tools, api_key=key,
status=status, label=label, debug=debug, num_retries=3,
chunk_callback=chunk_callback
)
else:
response = completion(model=model, messages=safe_messages, tools=tools, api_key=key, num_retries=3)
except Exception as e:
if current_brain == &#34;architect&#34;:
if status: status.update(&#34;[unavailable]Architect unavailable! Falling back to Engineer...&#34;)
# Preserve context when falling back - use clean_input directly
current_brain = &#34;engineer&#34;
model = self.engineer_model
tools = self._get_engineer_tools()
key = self.engineer_key
# Rebuild messages with Engineer system prompt and original user request
messages = [{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: self.engineer_system_prompt}]
# Add chat history if exists (excluding system prompt)
if chat_history:
for msg in chat_history[-self.max_history:]:
if msg.get(&#39;role&#39;) != &#39;system&#39;:
messages.append(msg)
# Add current user request
messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: clean_input})
continue
else:
return {&#34;response&#34;: f&#34;Error: Both engines failed. {str(e)}&#34;, &#34;chat_history&#34;: messages[1:], &#34;usage&#34;: usage}
if hasattr(response, &#34;usage&#34;) and response.usage:
usage[&#34;input&#34;] += getattr(response.usage, &#34;prompt_tokens&#34;, 0)
usage[&#34;output&#34;] += getattr(response.usage, &#34;completion_tokens&#34;, 0)
usage[&#34;total&#34;] += getattr(response.usage, &#34;total_tokens&#34;, 0)
resp_msg = response.choices[0].message
msg_dict = resp_msg.model_dump(exclude_none=True)
if msg_dict.get(&#34;tool_calls&#34;) and msg_dict.get(&#34;content&#34;) == &#34;&#34;: msg_dict[&#34;content&#34;] = None
messages.append(msg_dict)
if debug and resp_msg.content and not streamed_response:
# In CLI debug mode, only print intermediate reasoning if there are tool calls AND it wasn&#39;t already streamed.
# If there are no tool calls, this content is the final answer and will be printed by the caller.
if resp_msg.tool_calls:
if status:
try: status.stop()
except: pass
self.console.print(Panel(Markdown(resp_msg.content), title=f&#34;[{current_brain}][bold]{label} Reasoning[/bold][/{current_brain}]&#34;, border_style=&#34;architect&#34; if current_brain == &#34;architect&#34; else &#34;engineer&#34;))
if status:
try: status.start()
except: pass
if not resp_msg.tool_calls: break
# Track if we need to inject a user message after all tool responses
pending_user_message = None
for tc in resp_msg.tool_calls:
fn, args = tc.function.name, json.loads(tc.function.arguments)
# Validate tool access based on current brain
if fn in [&#39;delegate_to_engineer&#39;] and current_brain != &#34;architect&#34;:
obs = f&#34;Error: Tool &#39;{fn}&#39; is only available to the Architect (Architect). You are the Engineer (Engineer). Use &#39;run_commands&#39; directly to execute configuration.&#34;
messages.append({&#34;tool_call_id&#34;: tc.id, &#34;role&#34;: &#34;tool&#34;, &#34;name&#34;: fn, &#34;content&#34;: obs})
continue
if status:
if fn == &#34;delegate_to_engineer&#34;: status.update(f&#34;[architect]Architect: [DELEGATING MISSION] {args.get(&#39;task&#39;,&#39;&#39;)[:40]}...&#34;)
elif fn == &#34;manage_memory_tool&#34;: status.update(f&#34;[architect]Architect: [UPDATING MEMORY]&#34;)
if debug:
self._print_debug_observation(f&#34;Decision: {fn}&#34;, args, status=status)
if fn == &#34;delegate_to_engineer&#34;:
obs, eng_usage = self._engineer_loop(args[&#34;task&#34;], status=status, debug=debug, chat_history=messages[:-1])
usage[&#34;input&#34;] += eng_usage[&#34;input&#34;]; usage[&#34;output&#34;] += eng_usage[&#34;output&#34;]; usage[&#34;total&#34;] += eng_usage[&#34;total&#34;]
elif fn == &#34;consult_architect&#34;:
if status: status.update(&#34;[architect]Engineer consulting Architect...&#34;)
try:
# Consultation only - Engineer stays in control
claude_resp = completion(
model=self.architect_model,
messages=[
{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: self.architect_system_prompt},
{&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: f&#34;The Engineer needs your strategic advice.\n\nTECHNICAL SUMMARY: {args[&#39;technical_summary&#39;]}\n\nQUESTION: {args[&#39;question&#39;]}\n\nProvide strategic guidance. The Engineer will continue handling the user.&#34;}
],
api_key=self.architect_key,
num_retries=3
)
obs = claude_resp.choices[0].message.content
if debug:
if status:
try: status.stop()
except: pass
self.console.print(Panel(Markdown(obs), title=&#34;[architect]Architect Consultation[/architect]&#34;, border_style=&#34;architect&#34;))
if status:
try: status.start()
except: pass
except Exception as e:
if status: status.update(&#34;[unavailable]Architect unavailable! Engineer continuing alone...&#34;)
obs = f&#34;Architect unavailable ({str(e)}). Proceeding with your best technical judgment.&#34;
elif fn == &#34;escalate_to_architect&#34;:
if status: status.update(&#34;[architect]Transferring control to Architect...&#34;)
# Full escalation - Architect takes over
current_brain = &#34;architect&#34;
model = self.architect_model
tools = self._get_architect_tools()
key = self.architect_key
messages[0] = {&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: self.architect_system_prompt}
# Prepare handover context to inject AFTER all tool responses
handover_msg = f&#34;HANDOVER FROM EXECUTION ENGINE\n\nReason: {args[&#39;reason&#39;]}\n\nContext: {args[&#39;context&#39;]}\n\nYou are now in control of this conversation.&#34;
pending_user_message = handover_msg
obs = &#34;Control transferred to Architect. Handover context will be provided.&#34;
if debug:
if status:
try: status.stop()
except: pass
self.console.print(Panel(Text(handover_msg), title=&#34;[architect]Escalation to Architect[/architect]&#34;, border_style=&#34;architect&#34;))
if status:
try: status.start()
except: pass
elif fn == &#34;return_to_engineer&#34;:
if status: status.update(&#34;[engineer]Transferring control back to Engineer...&#34;)
# Architect returns control to Engineer
current_brain = &#34;engineer&#34;
model = self.engineer_model
tools = self._get_engineer_tools()
key = self.engineer_key
messages[0] = {&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: self.engineer_system_prompt}
# Prepare handover context to inject AFTER all tool responses
handover_msg = f&#34;HANDOVER FROM ARCHITECT\n\nSummary: {args[&#39;summary&#39;]}\n\nYou are now back in control. Continue handling the user&#39;s requests.&#34;
pending_user_message = handover_msg
obs = &#34;Control returned to Engineer. Handover summary will be provided.&#34;
if debug:
if status:
try: status.stop()
except: pass
self.console.print(Panel(Text(handover_msg), title=&#34;[engineer]Return to Engineer[/engineer]&#34;, border_style=&#34;engineer&#34;))
if status:
try: status.start()
except: pass
elif fn == &#34;list_nodes&#34;: obs = self.list_nodes_tool(**args)
elif fn == &#34;run_commands&#34;: obs = self.run_commands_tool(**args, status=status)
elif fn == &#34;get_node_info&#34;: obs = self.get_node_info_tool(**args)
elif fn == &#34;manage_memory_tool&#34;: obs = self.manage_memory_tool(**args)
elif fn.startswith(&#34;mcp_&#34;):
obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
else: obs = f&#34;Error: {fn} unknown.&#34;
if debug and fn not in [&#34;delegate_to_engineer&#34;, &#34;consult_architect&#34;, &#34;escalate_to_architect&#34;, &#34;return_to_engineer&#34;]:
self._print_debug_observation(f&#34;Observation: {fn}&#34;, obs, status=status)
# Ensure observation is a string and truncated for the LLM
obs_str = obs if isinstance(obs, str) else json.dumps(obs)
messages.append({&#34;tool_call_id&#34;: tc.id, &#34;role&#34;: &#34;tool&#34;, &#34;name&#34;: fn, &#34;content&#34;: self._truncate(obs_str)})
# Inject pending user message AFTER all tool responses are added
if pending_user_message:
messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: pending_user_message})
if iteration &gt;= self.hard_limit_iterations:
self.console.print(f&#34;[error]⛔ Agent reached hard limit ({self.hard_limit_iterations} steps). Forcing stop to prevent infinite loop.[/error]&#34;)
# Only inject user message if we&#39;re not in the middle of tool calls
last_msg = messages[-1] if messages else {}
if last_msg.get(&#34;role&#34;) != &#34;assistant&#34; or not last_msg.get(&#34;tool_calls&#34;):
messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: &#34;Hard iteration limit reached. Please provide a summary of your findings so far.&#34;})
try:
safe_messages = self._sanitize_messages(messages)
response = completion(model=model, messages=safe_messages, tools=[], api_key=key)
resp_msg = response.choices[0].message
messages.append(resp_msg.model_dump(exclude_none=True))
except Exception as e:
if status:
status.update(f&#34;[error]Error fetching summary: {e}[/error]&#34;)
printer.warning(f&#34;Failed to fetch final summary from LLM: {e}&#34;)
except KeyboardInterrupt:
if status: status.update(&#34;[error]Interrupted! Closing pending tasks...&#34;)
last_msg = messages[-1]
if last_msg.get(&#34;tool_calls&#34;):
for tc in last_msg[&#34;tool_calls&#34;]:
messages.append({&#34;tool_call_id&#34;: tc.get(&#34;id&#34;), &#34;role&#34;: &#34;tool&#34;, &#34;name&#34;: tc.get(&#34;function&#34;, {}).get(&#34;name&#34;), &#34;content&#34;: &#34;Operation cancelled by user.&#34;})
# Use a fresh list for the summary call to avoid history corruption
summary_messages = list(messages)
summary_messages.append({&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: &#34;USER INTERRUPTED. Briefly summarize what you were doing and stop.&#34;})
try:
safe_messages = self._sanitize_messages(summary_messages)
# Use tools=None to force a text summary during interruption
response = completion(model=model, messages=safe_messages, tools=None, api_key=key)
resp_msg = response.choices[0].message
messages.append(resp_msg.model_dump(exclude_none=True))
# IMPORTANT: Manually trigger callback for the summary so Web UI sees it
if chunk_callback and resp_msg.content:
chunk_callback(resp_msg.content)
except Exception:
error_msg = &#34;Operation interrupted by user. Summary unavailable.&#34;
messages.append({&#34;role&#34;: &#34;assistant&#34;, &#34;content&#34;: error_msg})
if chunk_callback:
chunk_callback(error_msg)
finally:
# Auto-save session
self.save_session(messages, model=model)
return {
&#34;response&#34;: messages[-1].get(&#34;content&#34;),
&#34;chat_history&#34;: messages[1:],
&#34;app_related&#34;: True,
&#34;usage&#34;: usage,
&#34;responder&#34;: current_brain, # &#34;architect&#34; or &#34;engineer&#34;
&#34;streamed&#34;: streamed_response
}</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.ai.confirm"><code class="name flex">
<span>def <span class="ident">confirm</span></span>(<span>self, user_input)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def confirm(self, user_input): return True</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="connpy.ai.delete_session"><code class="name flex">
<span>def <span class="ident">delete_session</span></span>(<span>self, session_id)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def delete_session(self, session_id):
&#34;&#34;&#34;Deletes a session by ID.&#34;&#34;&#34;
path = os.path.join(self.sessions_dir, f&#34;{session_id}.json&#34;)
if os.path.exists(path):
os.remove(path)
printer.success(f&#34;Session {session_id} deleted.&#34;)
else:
printer.error(f&#34;Session {session_id} not found.&#34;)</code></pre>
</details>
<div class="desc"><p>Deletes a session by ID.</p></div>
</dd>
<dt id="connpy.ai.get_last_session_id"><code class="name flex">
<span>def <span class="ident">get_last_session_id</span></span>(<span>self)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_last_session_id(self):
&#34;&#34;&#34;Returns the ID of the most recent session.&#34;&#34;&#34;
sessions = self._get_sessions()
return sessions[0][&#34;id&#34;] if sessions else None</code></pre>
</details>
<div class="desc"><p>Returns the ID of the most recent session.</p></div>
</dd>
<dt id="connpy.ai.get_node_info_tool"><code class="name flex">
<span>def <span class="ident">get_node_info_tool</span></span>(<span>self, node_name)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_node_info_tool(self, node_name):
&#34;&#34;&#34;Get detailed metadata for a specific node. Passwords are masked.&#34;&#34;&#34;
try:
d = self.config.getitem(node_name, extract=True)
if &#39;password&#39; in d: d[&#39;password&#39;] = &#39;***&#39;
return d
except Exception as e:
return f&#34;Error getting node info: {str(e)}&#34;</code></pre>
</details>
<div class="desc"><p>Get detailed metadata for a specific node. Passwords are masked.</p></div>
</dd>
<dt id="connpy.ai.list_nodes_tool"><code class="name flex">
<span>def <span class="ident">list_nodes_tool</span></span>(<span>self, filter_pattern='.*')</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def list_nodes_tool(self, filter_pattern=&#34;.*&#34;):
&#34;&#34;&#34;List nodes matching the filter pattern. Returns metadata for &lt;=5 nodes, names only for more.&#34;&#34;&#34;
try:
matched_names = self.config._getallnodes(filter_pattern)
if not matched_names: return &#34;No nodes found.&#34;
if len(matched_names) &lt;= 5:
matched_data = self.config.getitems(matched_names, extract=True)
res = {}
for name, data in matched_data.items():
os_tag = &#34;unknown&#34;
if isinstance(data, dict):
ts = data.get(&#34;tags&#34;)
if isinstance(ts, dict): os_tag = ts.get(&#34;os&#34;, &#34;unknown&#34;)
res[name] = {&#34;os&#34;: os_tag}
return res
return {&#34;count&#34;: len(matched_names), &#34;nodes&#34;: matched_names, &#34;note&#34;: &#34;Use &#39;get_node_info&#39; for details.&#34;}
except Exception as e:
return f&#34;Error listing nodes: {str(e)}&#34;</code></pre>
</details>
<div class="desc"><p>List nodes matching the filter pattern. Returns metadata for &lt;=5 nodes, names only for more.</p></div>
</dd>
<dt id="connpy.ai.list_sessions"><code class="name flex">
<span>def <span class="ident">list_sessions</span></span>(<span>self)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def list_sessions(self):
&#34;&#34;&#34;Prints a list of sessions using printer.table.&#34;&#34;&#34;
sessions = self._get_sessions()
if not sessions:
printer.info(&#34;No saved AI sessions found.&#34;)
return
columns = [&#34;ID&#34;, &#34;Title&#34;, &#34;Created At&#34;, &#34;Model&#34;]
rows = [[s[&#34;id&#34;], s[&#34;title&#34;], s[&#34;created_at&#34;], s[&#34;model&#34;]] for s in sessions]
printer.table(&#34;AI Persisted Sessions&#34;, columns, rows)</code></pre>
</details>
<div class="desc"><p>Prints a list of sessions using printer.table.</p></div>
</dd>
<dt id="connpy.ai.load_session_data"><code class="name flex">
<span>def <span class="ident">load_session_data</span></span>(<span>self, session_id)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def load_session_data(self, session_id):
&#34;&#34;&#34;Loads a session&#39;s raw data by ID.&#34;&#34;&#34;
path = os.path.join(self.sessions_dir, f&#34;{session_id}.json&#34;)
if os.path.exists(path):
try:
with open(path, &#34;r&#34;) as f:
data = json.load(f)
self.session_id = session_id
self.session_path = path
return data
except Exception as e:
printer.error(f&#34;Failed to load session {session_id}: {e}&#34;)
return None</code></pre>
</details>
<div class="desc"><p>Loads a session's raw data by ID.</p></div>
</dd>
<dt id="connpy.ai.manage_memory_tool"><code class="name flex">
<span>def <span class="ident">manage_memory_tool</span></span>(<span>self, content, action='append')</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def manage_memory_tool(self, content, action=&#34;append&#34;):
&#34;&#34;&#34;Save or update long-term memory. Only use when user explicitly requests it.&#34;&#34;&#34;
if not content or not content.strip():
return &#34;Error: Cannot save empty content to memory.&#34;
try:
mode = &#34;a&#34; if action == &#34;append&#34; else &#34;w&#34;
os.makedirs(os.path.dirname(self.memory_path), exist_ok=True)
with open(self.memory_path, mode) as f:
timestamp = datetime.datetime.now().strftime(&#39;%Y-%m-%d %H:%M&#39;)
f.write(f&#34;\n\n## {timestamp}\n{content.strip()}\n&#34; if action == &#34;append&#34; else content)
# Reload memory after update
with open(self.memory_path, &#34;r&#34;) as f:
self.long_term_memory = f.read()
return &#34;Memory updated successfully.&#34;
except PermissionError as e:
return f&#34;Error: Permission denied writing to memory file: {e}&#34;
except Exception as e:
return f&#34;Error updating memory: {str(e)}&#34;</code></pre>
</details>
<div class="desc"><p>Save or update long-term memory. Only use when user explicitly requests it.</p></div>
</dd>
<dt id="connpy.ai.register_ai_tool"><code class="name flex">
<span>def <span class="ident">register_ai_tool</span></span>(<span>self,<br>tool_definition,<br>handler,<br>target='engineer',<br>engineer_prompt=None,<br>architect_prompt=None,<br>status_formatter=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def register_ai_tool(self, tool_definition, handler, target=&#34;engineer&#34;, engineer_prompt=None, architect_prompt=None, status_formatter=None):
&#34;&#34;&#34;Register an external tool for the AI system.
Args:
tool_definition (dict): OpenAI-compatible tool definition.
handler (callable): Function(ai_instance, **tool_args) -&gt; str.
target (str): &#39;engineer&#39;, &#39;architect&#39;, or &#39;both&#39;.
engineer_prompt (str): Extra text for engineer system prompt.
architect_prompt (str): Extra text for architect system prompt.
status_formatter (callable): Function(args_dict) -&gt; status string.
&#34;&#34;&#34;
name = tool_definition[&#34;function&#34;][&#34;name&#34;]
# Check if already registered to prevent duplicates
if target in (&#34;engineer&#34;, &#34;both&#34;):
if not any(t[&#34;function&#34;][&#34;name&#34;] == name for t in self.external_engineer_tools):
self.external_engineer_tools.append(tool_definition)
if target in (&#34;architect&#34;, &#34;both&#34;):
if not any(t[&#34;function&#34;][&#34;name&#34;] == name for t in self.external_architect_tools):
self.external_architect_tools.append(tool_definition)
self.external_tool_handlers[name] = handler
if engineer_prompt and engineer_prompt not in self.engineer_prompt_extensions:
self.engineer_prompt_extensions.append(engineer_prompt)
if architect_prompt and architect_prompt not in self.architect_prompt_extensions:
self.architect_prompt_extensions.append(architect_prompt)
if status_formatter:
self.tool_status_formatters[name] = status_formatter</code></pre>
</details>
<div class="desc"><p>Register an external tool for the AI system.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>tool_definition</code></strong> :&ensp;<code>dict</code></dt>
<dd>OpenAI-compatible tool definition.</dd>
<dt><strong><code>handler</code></strong> :&ensp;<code>callable</code></dt>
<dd>Function(ai_instance, **tool_args) -&gt; str.</dd>
<dt><strong><code>target</code></strong> :&ensp;<code>str</code></dt>
<dd>'engineer', 'architect', or 'both'.</dd>
<dt><strong><code>engineer_prompt</code></strong> :&ensp;<code>str</code></dt>
<dd>Extra text for engineer system prompt.</dd>
<dt><strong><code>architect_prompt</code></strong> :&ensp;<code>str</code></dt>
<dd>Extra text for architect system prompt.</dd>
<dt><strong><code>status_formatter</code></strong> :&ensp;<code>callable</code></dt>
<dd>Function(args_dict) -&gt; status string.</dd>
</dl></div>
</dd>
<dt id="connpy.ai.run_commands_tool"><code class="name flex">
<span>def <span class="ident">run_commands_tool</span></span>(<span>self, nodes_filter, commands, status=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def run_commands_tool(self, nodes_filter, commands, status=None):
&#34;&#34;&#34;Execute commands on nodes matching the filter. Native interactive confirmation for unsafe commands.&#34;&#34;&#34;
# Handle if commands is a JSON string
if isinstance(commands, str):
try:
commands = json.loads(commands)
except ValueError:
commands = [c.strip() for c in commands.split(&#39;\n&#39;) if c.strip()]
# Expand multi-line commands within a list (in case the AI packs them)
if isinstance(commands, list):
expanded_commands = []
for cmd in commands:
expanded_commands.extend([c.strip() for c in str(cmd).split(&#39;\n&#39;) if c.strip()])
commands = expanded_commands
else:
commands = [str(commands)]
# Check command safety natively
if not self.trusted_session:
unsafe_commands = [cmd for cmd in commands if not self._is_safe_command(cmd)]
if unsafe_commands:
# Stop the spinner so prompt doesn&#39;t get messed up
if status: status.stop()
# Show ALL commands with unsafe ones highlighted
formatted_cmds = []
for cmd in commands:
if cmd in unsafe_commands:
formatted_cmds.append(f&#34; • [warning]{cmd}[/warning]&#34;)
else:
formatted_cmds.append(f&#34; • {cmd}&#34;)
panel_content = f&#34;Target: {nodes_filter}\nCommands:\n&#34; + &#34;\n&#34;.join(formatted_cmds)
# Use print_important if available (for remote bridges) fallback to standard print
print_fn = getattr(self.console, &#34;print_important&#34;, self.console.print)
print_fn(Panel(panel_content, title=&#34;[bold warning]⚠️ UNSAFE COMMANDS DETECTED[/bold warning]&#34;, border_style=&#34;warning&#34;))
try:
user_resp = self.confirm_handler(&#34;[bold warning]Execute? (y: yes / n: no / a: allow all this session / &lt;text&gt;: feedback)[/bold warning]&#34;, default=&#34;n&#34;)
except KeyboardInterrupt:
if status: status.update(&#34;[ai_status]Engineer: Resuming...&#34;)
self.console.print(&#34;[fail]✗ Aborted by user (Ctrl+C).[/fail]&#34;)
raise
# Resume the spinner
if status: status.update(&#34;[ai_status]Engineer: Processing user response...&#34;)
user_resp_lower = user_resp.strip().lower()
if user_resp_lower in [&#39;a&#39;, &#39;allow&#39;]:
self.trusted_session = True
self.console.print(&#34;[pass]✓ Trust Mode Enabled. All future commands in this session will execute without confirmation.[/pass]&#34;)
elif user_resp_lower in [&#39;y&#39;, &#39;yes&#39;]:
self.console.print(&#34;[pass]✓ Executing...[/pass]&#34;)
elif user_resp_lower in [&#39;n&#39;, &#39;no&#39;, &#39;&#39;, &#39;cancel&#39;]:
self.console.print(&#34;[fail]✗ Execution rejected by user.[/fail]&#34;)
return &#34;Error: User rejected execution.&#34;
else:
self.console.print(f&#34;[user_prompt]User feedback: [/user_prompt]{user_resp}&#34;)
return f&#34;User requested changes: {user_resp}. Please adjust the commands based on this feedback and try again.&#34;
try:
matched_names = self.config._getallnodes(nodes_filter)
if not matched_names: return &#34;No nodes found matching filter.&#34;
thisnodes_dict = self.config.getitems(matched_names, extract=True)
result = nodes(thisnodes_dict, config=self.config).run(commands)
return result
except Exception as e:
return f&#34;Error executing commands: {str(e)}&#34;</code></pre>
</details>
<div class="desc"><p>Execute commands on nodes matching the filter. Native interactive confirmation for unsafe commands.</p></div>
</dd>
<dt id="connpy.ai.save_session"><code class="name flex">
<span>def <span class="ident">save_session</span></span>(<span>self, history, title=None, model=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def save_session(self, history, title=None, model=None):
&#34;&#34;&#34;Saves current history to the session file.&#34;&#34;&#34;
if not self.session_id:
# Generate ID from first user query if available
first_user_msg = next((m[&#34;content&#34;] for m in history if m[&#34;role&#34;] == &#34;user&#34;), &#34;new-session&#34;)
self.session_id = self._generate_session_id(first_user_msg)
self.session_path = os.path.join(self.sessions_dir, f&#34;{self.session_id}.json&#34;)
# If it&#39;s a new file, we might want to set a better title
if not os.path.exists(self.session_path) and not title:
raw_title = next((m[&#34;content&#34;] for m in history if m[&#34;role&#34;] == &#34;user&#34;), &#34;New Session&#34;)
# Clean title: remove newlines, multiple spaces
clean_title = &#34; &#34;.join(raw_title.split())
if len(clean_title) &gt; 40:
title = clean_title[:37].strip() + &#34;...&#34;
else:
title = clean_title
try:
# Read existing metadata if it exists
metadata = {}
if os.path.exists(self.session_path):
with open(self.session_path, &#34;r&#34;) as f:
metadata = json.load(f)
metadata.update({
&#34;id&#34;: self.session_id,
&#34;title&#34;: title or metadata.get(&#34;title&#34;, &#34;New Session&#34;),
&#34;created_at&#34;: metadata.get(&#34;created_at&#34;, datetime.datetime.now().isoformat()),
&#34;updated_at&#34;: datetime.datetime.now().isoformat(),
&#34;model&#34;: model or metadata.get(&#34;model&#34;, self.engineer_model),
&#34;history&#34;: history
})
with open(self.session_path, &#34;w&#34;) as f:
json.dump(metadata, f, indent=4)
except Exception as e:
printer.error(f&#34;Failed to save session: {e}&#34;)
except Exception as e:
printer.error(f&#34;Failed to save session: {e}&#34;)</code></pre>
</details>
<div class="desc"><p>Saves current history to the session file.</p></div>
</dd>
</dl>
</dd>
<dt id="connpy.configfile"><code class="flex name class">
<span>class <span class="ident">configfile</span></span>
<span>(</span><span>conf=None, key=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@ClassHook
class configfile:
&#39;&#39;&#39; This class generates a configfile object. Containts a dictionary storing, config, nodes and profiles, normaly used by connection manager.
### Attributes:
- file (str): Path/file to config file.
- key (str): Path/file to RSA key file.
- config (dict): Dictionary containing information of connection
manager configuration.
- connections (dict): Dictionary containing all the nodes added to
connection manager.
- profiles (dict): Dictionary containing all the profiles added to
connection manager.
- privatekey (obj): Object containing the private key to encrypt
passwords.
- publickey (obj): Object containing the public key to decrypt
passwords.
&#39;&#39;&#39;
def __init__(self, conf = None, key = None):
&#39;&#39;&#39;
### Optional Parameters:
- conf (str): Path/file to config file. If left empty default
path is ~/.config/conn/config.yaml
- key (str): Path/file to RSA key file. If left empty default
path is ~/.config/conn/.osk
&#39;&#39;&#39;
home = os.path.expanduser(&#34;~&#34;)
defaultdir = home + &#39;/.config/conn&#39;
if conf is None:
# Standard path: use ~/.config/conn and respect .folder redirection
self.anchor_path = defaultdir
self.defaultdir = defaultdir
Path(defaultdir).mkdir(parents=True, exist_ok=True)
pathfile = defaultdir + &#39;/.folder&#39;
try:
with open(pathfile, &#34;r&#34;) as f:
configdir = f.read().strip()
except (FileNotFoundError, IOError):
with open(pathfile, &#34;w&#34;) as f:
f.write(str(defaultdir))
configdir = defaultdir
self.defaultdir = configdir
self.file = configdir + &#39;/config.yaml&#39;
self.key = key or (configdir + &#39;/.osk&#39;)
# Ensure redirected directories exist
Path(configdir).mkdir(parents=True, exist_ok=True)
Path(f&#34;{configdir}/plugins&#34;).mkdir(parents=True, exist_ok=True)
# Backwards compatibility: Migrate from JSON to YAML only for default path
legacy_json = configdir + &#39;/config.json&#39;
legacy_noext = configdir + &#39;/config&#39;
legacy_file = None
if os.path.exists(legacy_json): legacy_file = legacy_json
elif os.path.exists(legacy_noext): legacy_file = legacy_noext
if not os.path.exists(self.file) and legacy_file:
try:
with open(legacy_file, &#39;r&#39;) as f:
old_data = json.load(f)
if not self._validate_config(old_data):
printer.warning(f&#34;Legacy config {legacy_file} has invalid structure, skipping migration.&#34;)
else:
with open(self.file, &#39;w&#39;) as f:
yaml.dump(old_data, f, Dumper=NoAliasDumper, default_flow_style=False, sort_keys=False)
# Verify the written YAML can be read back correctly
with open(self.file, &#39;r&#39;) as f:
verify = yaml.safe_load(f)
if not self._validate_config(verify):
os.remove(self.file)
printer.warning(&#34;YAML verification failed after migration, keeping legacy config.&#34;)
else:
# Note: cachefile is derived later, we use temp one for migration sync
temp_cache = configdir + &#39;/.config.cache.json&#39;
with open(temp_cache, &#39;w&#39;) as f:
json.dump(old_data, f)
shutil.move(legacy_file, legacy_file + &#34;.backup&#34;)
printer.success(f&#34;Migrated legacy config ({len(old_data.get(&#39;connections&#39;,{}))} folders/nodes) into YAML and Cache successfully!&#34;)
except Exception as e:
if os.path.exists(self.file):
try: os.remove(self.file)
except OSError: pass
printer.warning(f&#34;Failed to migrate legacy config: {e}&#34;)
else:
# Custom path (common in tests): isolate everything to the conf parent directory
self.file = os.path.abspath(conf)
configdir = os.path.dirname(self.file)
self.anchor_path = configdir
self.defaultdir = configdir
self.key = os.path.abspath(key) if key else (configdir + &#39;/.osk&#39;)
# Sidecar files always live next to the config file (or in the redirected configdir)
self.cachefile = configdir + &#39;/.config.cache.json&#39;
self.fzf_cachefile = configdir + &#39;/.fzf_nodes_cache.txt&#39;
self.folders_cachefile = configdir + &#39;/.folders_cache.txt&#39;
self.profiles_cachefile = configdir + &#39;/.profiles_cache.txt&#39;
if os.path.exists(self.file):
config = self._loadconfig(self.file)
else:
config = self._createconfig(self.file)
self.config = config[&#34;config&#34;]
self.connections = config[&#34;connections&#34;]
self.profiles = config[&#34;profiles&#34;]
if not os.path.exists(self.key):
self._createkey(self.key)
with open(self.key) as f:
self.privatekey = RSA.import_key(f.read())
self.publickey = self.privatekey.publickey()
# Self-heal text caches if they are missing
if not os.path.exists(self.fzf_cachefile) or not os.path.exists(self.folders_cachefile) or not os.path.exists(self.profiles_cachefile):
self._generate_nodes_cache()
def _validate_config(self, data):
&#34;&#34;&#34;Verify config data has the required structure.&#34;&#34;&#34;
if not isinstance(data, dict):
return False
required = {&#34;config&#34;, &#34;connections&#34;, &#34;profiles&#34;}
return required.issubset(data.keys())
def _loadconfig(self, conf):
#Loads config file using dual cache
cache_exists = os.path.exists(self.cachefile)
yaml_time = os.path.getmtime(conf) if os.path.exists(conf) else 0
cache_time = os.path.getmtime(self.cachefile) if cache_exists else 0
if not cache_exists or yaml_time &gt; cache_time:
with open(conf, &#39;r&#39;) as f:
data = yaml.safe_load(f)
if not self._validate_config(data):
# YAML is broken, try to recover from cache
if cache_exists:
printer.warning(&#34;Config file appears corrupt, recovering from cache...&#34;)
with open(self.cachefile, &#39;r&#39;) as f:
data = json.load(f)
if self._validate_config(data):
# Re-write the YAML from good cache
with open(conf, &#39;w&#39;) as f:
yaml.dump(data, f, Dumper=NoAliasDumper, default_flow_style=False, sort_keys=False)
return data
# Both broken or no cache - create fresh
printer.error(&#34;Config file is corrupt and no valid cache exists. Creating default config.&#34;)
return self._createconfig(conf)
try:
with open(self.cachefile, &#39;w&#39;) as f:
json.dump(data, f)
except Exception:
pass
return data
else:
with open(self.cachefile, &#39;r&#39;) as f:
data = json.load(f)
if not self._validate_config(data):
# Cache broken, try yaml
with open(conf, &#39;r&#39;) as f:
data = yaml.safe_load(f)
if self._validate_config(data):
return data
# Both broken
printer.error(&#34;Both config and cache are corrupt. Creating default config.&#34;)
return self._createconfig(conf)
return data
def _createconfig(self, conf):
#Create config file (always writes defaults, safe for recovery)
defaultconfig = {&#39;config&#39;: {&#39;case&#39;: False, &#39;idletime&#39;: 30, &#39;fzf&#39;: False}, &#39;connections&#39;: {}, &#39;profiles&#39;: { &#34;default&#34;: { &#34;host&#34;:&#34;&#34;, &#34;protocol&#34;:&#34;ssh&#34;, &#34;port&#34;:&#34;&#34;, &#34;user&#34;:&#34;&#34;, &#34;password&#34;:&#34;&#34;, &#34;options&#34;:&#34;&#34;, &#34;logs&#34;:&#34;&#34;, &#34;tags&#34;: &#34;&#34;, &#34;jumphost&#34;:&#34;&#34;}}}
with open(conf, &#34;w&#34;) as f:
yaml.dump(defaultconfig, f, Dumper=NoAliasDumper, default_flow_style=False, sort_keys=False)
os.chmod(conf, 0o600)
try:
with open(self.cachefile, &#39;w&#39;) as f:
json.dump(defaultconfig, f)
except Exception:
pass
return defaultconfig
@MethodHook
def _saveconfig(self, conf):
#Save config file atomically to prevent corruption
newconfig = {&#34;config&#34;:{}, &#34;connections&#34;: {}, &#34;profiles&#34;: {}}
newconfig[&#34;config&#34;] = self.config
newconfig[&#34;connections&#34;] = self.connections
newconfig[&#34;profiles&#34;] = self.profiles
tmpfile = conf + &#39;.tmp&#39;
try:
with open(tmpfile, &#34;w&#34;) as f:
yaml.dump(newconfig, f, Dumper=NoAliasDumper, default_flow_style=False, sort_keys=False)
# Atomic replace: only overwrite original if write succeeded
shutil.move(tmpfile, conf)
with open(self.cachefile, &#34;w&#34;) as f:
json.dump(newconfig, f)
self._generate_nodes_cache()
except (IOError, OSError) as e:
printer.error(f&#34;Failed to save config: {e}&#34;)
# Clean up temp file if it exists
if os.path.exists(tmpfile):
try:
os.remove(tmpfile)
except OSError:
pass
return 1
return 0
def _generate_nodes_cache(self, nodes=None, folders=None, profiles=None):
try:
if nodes is None:
nodes = self._getallnodes()
if folders is None:
folders = self._getallfolders()
if profiles is None:
profiles = list(self.profiles.keys())
with open(self.fzf_cachefile, &#34;w&#34;) as f:
f.write(&#34;\n&#34;.join(nodes))
with open(self.folders_cachefile, &#34;w&#34;) as f:
f.write(&#34;\n&#34;.join(folders))
with open(self.profiles_cachefile, &#34;w&#34;) as f:
f.write(&#34;\n&#34;.join(profiles))
except Exception:
pass
def _createkey(self, keyfile):
#Create key file
key = RSA.generate(2048)
with open(keyfile,&#39;wb&#39;) as f:
f.write(key.export_key(&#39;PEM&#39;))
f.close()
os.chmod(keyfile, 0o600)
return key
@MethodHook
def _explode_unique(self, unique):
#Divide unique name into folder, subfolder and id
uniques = unique.split(&#34;@&#34;)
if not unique.startswith(&#34;@&#34;):
result = {&#34;id&#34;: uniques[0]}
else:
result = {}
if len(uniques) == 2:
result[&#34;folder&#34;] = uniques[1]
if result[&#34;folder&#34;] == &#34;&#34;:
return False
elif len(uniques) == 3:
result[&#34;folder&#34;] = uniques[2]
result[&#34;subfolder&#34;] = uniques[1]
if result[&#34;folder&#34;] == &#34;&#34; or result[&#34;subfolder&#34;] == &#34;&#34;:
return False
elif len(uniques) &gt; 3:
return False
return result
@MethodHook
def getitem(self, unique, keys = None, extract = False):
&#39;&#39;&#39;
Get an node or a group of nodes from configfile which can be passed to node/nodes class
### Parameters:
- unique (str): Unique name of the node or folder in config using
connection manager style: node[@subfolder][@folder]
or [@subfolder]@folder
### Optional Parameters:
- keys (list): In case you pass a folder as unique, you can filter
nodes inside the folder passing a list.
- extract (bool): If True, extract information from profiles.
Default False.
### Returns:
dict: Dictionary containing information of node or multiple
dictionaries of multiple nodes.
&#39;&#39;&#39;
uniques = self._explode_unique(unique)
if unique.startswith(&#34;@&#34;):
if uniques.keys() &gt;= {&#34;folder&#34;, &#34;subfolder&#34;}:
folder = self.connections[uniques[&#34;folder&#34;]][uniques[&#34;subfolder&#34;]]
else:
folder = self.connections[uniques[&#34;folder&#34;]]
newfolder = deepcopy(folder)
newfolder.pop(&#34;type&#34;)
for node_name in folder.keys():
if node_name == &#34;type&#34;:
continue
if &#34;type&#34; in newfolder[node_name].keys():
if newfolder[node_name][&#34;type&#34;] == &#34;subfolder&#34;:
newfolder.pop(node_name)
else:
newfolder[node_name].pop(&#34;type&#34;)
if keys != None:
newfolder = dict((k, newfolder[k]) for k in keys)
if extract:
for node_name, node_keys in newfolder.items():
for key, value in node_keys.items():
profile = re.search(&#34;^@(.*)&#34;, str(value))
if profile:
try:
newfolder[node_name][key] = self.profiles[profile.group(1)][key]
except KeyError:
newfolder[node_name][key] = &#34;&#34;
elif value == &#39;&#39; and key == &#34;protocol&#34;:
try:
newfolder[node_name][key] = self.profiles[&#34;default&#34;][key]
except KeyError:
newfolder[node_name][key] = &#34;ssh&#34;
newfolder = {&#34;{}{}&#34;.format(k,unique):v for k,v in newfolder.items()}
return newfolder
else:
if uniques.keys() &gt;= {&#34;folder&#34;, &#34;subfolder&#34;}:
node = self.connections[uniques[&#34;folder&#34;]][uniques[&#34;subfolder&#34;]][uniques[&#34;id&#34;]]
elif &#34;folder&#34; in uniques.keys():
node = self.connections[uniques[&#34;folder&#34;]][uniques[&#34;id&#34;]]
else:
node = self.connections[uniques[&#34;id&#34;]]
newnode = deepcopy(node)
newnode.pop(&#34;type&#34;)
if extract:
for key, value in newnode.items():
profile = re.search(&#34;^@(.*)&#34;, str(value))
if profile:
try:
newnode[key] = self.profiles[profile.group(1)][key]
except KeyError:
newnode[key] = &#34;&#34;
elif value == &#39;&#39; and key == &#34;protocol&#34;:
try:
newnode[key] = self.profiles[&#34;default&#34;][key]
except KeyError:
newnode[key] = &#34;ssh&#34;
return newnode
@MethodHook
def getitems(self, uniques, extract = False):
&#39;&#39;&#39;
Get a group of nodes from configfile which can be passed to node/nodes class
### Parameters:
- uniques (str/list): String name that will match hostnames
from the connection manager. It can be a
list of strings.
### Optional Parameters:
- extract (bool): If True, extract information from profiles.
Default False.
### Returns:
dict: Dictionary containing information of node or multiple
dictionaries of multiple nodes.
&#39;&#39;&#39;
nodes = {}
if isinstance(uniques, str):
uniques = [uniques]
for i in uniques:
if i.startswith(&#34;@&#34;):
if not self.config[&#34;case&#34;]:
i = i.lower()
this = self.getitem(i, extract = extract)
nodes.update(this)
else:
if not self.config[&#34;case&#34;]:
i = i.lower()
this = self.getitem(i, extract = extract)
nodes[i] = this
return nodes
@MethodHook
def _connections_add(self,*, id, host, folder=&#39;&#39;, subfolder=&#39;&#39;, options=&#39;&#39;, logs=&#39;&#39;, password=&#39;&#39;, port=&#39;&#39;, protocol=&#39;&#39;, user=&#39;&#39;, tags=&#39;&#39;, jumphost=&#39;&#39;, type = &#34;connection&#34; ):
#Add connection from config
if folder == &#39;&#39;:
self.connections[id] = {&#34;host&#34;: host, &#34;options&#34;: options, &#34;logs&#34;: logs, &#34;password&#34;: password, &#34;port&#34;: port, &#34;protocol&#34;: protocol, &#34;user&#34;: user, &#34;tags&#34;: tags,&#34;jumphost&#34;: jumphost,&#34;type&#34;: type}
elif folder != &#39;&#39; and subfolder == &#39;&#39;:
self.connections[folder][id] = {&#34;host&#34;: host, &#34;options&#34;: options, &#34;logs&#34;: logs, &#34;password&#34;: password, &#34;port&#34;: port, &#34;protocol&#34;: protocol, &#34;user&#34;: user, &#34;tags&#34;: tags, &#34;jumphost&#34;: jumphost, &#34;type&#34;: type}
elif folder != &#39;&#39; and subfolder != &#39;&#39;:
self.connections[folder][subfolder][id] = {&#34;host&#34;: host, &#34;options&#34;: options, &#34;logs&#34;: logs, &#34;password&#34;: password, &#34;port&#34;: port, &#34;protocol&#34;: protocol, &#34;user&#34;: user, &#34;tags&#34;: tags, &#34;jumphost&#34;: jumphost, &#34;type&#34;: type}
@MethodHook
def _connections_del(self,*, id, folder=&#39;&#39;, subfolder=&#39;&#39;):
#Delete connection from config
if folder == &#39;&#39;:
del self.connections[id]
elif folder != &#39;&#39; and subfolder == &#39;&#39;:
del self.connections[folder][id]
elif folder != &#39;&#39; and subfolder != &#39;&#39;:
del self.connections[folder][subfolder][id]
@MethodHook
def _folder_add(self,*, folder, subfolder = &#39;&#39;):
#Add Folder from config
if subfolder == &#39;&#39;:
if folder not in self.connections:
self.connections[folder] = {&#34;type&#34;: &#34;folder&#34;}
else:
if subfolder not in self.connections[folder]:
self.connections[folder][subfolder] = {&#34;type&#34;: &#34;subfolder&#34;}
@MethodHook
def _folder_del(self,*, folder, subfolder=&#39;&#39;):
#Delete folder from config
if subfolder == &#39;&#39;:
del self.connections[folder]
else:
del self.connections[folder][subfolder]
@MethodHook
def _profiles_add(self,*, id, host = &#39;&#39;, options=&#39;&#39;, logs=&#39;&#39;, password=&#39;&#39;, port=&#39;&#39;, protocol=&#39;&#39;, user=&#39;&#39;, tags=&#39;&#39;, jumphost=&#39;&#39; ):
#Add profile from config
self.profiles[id] = {&#34;host&#34;: host, &#34;options&#34;: options, &#34;logs&#34;: logs, &#34;password&#34;: password, &#34;port&#34;: port, &#34;protocol&#34;: protocol, &#34;user&#34;: user, &#34;tags&#34;: tags, &#34;jumphost&#34;: jumphost}
@MethodHook
def _profiles_del(self,*, id ):
#Delete profile from config
del self.profiles[id]
@MethodHook
def _getallnodes(self, filter = None):
#get all nodes on configfile
nodes = []
layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;]
folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;folder&#34;]
nodes.extend(layer1)
for f in folders:
layer2 = [k + &#34;@&#34; + f for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;]
nodes.extend(layer2)
subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;subfolder&#34;]
for s in subfolders:
layer3 = [k + &#34;@&#34; + s + &#34;@&#34; + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;]
nodes.extend(layer3)
if filter:
flat_filter = []
if isinstance(filter, str):
flat_filter = [filter]
elif isinstance(filter, list):
for item in filter:
if isinstance(item, str):
flat_filter.append(item)
else:
printer.error(&#34;Filter must be a string or a list of strings&#34;)
sys.exit(1)
nodes = [item for item in nodes if any(re.search(pattern, item) for pattern in flat_filter)]
return nodes
@MethodHook
def _getallnodesfull(self, filter = None, extract = True):
#get all nodes on configfile with all their attributes.
nodes = {}
layer1 = {k:v for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;}
folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;folder&#34;]
nodes.update(layer1)
for f in folders:
layer2 = {k + &#34;@&#34; + f:v for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;}
nodes.update(layer2)
subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;subfolder&#34;]
for s in subfolders:
layer3 = {k + &#34;@&#34; + s + &#34;@&#34; + f:v for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34;}
nodes.update(layer3)
if filter:
flat_filter = []
if isinstance(filter, str):
flat_filter = [filter]
elif isinstance(filter, list):
for item in filter:
if isinstance(item, str):
flat_filter.append(item)
else:
printer.error(&#34;Filter must be a string or a list of strings&#34;)
sys.exit(1)
flat_filter = [&#34;^(?!.*@).+$&#34; if item == &#34;@&#34; else item for item in flat_filter]
nodes = {k: v for k, v in nodes.items() if any(re.search(pattern, k) for pattern in flat_filter)}
if extract:
for node, keys in nodes.items():
for key, value in keys.items():
profile = re.search(&#34;^@(.*)&#34;, str(value))
if profile:
try:
nodes[node][key] = self.profiles[profile.group(1)][key]
except KeyError:
nodes[node][key] = &#34;&#34;
elif value == &#39;&#39; and key == &#34;protocol&#34;:
try:
nodes[node][key] = self.profiles[&#34;default&#34;][key]
except KeyError:
nodes[node][key] = &#34;ssh&#34;
return nodes
@MethodHook
def _getallfolders(self):
#get all folders on configfile
folders = [&#34;@&#34; + k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;folder&#34;]
subfolders = []
for f in folders:
s = [&#34;@&#34; + k + f for k,v in self.connections[f[1:]].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;subfolder&#34;]
subfolders.extend(s)
folders.extend(subfolders)
return folders
@MethodHook
def _profileused(self, profile):
#Return all the nodes that uses this profile.
nodes = []
layer1 = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34; and (&#34;@&#34; + profile in v.values() or ( isinstance(v.get(&#34;password&#34;),list) and &#34;@&#34; + profile in v.get(&#34;password&#34;)))]
folders = [k for k,v in self.connections.items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;folder&#34;]
nodes.extend(layer1)
for f in folders:
layer2 = [k + &#34;@&#34; + f for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34; and (&#34;@&#34; + profile in v.values() or ( isinstance(v.get(&#34;password&#34;),list) and &#34;@&#34; + profile in v.get(&#34;password&#34;)))]
nodes.extend(layer2)
subfolders = [k for k,v in self.connections[f].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;subfolder&#34;]
for s in subfolders:
layer3 = [k + &#34;@&#34; + s + &#34;@&#34; + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get(&#34;type&#34;) == &#34;connection&#34; and (&#34;@&#34; + profile in v.values() or ( isinstance(v.get(&#34;password&#34;),list) and &#34;@&#34; + profile in v.get(&#34;password&#34;)))]
nodes.extend(layer3)
return nodes
@MethodHook
def encrypt(self, password, keyfile=None):
&#39;&#39;&#39;
Encrypts password using RSA keyfile
### Parameters:
- password (str): Plaintext password to encrypt.
### Optional Parameters:
- keyfile (str): Path/file to keyfile. Default is config keyfile.
### Returns:
str: Encrypted password.
&#39;&#39;&#39;
if keyfile is None:
keyfile = self.key
with open(keyfile) as f:
key = RSA.import_key(f.read())
f.close()
publickey = key.publickey()
encryptor = PKCS1_OAEP.new(publickey)
password = encryptor.encrypt(password.encode(&#34;utf-8&#34;))
return str(password)</code></pre>
</details>
<div class="desc"><p>This class generates a configfile object. Containts a dictionary storing, config, nodes and profiles, normaly used by connection manager.</p>
<h3 id="attributes">Attributes:</h3>
<pre><code>- file (str): Path/file to config file.
- key (str): Path/file to RSA key file.
- config (dict): Dictionary containing information of connection
manager configuration.
- connections (dict): Dictionary containing all the nodes added to
connection manager.
- profiles (dict): Dictionary containing all the profiles added to
connection manager.
- privatekey (obj): Object containing the private key to encrypt
passwords.
- publickey (obj): Object containing the public key to decrypt
passwords.
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- conf (str): Path/file to config file. If left empty default
path is ~/.config/conn/config.yaml
- key (str): Path/file to RSA key file. If left empty default
path is ~/.config/conn/.osk
</code></pre></div>
<h3>Methods</h3>
<dl>
<dt id="connpy.configfile.encrypt"><code class="name flex">
<span>def <span class="ident">encrypt</span></span>(<span>self, password, keyfile=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def encrypt(self, password, keyfile=None):
&#39;&#39;&#39;
Encrypts password using RSA keyfile
### Parameters:
- password (str): Plaintext password to encrypt.
### Optional Parameters:
- keyfile (str): Path/file to keyfile. Default is config keyfile.
### Returns:
str: Encrypted password.
&#39;&#39;&#39;
if keyfile is None:
keyfile = self.key
with open(keyfile) as f:
key = RSA.import_key(f.read())
f.close()
publickey = key.publickey()
encryptor = PKCS1_OAEP.new(publickey)
password = encryptor.encrypt(password.encode(&#34;utf-8&#34;))
return str(password)</code></pre>
</details>
<div class="desc"><p>Encrypts password using RSA keyfile</p>
<h3 id="parameters">Parameters:</h3>
<pre><code>- password (str): Plaintext password to encrypt.
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- keyfile (str): Path/file to keyfile. Default is config keyfile.
</code></pre>
<h3 id="returns">Returns:</h3>
<pre><code>str: Encrypted password.
</code></pre></div>
</dd>
<dt id="connpy.configfile.getitem"><code class="name flex">
<span>def <span class="ident">getitem</span></span>(<span>self, unique, keys=None, extract=False)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def getitem(self, unique, keys = None, extract = False):
&#39;&#39;&#39;
Get an node or a group of nodes from configfile which can be passed to node/nodes class
### Parameters:
- unique (str): Unique name of the node or folder in config using
connection manager style: node[@subfolder][@folder]
or [@subfolder]@folder
### Optional Parameters:
- keys (list): In case you pass a folder as unique, you can filter
nodes inside the folder passing a list.
- extract (bool): If True, extract information from profiles.
Default False.
### Returns:
dict: Dictionary containing information of node or multiple
dictionaries of multiple nodes.
&#39;&#39;&#39;
uniques = self._explode_unique(unique)
if unique.startswith(&#34;@&#34;):
if uniques.keys() &gt;= {&#34;folder&#34;, &#34;subfolder&#34;}:
folder = self.connections[uniques[&#34;folder&#34;]][uniques[&#34;subfolder&#34;]]
else:
folder = self.connections[uniques[&#34;folder&#34;]]
newfolder = deepcopy(folder)
newfolder.pop(&#34;type&#34;)
for node_name in folder.keys():
if node_name == &#34;type&#34;:
continue
if &#34;type&#34; in newfolder[node_name].keys():
if newfolder[node_name][&#34;type&#34;] == &#34;subfolder&#34;:
newfolder.pop(node_name)
else:
newfolder[node_name].pop(&#34;type&#34;)
if keys != None:
newfolder = dict((k, newfolder[k]) for k in keys)
if extract:
for node_name, node_keys in newfolder.items():
for key, value in node_keys.items():
profile = re.search(&#34;^@(.*)&#34;, str(value))
if profile:
try:
newfolder[node_name][key] = self.profiles[profile.group(1)][key]
except KeyError:
newfolder[node_name][key] = &#34;&#34;
elif value == &#39;&#39; and key == &#34;protocol&#34;:
try:
newfolder[node_name][key] = self.profiles[&#34;default&#34;][key]
except KeyError:
newfolder[node_name][key] = &#34;ssh&#34;
newfolder = {&#34;{}{}&#34;.format(k,unique):v for k,v in newfolder.items()}
return newfolder
else:
if uniques.keys() &gt;= {&#34;folder&#34;, &#34;subfolder&#34;}:
node = self.connections[uniques[&#34;folder&#34;]][uniques[&#34;subfolder&#34;]][uniques[&#34;id&#34;]]
elif &#34;folder&#34; in uniques.keys():
node = self.connections[uniques[&#34;folder&#34;]][uniques[&#34;id&#34;]]
else:
node = self.connections[uniques[&#34;id&#34;]]
newnode = deepcopy(node)
newnode.pop(&#34;type&#34;)
if extract:
for key, value in newnode.items():
profile = re.search(&#34;^@(.*)&#34;, str(value))
if profile:
try:
newnode[key] = self.profiles[profile.group(1)][key]
except KeyError:
newnode[key] = &#34;&#34;
elif value == &#39;&#39; and key == &#34;protocol&#34;:
try:
newnode[key] = self.profiles[&#34;default&#34;][key]
except KeyError:
newnode[key] = &#34;ssh&#34;
return newnode</code></pre>
</details>
<div class="desc"><p>Get an node or a group of nodes from configfile which can be passed to node/nodes class</p>
<h3 id="parameters">Parameters:</h3>
<pre><code>- unique (str): Unique name of the node or folder in config using
connection manager style: node[@subfolder][@folder]
or [@subfolder]@folder
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- keys (list): In case you pass a folder as unique, you can filter
nodes inside the folder passing a list.
- extract (bool): If True, extract information from profiles.
Default False.
</code></pre>
<h3 id="returns">Returns:</h3>
<pre><code>dict: Dictionary containing information of node or multiple
dictionaries of multiple nodes.
</code></pre></div>
</dd>
<dt id="connpy.configfile.getitems"><code class="name flex">
<span>def <span class="ident">getitems</span></span>(<span>self, uniques, extract=False)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def getitems(self, uniques, extract = False):
&#39;&#39;&#39;
Get a group of nodes from configfile which can be passed to node/nodes class
### Parameters:
- uniques (str/list): String name that will match hostnames
from the connection manager. It can be a
list of strings.
### Optional Parameters:
- extract (bool): If True, extract information from profiles.
Default False.
### Returns:
dict: Dictionary containing information of node or multiple
dictionaries of multiple nodes.
&#39;&#39;&#39;
nodes = {}
if isinstance(uniques, str):
uniques = [uniques]
for i in uniques:
if i.startswith(&#34;@&#34;):
if not self.config[&#34;case&#34;]:
i = i.lower()
this = self.getitem(i, extract = extract)
nodes.update(this)
else:
if not self.config[&#34;case&#34;]:
i = i.lower()
this = self.getitem(i, extract = extract)
nodes[i] = this
return nodes</code></pre>
</details>
<div class="desc"><p>Get a group of nodes from configfile which can be passed to node/nodes class</p>
<h3 id="parameters">Parameters:</h3>
<pre><code>- uniques (str/list): String name that will match hostnames
from the connection manager. It can be a
list of strings.
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- extract (bool): If True, extract information from profiles.
Default False.
</code></pre>
<h3 id="returns">Returns:</h3>
<pre><code>dict: Dictionary containing information of node or multiple
dictionaries of multiple nodes.
</code></pre></div>
</dd>
</dl>
</dd>
<dt id="connpy.node"><code class="flex name class">
<span>class <span class="ident">node</span></span>
<span>(</span><span>unique,<br>host,<br>options='',<br>logs='',<br>password='',<br>port='',<br>protocol='',<br>user='',<br>config='',<br>tags='',<br>jumphost='')</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@ClassHook
class node:
&#39;&#39;&#39; This class generates a node object. Containts all the information and methods to connect and interact with a device using ssh or telnet.
### Attributes:
- output (str): Output of the commands you ran with run or test
method.
- result(bool): True if expected value is found after running
the commands using test method.
- status (int): 0 if the method run or test run successfully.
1 if connection failed.
2 if expect timeouts without prompt or EOF.
&#39;&#39;&#39;
def __init__(self, unique, host, options=&#39;&#39;, logs=&#39;&#39;, password=&#39;&#39;, port=&#39;&#39;, protocol=&#39;&#39;, user=&#39;&#39;, config=&#39;&#39;, tags=&#39;&#39;, jumphost=&#39;&#39;):
&#39;&#39;&#39;
### Parameters:
- unique (str): Unique name to assign to the node.
- host (str): IP address or hostname of the node.
### Optional Parameters:
- options (str): Additional options to pass the ssh/telnet for
connection.
- logs (str): Path/file for storing the logs. You can use
${unique},${host}, ${port}, ${user}, ${protocol}
as variables.
- password (str): Encrypted or plaintext password.
- port (str): Port to connect to node, default 22 for ssh and 23
for telnet.
- protocol (str): Select ssh, telnet, kubectl or docker. Default is ssh.
- user (str): Username to of the node.
- config (obj): Pass the object created with class configfile with
key for decryption and extra configuration if you
are using connection manager.
- tags (dict) : Tags useful for automation and personal porpuse
like &#34;os&#34;, &#34;prompt&#34; and &#34;screenleght_command&#34;
- jumphost (str): Reference another node to be used as a jumphost
&#39;&#39;&#39;
self.config = config
if config == &#39;&#39;:
self.idletime = 0
self.key = None
else:
self.idletime = config.config[&#34;idletime&#34;]
self.key = config.key
self.unique = unique
attr = {&#34;host&#34;: host, &#34;logs&#34;: logs, &#34;options&#34;:options, &#34;port&#34;: port, &#34;protocol&#34;: protocol, &#34;user&#34;: user, &#34;tags&#34;: tags, &#34;jumphost&#34;: jumphost}
for key in attr:
profile = re.search(&#34;^@(.*)&#34;, str(attr[key]))
if profile and config != &#39;&#39;:
try:
setattr(self,key,config.profiles[profile.group(1)][key])
except KeyError:
setattr(self,key,&#34;&#34;)
elif attr[key] == &#39;&#39; and key == &#34;protocol&#34;:
try:
setattr(self,key,config.profiles[&#34;default&#34;][key])
except (KeyError, AttributeError):
setattr(self,key,&#34;ssh&#34;)
else:
setattr(self,key,attr[key])
if isinstance(password,list):
self.password = []
for i, s in enumerate(password):
profile = re.search(&#34;^@(.*)&#34;, password[i])
if profile and config != &#39;&#39;:
self.password.append(config.profiles[profile.group(1)][&#34;password&#34;])
else:
self.password.append(password[i])
else:
self.password = [password]
if self.jumphost != &#34;&#34; and config != &#39;&#39;:
self.jumphost = config.getitem(self.jumphost)
for key in self.jumphost:
profile = re.search(&#34;^@(.*)&#34;, str(self.jumphost[key]))
if profile:
try:
self.jumphost[key] = config.profiles[profile.group(1)][key]
except KeyError:
self.jumphost[key] = &#34;&#34;
elif self.jumphost[key] == &#39;&#39; and key == &#34;protocol&#34;:
try:
self.jumphost[key] = config.profiles[&#34;default&#34;][key]
except KeyError:
self.jumphost[key] = &#34;ssh&#34;
if isinstance(self.jumphost[&#34;password&#34;],list):
jumphost_password = []
for i, s in enumerate(self.jumphost[&#34;password&#34;]):
profile = re.search(&#34;^@(.*)&#34;, self.jumphost[&#34;password&#34;][i])
if profile:
jumphost_password.append(config.profiles[profile.group(1)][&#34;password&#34;])
else:
jumphost_password.append(self.jumphost[&#34;password&#34;][i])
self.jumphost[&#34;password&#34;] = jumphost_password
else:
self.jumphost[&#34;password&#34;] = [self.jumphost[&#34;password&#34;]]
if self.jumphost[&#34;password&#34;] != [&#34;&#34;]:
self.password = self.jumphost[&#34;password&#34;] + self.password
if self.jumphost[&#34;protocol&#34;] == &#34;ssh&#34;:
jumphost_cmd = self.jumphost[&#34;protocol&#34;] + &#34; -W %h:%p&#34;
if self.jumphost[&#34;port&#34;] != &#39;&#39;:
jumphost_cmd = jumphost_cmd + &#34; -p &#34; + self.jumphost[&#34;port&#34;]
if self.jumphost[&#34;options&#34;] != &#39;&#39;:
jumphost_cmd = jumphost_cmd + &#34; &#34; + self.jumphost[&#34;options&#34;]
if self.jumphost[&#34;user&#34;] == &#39;&#39;:
jumphost_cmd = jumphost_cmd + &#34; {}&#34;.format(self.jumphost[&#34;host&#34;])
else:
jumphost_cmd = jumphost_cmd + &#34; {}&#34;.format(&#34;@&#34;.join([self.jumphost[&#34;user&#34;],self.jumphost[&#34;host&#34;]]))
self.jumphost = f&#34;-o ProxyCommand=\&#34;{jumphost_cmd}\&#34;&#34;
elif self.jumphost[&#34;protocol&#34;] == &#34;ssm&#34;:
ssm_target = self.jumphost[&#34;host&#34;]
ssm_cmd = f&#34;aws ssm start-session --target {ssm_target} --document-name AWS-StartSSHSession --parameters &#39;portNumber=22&#39;&#34;
if isinstance(self.jumphost.get(&#34;tags&#34;), dict):
if &#34;profile&#34; in self.jumphost[&#34;tags&#34;]:
ssm_cmd += f&#34; --profile {self.jumphost[&#39;tags&#39;][&#39;profile&#39;]}&#34;
if &#34;region&#34; in self.jumphost[&#34;tags&#34;]:
ssm_cmd += f&#34; --region {self.jumphost[&#39;tags&#39;][&#39;region&#39;]}&#34;
if self.jumphost[&#34;options&#34;] != &#39;&#39;:
ssm_cmd += f&#34; {self.jumphost[&#39;options&#39;]}&#34;
bastion_user_part = f&#34;{self.jumphost[&#39;user&#39;]}@{ssm_target}&#34; if self.jumphost[&#39;user&#39;] else ssm_target
ssh_opts = &#34;&#34;
if isinstance(self.jumphost.get(&#34;tags&#34;), dict) and &#34;ssh_options&#34; in self.jumphost[&#34;tags&#34;]:
ssh_opts = f&#34; {self.jumphost[&#39;tags&#39;][&#39;ssh_options&#39;]}&#34;
inner_ssh = f&#34;ssh{ssh_opts} -o ProxyCommand=&#39;{ssm_cmd}&#39; -W %h:%p {bastion_user_part}&#34;
self.jumphost = f&#34;-o ProxyCommand=\&#34;{inner_ssh}\&#34;&#34;
elif self.jumphost[&#34;protocol&#34;] in [&#34;kubectl&#34;, &#34;docker&#34;]:
nc_cmd = &#34;nc&#34;
if isinstance(self.jumphost.get(&#34;tags&#34;), dict) and &#34;nc_command&#34; in self.jumphost[&#34;tags&#34;]:
nc_cmd = self.jumphost[&#34;tags&#34;][&#34;nc_command&#34;]
if self.jumphost[&#34;protocol&#34;] == &#34;kubectl&#34;:
proxy_cmd = f&#34;kubectl exec &#34;
if self.jumphost[&#34;options&#34;] != &#39;&#39;:
proxy_cmd += f&#34;{self.jumphost[&#39;options&#39;]} &#34;
proxy_cmd += f&#34;{self.jumphost[&#39;host&#39;]} -i -- {nc_cmd} %h %p&#34;
else:
proxy_cmd = f&#34;docker &#34;
if self.jumphost[&#34;options&#34;] != &#39;&#39;:
proxy_cmd += f&#34;{self.jumphost[&#39;options&#39;]} &#34;
proxy_cmd += f&#34;exec -i {self.jumphost[&#39;host&#39;]} {nc_cmd} %h %p&#34;
self.jumphost = f&#34;-o ProxyCommand=\&#34;{proxy_cmd}\&#34;&#34;
else:
self.jumphost = &#34;&#34;
self.output = &#34;&#34;
self.status = 1
self.result = {}
@MethodHook
def _passtx(self, passwords, *, keyfile=None):
# decrypts passwords, used by other methdos.
dpass = []
if keyfile is None:
keyfile = self.key
if keyfile is not None:
with open(keyfile) as f:
key = RSA.import_key(f.read())
decryptor = PKCS1_OAEP.new(key)
for passwd in passwords:
if not re.match(&#39;^b[\&#34;\&#39;].+[\&#34;\&#39;]$&#39;, passwd):
dpass.append(passwd)
else:
try:
decrypted = decryptor.decrypt(ast.literal_eval(passwd)).decode(&#34;utf-8&#34;)
dpass.append(decrypted)
except Exception:
printer.error(&#34;Decryption failed: Missing or corrupted key.&#34;)
printer.info(&#34;Verify your RSA key and configuration settings.&#34;)
sys.exit(1)
return dpass
@MethodHook
def _logfile(self, logfile = None):
# translate logs variables and generate logs path.
if logfile == None:
logfile = self.logs
logfile = logfile.replace(&#34;${unique}&#34;, self.unique)
logfile = logfile.replace(&#34;${host}&#34;, self.host)
logfile = logfile.replace(&#34;${port}&#34;, self.port)
logfile = logfile.replace(&#34;${user}&#34;, self.user)
logfile = logfile.replace(&#34;${protocol}&#34;, self.protocol)
now = datetime.datetime.now()
dateconf = re.search(r&#39;\$\{date \&#39;(.*)\&#39;}&#39;, logfile)
if dateconf:
logfile = re.sub(r&#39;\$\{date (.*)}&#39;,now.strftime(dateconf.group(1)), logfile)
return logfile
@MethodHook
def _logclean(self, logfile, var = False):
&#34;&#34;&#34;Remove special ascii characters and process terminal cursor movements to clean logs.&#34;&#34;&#34;
from .utils import log_cleaner
if var == False:
try:
with open(logfile, &#34;r&#34;) as f:
t = f.read()
except:
return
else:
t = logfile
result = log_cleaner(t)
if var == False:
try:
with open(logfile, &#34;w&#34;) as f:
f.write(result)
except:
pass
return
else:
return result
@MethodHook
def _savelog(self):
&#39;&#39;&#39;Save the log buffer to the file at regular intervals if there are changes.&#39;&#39;&#39;
t = threading.current_thread()
prev_size = 0 # Store the previous size of the buffer
while getattr(t, &#34;do_run&#34;, True): # Check if thread is signaled to stop
current_size = self.mylog.tell() # Current size of the buffer
# Only save if the buffer size has changed
if current_size != prev_size:
with open(self.logfile, &#34;w&#34;) as f: # Use &#34;w&#34; to overwrite the file
f.write(self._logclean(self.mylog.getvalue().decode(), True))
prev_size = current_size # Update the previous size
sleep(5)
@MethodHook
def _filter(self, a):
#Set time for last input when using interact
self.lastinput = time()
return a
@MethodHook
def _keepalive(self):
#Send keepalive ctrl+e when idletime passed without new inputs on interact
self.lastinput = time()
t = threading.current_thread()
while True:
if time() - self.lastinput &gt;= self.idletime:
self.child.sendcontrol(&#34;e&#34;)
self.lastinput = time()
sleep(1)
def _setup_interact_environment(self, debug=False, logger=None, async_mode=False):
size = re.search(&#39;columns=([0-9]+).*lines=([0-9]+)&#39;,str(os.get_terminal_size()))
self.child.setwinsize(int(size.group(2)),int(size.group(1)))
if logger:
port_str = f&#34;:{self.port}&#34; if self.port and self.protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34;
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}&#34;)
# Always initialize self.mylog to capture terminal context for the AI Copilot
if not hasattr(self, &#39;mylog&#39;):
self.mylog = io.BytesIO()
if not async_mode:
self.child.logfile_read = self.mylog
# Only start disk-logging tasks if logfile is configured
if &#39;logfile&#39; in dir(self):
if not async_mode:
# Start the _savelog thread (sync mode)
log_thread = threading.Thread(target=self._savelog)
log_thread.daemon = True
log_thread.start()
if &#39;missingtext&#39; in dir(self):
print(self.child.after.decode(), end=&#39;&#39;)
if self.idletime &gt; 0 and not async_mode:
x = threading.Thread(target=self._keepalive)
x.daemon = True
x.start()
if debug:
if &#39;mylog&#39; in dir(self):
if not async_mode:
print(self.mylog.getvalue().decode())
def _teardown_interact_environment(self):
if &#39;logfile&#39; in dir(self) and hasattr(self, &#39;mylog&#39;):
with open(self.logfile, &#34;w&#34;) as f:
f.write(self._logclean(self.mylog.getvalue().decode(), True))
async def _async_interact_loop(self, local_stream, resize_callback, copilot_handler=None):
local_stream.setup(resize_callback=resize_callback)
try:
child_fd = self.child.child_fd
# 1. Flush ghost buffer (Clean UX)
ghost_buffer = b&#39;&#39;
if getattr(self, &#39;missingtext&#39;, False):
# If we are missing the password, we MUST show the password prompt
ghost_buffer = (self.child.after or b&#39;&#39;) + (self.child.buffer or b&#39;&#39;)
else:
# We auto-logged in. Hide the messy password negotiation and just keep any pending live stream.
ghost_buffer = self.child.buffer or b&#39;&#39;
# Fix user&#39;s pet peeve: Strip leading newlines to avoid the empty lines
# the router echoes after receiving the password or blank line.
if not getattr(self, &#39;missingtext&#39;, False):
ghost_buffer = ghost_buffer.lstrip(b&#39;\r\n &#39;)
if ghost_buffer:
# Add a single clean newline so it doesn&#39;t merge with the Connected message
await local_stream.write(b&#39;\r\n&#39; + ghost_buffer)
if hasattr(self, &#39;mylog&#39;):
self.mylog.write(b&#39;\n&#39; + ghost_buffer)
self.child.buffer = b&#39;&#39;
self.child.before = b&#39;&#39;
# 2. Set child fd non-blocking
flags = fcntl.fcntl(child_fd, fcntl.F_GETFL)
fcntl.fcntl(child_fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
loop = asyncio.get_running_loop()
child_reader_queue = asyncio.Queue()
# Track command byte positions for copilot context navigation
# Each entry is (byte_position, command_text_or_None)
cmd_byte_positions = [(0, None)]
def _child_read_ready():
try:
# Increase buffer to 64KB for better high-speed handling
data = os.read(child_fd, 65536)
if data:
child_reader_queue.put_nowait(data)
else:
child_reader_queue.put_nowait(b&#39;&#39;)
except BlockingIOError:
pass
except OSError:
child_reader_queue.put_nowait(b&#39;&#39;)
loop.add_reader(child_fd, _child_read_ready)
self.lastinput = time()
async def ingress_task():
while True:
data = await local_stream.read()
if not data:
break
# Copilot interception
if copilot_handler and b&#39;\x00&#39; in data:
# Build node info from available metadata and ensure values are strings (not bytes)
def to_str(val):
if isinstance(val, bytes):
return val.decode(errors=&#39;replace&#39;)
return str(val) if val is not None else &#34;unknown&#34;
node_info = {
&#34;name&#34;: to_str(getattr(self, &#39;unique&#39;, &#39;unknown&#39;)),
&#34;host&#34;: to_str(getattr(self, &#39;host&#39;, &#39;unknown&#39;))
}
if isinstance(getattr(self, &#39;tags&#39;, None), dict):
node_info[&#34;os&#34;] = to_str(self.tags.get(&#34;os&#34;, &#34;unknown&#34;))
node_info[&#34;prompt&#34;] = to_str(self.tags.get(&#34;prompt&#34;, r&#39;&gt;$|#$|\$$|&gt;.$|#.$|\$.$&#39;))
# Invoke copilot (async callback handles UI)
await copilot_handler(self.mylog.getvalue(), node_info, local_stream, child_fd, cmd_byte_positions)
continue
# Remove any stray \x00 bytes and forward normally
clean_data = data.replace(b&#39;\x00&#39;, b&#39;&#39;)
if clean_data:
# Track command boundaries when user hits Enter
if hasattr(self, &#39;mylog&#39;) and (b&#39;\r&#39; in clean_data or b&#39;\n&#39; in clean_data):
cmd_byte_positions.append((self.mylog.tell(), None))
try:
os.write(child_fd, clean_data)
except OSError:
break
self.lastinput = time()
async def egress_task():
# Continue stripping newlines from the live stream until we hit real text
skip_newlines = not getattr(self, &#39;missingtext&#39;, False) and not ghost_buffer
while True:
data = await child_reader_queue.get()
if not data:
break
# Batching Optimization: Drain the queue to batch writes during high-volume bursts
# Helps the terminal parse ANSI faster and reduces syscalls.
chunks = [data]
while not child_reader_queue.empty():
try:
extra = child_reader_queue.get_nowait()
if not extra:
chunks.append(b&#39;&#39;) # Re-put EOF later or handle it
break
chunks.append(extra)
except asyncio.QueueEmpty:
break
has_eof = chunks[-1] == b&#39;&#39;
if has_eof:
chunks.pop()
if chunks:
combined_data = b&#39;&#39;.join(chunks)
if skip_newlines:
stripped = combined_data.lstrip(b&#39;\r\n&#39;)
if stripped:
skip_newlines = False
combined_data = stripped
else:
if has_eof: break
continue
await local_stream.write(combined_data)
if hasattr(self, &#39;mylog&#39;):
self.mylog.write(combined_data)
if has_eof:
break
async def keepalive_task():
while True:
await asyncio.sleep(1)
if time() - self.lastinput &gt;= self.idletime:
try:
self.child.sendcontrol(&#34;e&#34;)
self.lastinput = time()
except Exception:
pass
async def savelog_task():
prev_size = 0
while True:
await asyncio.sleep(5)
current_size = self.mylog.tell()
if current_size != prev_size:
try:
# Move heavy log cleaning to a thread to avoid freezing the interaction loop
raw_log = self.mylog.getvalue().decode(errors=&#39;replace&#39;)
cleaned_log = await asyncio.to_thread(self._logclean, raw_log, True)
with open(self.logfile, &#34;w&#34;) as f:
f.write(cleaned_log)
prev_size = current_size
except Exception:
pass
try:
# We wait for either the user (ingress) or the child (egress) to finish
tasks = [
asyncio.create_task(ingress_task()),
asyncio.create_task(egress_task())
]
if self.idletime &gt; 0:
tasks.append(asyncio.create_task(keepalive_task()))
if hasattr(self, &#39;logfile&#39;) and hasattr(self, &#39;mylog&#39;):
tasks.append(asyncio.create_task(savelog_task()))
done, pending = await asyncio.wait(
[tasks[0], tasks[1]],
return_when=asyncio.FIRST_COMPLETED
)
# If ingress finished first (user quit), give egress a small window to catch up
# on the remaining output in the queue.
if tasks[0] in done and tasks[1] not in done:
try:
await asyncio.wait_for(tasks[1], timeout=0.2)
except (asyncio.TimeoutError, asyncio.CancelledError):
pass
for t in tasks:
if t not in done:
t.cancel()
# Final log sync on thread to avoid losing last lines
if hasattr(self, &#39;logfile&#39;) and hasattr(self, &#39;mylog&#39;):
try:
raw_log = self.mylog.getvalue().decode(errors=&#39;replace&#39;)
cleaned_log = await asyncio.to_thread(self._logclean, raw_log, True)
with open(self.logfile, &#34;w&#34;) as f:
f.write(cleaned_log)
except Exception:
pass
finally:
loop.remove_reader(child_fd)
try:
flags = fcntl.fcntl(child_fd, fcntl.F_GETFL)
fcntl.fcntl(child_fd, fcntl.F_SETFL, flags &amp; ~os.O_NONBLOCK)
except Exception:
pass
finally:
local_stream.teardown()
@MethodHook
def interact(self, debug=False, logger=None):
&#39;&#39;&#39;
Asynchronous interactive session using Smart Tunnel architecture.
Allows multiplexing I/O and handling SIGWINCH events locally without blocking.
&#39;&#39;&#39;
connect = self._connect(debug=debug, logger=logger)
if connect == True:
try:
self._setup_interact_environment(debug=debug, logger=logger, async_mode=True)
local_stream = LocalStream()
def resize_callback(rows, cols):
try:
self.child.setwinsize(rows, cols)
except Exception:
pass
# Build local copilot handler
copilot_handler = self._build_local_copilot_handler()
asyncio.run(self._async_interact_loop(local_stream, resize_callback, copilot_handler=copilot_handler))
finally:
self._teardown_interact_environment()
else:
if logger:
logger(&#34;error&#34;, str(connect))
else:
printer.error(f&#34;Connection failed: {str(connect)}&#34;)
sys.exit(1)
def _build_local_copilot_handler(self):
&#34;&#34;&#34;Build copilot handler for local CLI sessions using rich for rendering.&#34;&#34;&#34;
config = getattr(self, &#39;config&#39;, None) if hasattr(self, &#39;config&#39;) else None
return self._copilot_handler(config)
def _copilot_handler(self, config):
&#34;&#34;&#34;Unified copilot handler for local session.&#34;&#34;&#34;
from .cli.terminal_ui import CopilotInterface
from .services.ai_service import AIService
import asyncio
import os
async def handler(buffer, node_info, stream, child_fd, cmd_byte_positions=None):
try:
interface = CopilotInterface(
config,
history=getattr(stream, &#39;copilot_history&#39;, None),
session_state=getattr(stream, &#39;copilot_state&#39;, None)
)
# Save history back to stream for persistence in current session
stream.copilot_history = interface.history
stream.copilot_state = interface.session_state
ai_service = AIService(config)
async def on_ai_call(active_buffer, question, chunk_callback, merged_node_info):
return await ai_service.aask_copilot(
active_buffer,
question,
node_info=merged_node_info,
chunk_callback=chunk_callback
)
# Get raw bytes from BytesIO
raw_bytes = self.mylog.getvalue()
# Detener el lector de la terminal para que prompt_toolkit (en run_session)
# tenga control exclusivo del stdin sin interferencias de LocalStream.
if hasattr(stream, &#39;stop_reading&#39;):
stream.stop_reading()
elif hasattr(stream, &#39;_loop&#39;) and hasattr(stream, &#39;stdin_fd&#39;):
# Fallback si no tiene el método (en LocalStream)
stream._loop.remove_reader(stream.stdin_fd)
try:
with copilot_terminal_mode():
while True:
action, commands, custom_cmd = await interface.run_session(
raw_bytes=raw_bytes,
cmd_byte_positions=cmd_byte_positions,
node_info=node_info,
on_ai_call=on_ai_call
)
if action == &#34;continue&#34;:
continue
break
finally:
# Reiniciar el lector de la terminal para volver al modo interactivo SSH/Telnet
if hasattr(stream, &#39;start_reading&#39;):
stream.start_reading()
elif hasattr(stream, &#39;_loop&#39;) and hasattr(stream, &#39;stdin_fd&#39;):
stream._loop.add_reader(stream.stdin_fd, stream._read_ready)
if action in (&#34;send_all&#34;, &#34;custom&#34;):
cmds_to_send = commands if action == &#34;send_all&#34; else custom_cmd
if cmds_to_send:
os.write(child_fd, b&#39;\x15&#39;) # Ctrl+U
await asyncio.sleep(0.1)
# Prepend screen length command to avoid pagination
if &#34;screen_length_command&#34; in self.tags:
cmds_to_send.insert(0, self.tags[&#34;screen_length_command&#34;])
for cmd in cmds_to_send:
if cmd_byte_positions is not None:
cmd_byte_positions.append((self.mylog.tell(), cmd))
os.write(child_fd, (cmd + &#34;\n&#34;).encode())
await asyncio.sleep(0.8)
else:
os.write(child_fd, b&#39;\x15\r&#39;)
except Exception as e:
import traceback
print(f&#34;\n[ERROR in Copilot Handler] {e}&#34;, flush=True)
traceback.print_exc()
os.write(child_fd, b&#39;\x15\r&#39;)
return handler
@MethodHook
def run(self, commands, vars = None,*, folder = &#39;&#39;, prompt = r&#39;&gt;$|#$|\$$|&gt;.$|#.$|\$.$&#39;, stdout = False, timeout = 10, logger = None):
&#39;&#39;&#39;
Run a command or list of commands on the node and return the output.
### Parameters:
- commands (str/list): Commands to run on the node. Should be
str or a list of str. You can use variables
as {varname} and defining them in optional
parameter vars.
### Optional Parameters:
- vars (dict): Dictionary containing the definition of variables
used in commands parameter.
Keys: Variable names.
Values: strings.
### Optional Named Parameters:
- folder (str): Path where output log should be stored, leave
empty to disable logging.
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses &#34;&gt;&#34; or EOF while
routers use &#34;&gt;&#34; or &#34;#&#34;. The default value should
work for most nodes. Change it if your connection
need some special symbol.
- stdout (bool):Set True to send the command output to stdout.
default False.
- timeout (int):Time in seconds for expect to wait for prompt/EOF.
default 10.
### Returns:
str: Output of the commands you ran on the node.
&#39;&#39;&#39;
connect = self._connect(timeout = timeout, logger = logger)
now = datetime.datetime.now().strftime(&#39;%Y-%m-%d_%H%M%S&#39;)
if connect == True:
if logger:
port_str = f&#34;:{self.port}&#34; if self.port and self.protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34;
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}&#34;)
# Attempt to set the terminal size
try:
self.child.setwinsize(65535, 65535)
except Exception:
try:
self.child.setwinsize(10000, 10000)
except Exception:
pass
if &#34;prompt&#34; in self.tags:
prompt = self.tags[&#34;prompt&#34;]
expects = [prompt, pexpect.EOF, pexpect.TIMEOUT]
output = &#39;&#39;
status = &#39;&#39;
if not isinstance(commands, list):
commands = [commands]
if &#34;screen_length_command&#34; in self.tags:
commands.insert(0, self.tags[&#34;screen_length_command&#34;])
self.mylog = io.BytesIO()
self.child.logfile_read = self.mylog
for c in commands:
if vars is not None:
try:
c = c.format(**vars)
except KeyError as e:
self.output = f&#34;Error: Variable {e} not defined in task or inventory&#34;
self.status = 1
return self.output
result = self.child.expect(expects, timeout = timeout)
self.child.sendline(c)
if result == 2:
break
if not result == 2:
result = self.child.expect(expects, timeout = timeout)
self.child.close()
output = self._logclean(self.mylog.getvalue().decode(), True)
if logger:
logger(&#34;output&#34;, output)
if folder != &#39;&#39;:
with open(folder + &#34;/&#34; + self.unique + &#34;_&#34; + now + &#34;.txt&#34;, &#34;w&#34;) as f:
f.write(output)
f.close()
self.output = output
if result == 2:
self.status = 2
else:
self.status = 0
return output
else:
self.output = connect
self.status = 1
if logger:
logger(&#34;error&#34;, f&#34;Connection failed: {connect}&#34;)
if folder != &#39;&#39;:
with open(folder + &#34;/&#34; + self.unique + &#34;_&#34; + now + &#34;.txt&#34;, &#34;w&#34;) as f:
f.write(connect)
f.close()
return connect
@MethodHook
def test(self, commands, expected, vars = None,*, folder = &#39;&#39;, prompt = r&#39;&gt;$|#$|\$$|&gt;.$|#.$|\$.$&#39;, timeout = 10, logger = None):
&#39;&#39;&#39;
Run a command or list of commands on the node, then check if expected value appears on the output after the last command.
### Parameters:
- commands (str/list): Commands to run on the node. Should be
str or a list of str. You can use variables
as {varname} and defining them in optional
parameter vars.
- expected (str) : Expected text to appear after running
all the commands on the node.You can use
variables as {varname} and defining them
in optional parameter vars.
### Optional Parameters:
- vars (dict): Dictionary containing the definition of variables
used in commands and expected parameters.
Keys: Variable names.
Values: strings.
### Optional Named Parameters:
- folder (str): Path where output log should be stored, leave
empty to not store logs.
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses &#34;&gt;&#34; or EOF while
routers use &#34;&gt;&#34; or &#34;#&#34;. The default value should
work for most nodes. Change it if your connection
need some special symbol.
- timeout (int):Time in seconds for expect to wait for prompt/EOF.
default 10.
### Returns:
bool: true if expected value is found after running the commands
false if prompt is found before.
&#39;&#39;&#39;
now = datetime.datetime.now().strftime(&#34;%Y-%m-%d_%H-%M-%S&#34;)
connect = self._connect(timeout = timeout, logger = logger)
if connect == True:
if logger:
port_str = f&#34;:{self.port}&#34; if self.port and self.protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34;
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}&#34;)
# Attempt to set the terminal size
try:
self.child.setwinsize(65535, 65535)
except Exception:
try:
self.child.setwinsize(10000, 10000)
except Exception:
pass
if &#34;prompt&#34; in self.tags:
prompt = self.tags[&#34;prompt&#34;]
expects = [prompt, pexpect.EOF, pexpect.TIMEOUT]
output = &#39;&#39;
if not isinstance(commands, list):
commands = [commands]
if not isinstance(expected, list):
expected = [expected]
if &#34;screen_length_command&#34; in self.tags:
commands.insert(0, self.tags[&#34;screen_length_command&#34;])
self.mylog = io.BytesIO()
self.child.logfile_read = self.mylog
for c in commands:
if vars is not None:
try:
c = c.format(**vars)
except KeyError as e:
self.output = f&#34;Error: Variable {e} not defined in task or inventory&#34;
self.status = 1
return self.output
result = self.child.expect(expects, timeout = timeout)
self.child.sendline(c)
if result == 2:
break
if not result == 2:
result = self.child.expect(expects, timeout = timeout)
self.child.close()
output = self._logclean(self.mylog.getvalue().decode(), True)
if logger:
logger(&#34;output&#34;, output)
if folder != &#39;&#39;:
with open(folder + &#34;/&#34; + self.unique + &#34;_&#34; + now + &#34;.txt&#34;, &#34;w&#34;) as f:
f.write(output)
f.close()
self.output = output
if result in [0, 1]:
# lastcommand = commands[-1]
# if vars is not None:
# lastcommand = lastcommand.format(**vars)
# last_command_index = output.rfind(lastcommand)
# cleaned_output = output[last_command_index + len(lastcommand):].strip()
self.result = {}
for e in expected:
if vars is not None:
e = e.format(**vars)
updatedprompt = re.sub(r&#39;(?&lt;!\\)\$&#39;, &#39;&#39;, prompt)
newpattern = f&#34;.*({updatedprompt}).*{e}.*&#34;
cleaned_output = output
cleaned_output = re.sub(newpattern, &#39;&#39;, cleaned_output)
if e in cleaned_output:
self.result[e] = True
else:
self.result[e]= False
self.status = 0
return self.result
if result == 2:
self.result = None
self.status = 2
return output
else:
self.result = None
self.output = connect
self.status = 1
return connect
@MethodHook
def _generate_ssh_sftp_cmd(self):
cmd = self.protocol
if self.port:
if self.protocol == &#34;ssh&#34;:
cmd += &#34; -p &#34; + self.port
elif self.protocol == &#34;sftp&#34;:
cmd += &#34; -P &#34; + self.port
if self.options:
opts = self.options
if self.protocol == &#34;sftp&#34;:
# Strip SSH-only flags that sftp doesn&#39;t support
opts = re.sub(r&#39;(?&lt;!\S)-[XxtTAaNf]\b&#39;, &#39;&#39;, opts).strip()
if opts:
cmd += &#34; &#34; + opts
if self.jumphost:
cmd += &#34; &#34; + self.jumphost
user_host = f&#34;{self.user}@{self.host}&#34; if self.user else self.host
cmd += f&#34; {user_host}&#34;
return cmd
@MethodHook
def _generate_telnet_cmd(self):
cmd = f&#34;telnet {self.host}&#34;
if self.port:
cmd += f&#34; {self.port}&#34;
if self.options:
cmd += f&#34; {self.options}&#34;
return cmd
@MethodHook
def _generate_kube_cmd(self):
cmd = f&#34;kubectl exec {self.options} {self.host} -it --&#34;
kube_command = self.tags.get(&#34;kube_command&#34;, &#34;/bin/bash&#34;) if isinstance(self.tags, dict) else &#34;/bin/bash&#34;
cmd += f&#34; {kube_command}&#34;
return cmd
@MethodHook
def _generate_docker_cmd(self):
cmd = f&#34;docker {self.options} exec -it {self.host}&#34;
docker_command = self.tags.get(&#34;docker_command&#34;, &#34;/bin/bash&#34;) if isinstance(self.tags, dict) else &#34;/bin/bash&#34;
cmd += f&#34; {docker_command}&#34;
return cmd
@MethodHook
def _generate_ssm_cmd(self):
region = self.tags.get(&#34;region&#34;, &#34;&#34;) if isinstance(self.tags, dict) else &#34;&#34;
profile = self.tags.get(&#34;profile&#34;, &#34;&#34;) if isinstance(self.tags, dict) else &#34;&#34;
cmd = f&#34;aws ssm start-session --target {self.host}&#34;
if region:
cmd += f&#34; --region {region}&#34;
if profile:
cmd += f&#34; --profile {profile}&#34;
if self.options:
cmd += f&#34; {self.options}&#34;
return cmd
@MethodHook
def _generate_ssm_cmd(self):
region = self.tags.get(&#34;region&#34;, &#34;&#34;) if isinstance(self.tags, dict) else &#34;&#34;
profile = self.tags.get(&#34;profile&#34;, &#34;&#34;) if isinstance(self.tags, dict) else &#34;&#34;
cmd = f&#34;aws ssm start-session --target {self.host}&#34;
if region:
cmd += f&#34; --region {region}&#34;
if profile:
cmd += f&#34; --profile {profile}&#34;
if self.options:
cmd += f&#34; {self.options}&#34;
return cmd
@MethodHook
def _get_cmd(self):
if self.protocol in [&#34;ssh&#34;, &#34;sftp&#34;]:
return self._generate_ssh_sftp_cmd()
elif self.protocol == &#34;telnet&#34;:
return self._generate_telnet_cmd()
elif self.protocol == &#34;kubectl&#34;:
return self._generate_kube_cmd()
elif self.protocol == &#34;docker&#34;:
return self._generate_docker_cmd()
elif self.protocol == &#34;ssm&#34;:
return self._generate_ssm_cmd()
else:
printer.error(f&#34;Invalid protocol: {self.protocol}&#34;)
sys.exit(1)
@MethodHook
def _connect(self, debug=False, timeout=10, max_attempts=3, logger=None):
cmd = self._get_cmd()
passwords = self._passtx(self.password) if self.password and any(self.password) else []
if self.logs != &#39;&#39;:
self.logfile = self._logfile()
default_prompt = r&#39;&gt;$|#$|\$$|&gt;.$|#.$|\$.$&#39;
prompt = self.tags.get(&#34;prompt&#34;, default_prompt) if isinstance(self.tags, dict) else default_prompt
password_prompt = &#39;[p|P]assword:|[u|U]sername:&#39; if self.protocol != &#39;telnet&#39; else &#39;[p|P]assword:&#39;
expects = {
&#34;ssh&#34;: [&#39;yes/no&#39;, &#39;refused&#39;, &#39;supported&#39;, &#39;Invalid|[u|U]sage: ssh&#39;, &#39;ssh-keygen.*\&#34;&#39;, &#39;timeout|timed.out&#39;, &#39;unavailable&#39;, &#39;closed&#39;, password_prompt, prompt, &#39;suspend&#39;, pexpect.EOF, pexpect.TIMEOUT, &#34;No route to host&#34;, &#34;resolve hostname&#34;, &#34;no matching&#34;, &#34;[b|B]ad (owner|permissions)&#34;],
&#34;sftp&#34;: [&#39;yes/no&#39;, &#39;refused&#39;, &#39;supported&#39;, &#39;Invalid|[u|U]sage: sftp&#39;, &#39;ssh-keygen.*\&#34;&#39;, &#39;timeout|timed.out&#39;, &#39;unavailable&#39;, &#39;closed&#39;, password_prompt, prompt, &#39;suspend&#39;, pexpect.EOF, pexpect.TIMEOUT, &#34;No route to host&#34;, &#34;resolve hostname&#34;, &#34;no matching&#34;, &#34;[b|B]ad (owner|permissions)&#34;],
&#34;telnet&#34;: [&#39;[u|U]sername:&#39;, &#39;refused&#39;, &#39;supported&#39;, &#39;invalid|unrecognized option&#39;, &#39;ssh-keygen.*\&#34;&#39;, &#39;timeout|timed.out&#39;, &#39;unavailable&#39;, &#39;closed&#39;, password_prompt, prompt, &#39;suspend&#39;, pexpect.EOF, pexpect.TIMEOUT, &#34;No route to host&#34;, &#34;resolve hostname&#34;, &#34;no matching&#34;, &#34;[b|B]ad (owner|permissions)&#34;],
&#34;kubectl&#34;: [&#39;[u|U]sername:&#39;, &#39;[r|R]efused&#39;, &#39;[E|e]rror&#39;, &#39;DEPRECATED&#39;, pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF, &#34;expired|invalid&#34;],
&#34;docker&#34;: [&#39;[u|U]sername:&#39;, &#39;Cannot&#39;, &#39;[E|e]rror&#39;, &#39;failed&#39;, &#39;not a docker command&#39;, &#39;unknown&#39;, &#39;unable to resolve&#39;, pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF],
&#34;ssm&#34;: [&#39;[u|U]sername:&#39;, &#39;Cannot&#39;, &#39;[E|e]rror&#39;, &#39;failed&#39;, &#39;SessionManagerPlugin&#39;, &#39;[u|U]nknown&#39;, &#39;unable to resolve&#39;, pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF]
}
error_indices = {
&#34;ssh&#34;: [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16],
&#34;sftp&#34;: [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16],
&#34;telnet&#34;: [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16],
&#34;kubectl&#34;: [1, 2, 3, 4, 8], # Define error indices for kube
&#34;docker&#34;: [1, 2, 3, 4, 5, 6, 7], # Define error indices for docker
&#34;ssm&#34;: [1, 2, 3, 4, 5, 6, 7]
}
eof_indices = {
&#34;ssh&#34;: [8, 9, 10, 11],
&#34;sftp&#34;: [8, 9, 10, 11],
&#34;telnet&#34;: [8, 9, 10, 11],
&#34;kubectl&#34;: [5, 6, 7], # Define eof indices for kube
&#34;docker&#34;: [8, 9, 10], # Define eof indices for docker
&#34;ssm&#34;: [8, 9, 10]
}
initial_indices = {
&#34;ssh&#34;: [0],
&#34;sftp&#34;: [0],
&#34;telnet&#34;: [0],
&#34;kubectl&#34;: [0], # Define special indices for kube
&#34;docker&#34;: [0], # Define special indices for docker
&#34;ssm&#34;: [0]
}
attempts = 1
while attempts &lt;= max_attempts:
child = pexpect.spawn(cmd)
if isinstance(self.tags, dict) and self.tags.get(&#34;console&#34;):
child.sendline()
if debug:
if logger:
logger(&#34;debug&#34;, f&#34;Command:\n{cmd}&#34;)
self.mylog = io.BytesIO()
self.mylog.write(f&#34;[i] [DEBUG] Command:\r\n {cmd}\r\n&#34;.encode())
child.logfile_read = self.mylog
endloop = False
for i in range(len(passwords) if passwords else 1):
while True:
results = child.expect(expects[self.protocol], timeout=timeout)
results_value = expects[self.protocol][results]
if results in initial_indices[self.protocol]:
if self.protocol in [&#34;ssh&#34;, &#34;sftp&#34;]:
child.sendline(&#39;yes&#39;)
elif self.protocol in [&#34;telnet&#34;, &#34;kubectl&#34;, &#34;docker&#34;, &#34;ssm&#34;]:
if self.user:
child.sendline(self.user)
else:
self.missingtext = True
break
elif results in error_indices[self.protocol]:
child.terminate()
if results_value == pexpect.TIMEOUT and attempts != max_attempts:
attempts += 1
endloop = True
break
else:
after = &#34;Connection timeout&#34; if results_value == pexpect.TIMEOUT else child.after.decode()
return f&#34;Connection failed code: {results}\n{child.before.decode().lstrip()}{after}{child.readline().decode()}&#34;.rstrip()
elif results in eof_indices[self.protocol]:
if results_value == password_prompt:
if passwords:
child.sendline(passwords[i])
else:
self.missingtext = True
break
elif results_value == &#34;suspend&#34;:
child.sendline(&#34;\r&#34;)
sleep(2)
else:
endloop = True
child.sendline()
break
if endloop:
break
if results_value == pexpect.TIMEOUT:
continue
else:
break
if isinstance(self.tags, dict) and self.tags.get(&#34;post_connect_commands&#34;):
cmds = self.tags.get(&#34;post_connect_commands&#34;)
commands = [cmds] if isinstance(cmds, str) else cmds
for command in commands:
child.sendline(command)
sleep(1)
child.readline(0)
self.child = child
from pexpect import fdpexpect
self.raw_child = fdpexpect.fdspawn(self.child.child_fd)
return True</code></pre>
</details>
<div class="desc"><p>This class generates a node object. Containts all the information and methods to connect and interact with a device using ssh or telnet.</p>
<h3 id="attributes">Attributes:</h3>
<pre><code>- output (str): Output of the commands you ran with run or test
method.
- result(bool): True if expected value is found after running
the commands using test method.
- status (int): 0 if the method run or test run successfully.
1 if connection failed.
2 if expect timeouts without prompt or EOF.
</code></pre>
<h3 id="parameters">Parameters:</h3>
<pre><code>- unique (str): Unique name to assign to the node.
- host (str): IP address or hostname of the node.
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- options (str): Additional options to pass the ssh/telnet for
connection.
- logs (str): Path/file for storing the logs. You can use
${unique},${host}, ${port}, ${user}, ${protocol}
as variables.
- password (str): Encrypted or plaintext password.
- port (str): Port to connect to node, default 22 for ssh and 23
for telnet.
- protocol (str): Select ssh, telnet, kubectl or docker. Default is ssh.
- user (str): Username to of the node.
- config (obj): Pass the object created with class configfile with
key for decryption and extra configuration if you
are using connection manager.
- tags (dict) : Tags useful for automation and personal porpuse
like "os", "prompt" and "screenleght_command"
- jumphost (str): Reference another node to be used as a jumphost
</code></pre></div>
<h3>Methods</h3>
<dl>
<dt id="connpy.node.interact"><code class="name flex">
<span>def <span class="ident">interact</span></span>(<span>self, debug=False, logger=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def interact(self, debug=False, logger=None):
&#39;&#39;&#39;
Asynchronous interactive session using Smart Tunnel architecture.
Allows multiplexing I/O and handling SIGWINCH events locally without blocking.
&#39;&#39;&#39;
connect = self._connect(debug=debug, logger=logger)
if connect == True:
try:
self._setup_interact_environment(debug=debug, logger=logger, async_mode=True)
local_stream = LocalStream()
def resize_callback(rows, cols):
try:
self.child.setwinsize(rows, cols)
except Exception:
pass
# Build local copilot handler
copilot_handler = self._build_local_copilot_handler()
asyncio.run(self._async_interact_loop(local_stream, resize_callback, copilot_handler=copilot_handler))
finally:
self._teardown_interact_environment()
else:
if logger:
logger(&#34;error&#34;, str(connect))
else:
printer.error(f&#34;Connection failed: {str(connect)}&#34;)
sys.exit(1)</code></pre>
</details>
<div class="desc"><p>Asynchronous interactive session using Smart Tunnel architecture.
Allows multiplexing I/O and handling SIGWINCH events locally without blocking.</p></div>
</dd>
<dt id="connpy.node.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self,<br>commands,<br>vars=None,<br>*,<br>folder='',<br>prompt=&#x27;&gt;$|#$|\\$$|&gt;.$|#.$|\\$.$&#x27;,<br>stdout=False,<br>timeout=10,<br>logger=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def run(self, commands, vars = None,*, folder = &#39;&#39;, prompt = r&#39;&gt;$|#$|\$$|&gt;.$|#.$|\$.$&#39;, stdout = False, timeout = 10, logger = None):
&#39;&#39;&#39;
Run a command or list of commands on the node and return the output.
### Parameters:
- commands (str/list): Commands to run on the node. Should be
str or a list of str. You can use variables
as {varname} and defining them in optional
parameter vars.
### Optional Parameters:
- vars (dict): Dictionary containing the definition of variables
used in commands parameter.
Keys: Variable names.
Values: strings.
### Optional Named Parameters:
- folder (str): Path where output log should be stored, leave
empty to disable logging.
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses &#34;&gt;&#34; or EOF while
routers use &#34;&gt;&#34; or &#34;#&#34;. The default value should
work for most nodes. Change it if your connection
need some special symbol.
- stdout (bool):Set True to send the command output to stdout.
default False.
- timeout (int):Time in seconds for expect to wait for prompt/EOF.
default 10.
### Returns:
str: Output of the commands you ran on the node.
&#39;&#39;&#39;
connect = self._connect(timeout = timeout, logger = logger)
now = datetime.datetime.now().strftime(&#39;%Y-%m-%d_%H%M%S&#39;)
if connect == True:
if logger:
port_str = f&#34;:{self.port}&#34; if self.port and self.protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34;
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}&#34;)
# Attempt to set the terminal size
try:
self.child.setwinsize(65535, 65535)
except Exception:
try:
self.child.setwinsize(10000, 10000)
except Exception:
pass
if &#34;prompt&#34; in self.tags:
prompt = self.tags[&#34;prompt&#34;]
expects = [prompt, pexpect.EOF, pexpect.TIMEOUT]
output = &#39;&#39;
status = &#39;&#39;
if not isinstance(commands, list):
commands = [commands]
if &#34;screen_length_command&#34; in self.tags:
commands.insert(0, self.tags[&#34;screen_length_command&#34;])
self.mylog = io.BytesIO()
self.child.logfile_read = self.mylog
for c in commands:
if vars is not None:
try:
c = c.format(**vars)
except KeyError as e:
self.output = f&#34;Error: Variable {e} not defined in task or inventory&#34;
self.status = 1
return self.output
result = self.child.expect(expects, timeout = timeout)
self.child.sendline(c)
if result == 2:
break
if not result == 2:
result = self.child.expect(expects, timeout = timeout)
self.child.close()
output = self._logclean(self.mylog.getvalue().decode(), True)
if logger:
logger(&#34;output&#34;, output)
if folder != &#39;&#39;:
with open(folder + &#34;/&#34; + self.unique + &#34;_&#34; + now + &#34;.txt&#34;, &#34;w&#34;) as f:
f.write(output)
f.close()
self.output = output
if result == 2:
self.status = 2
else:
self.status = 0
return output
else:
self.output = connect
self.status = 1
if logger:
logger(&#34;error&#34;, f&#34;Connection failed: {connect}&#34;)
if folder != &#39;&#39;:
with open(folder + &#34;/&#34; + self.unique + &#34;_&#34; + now + &#34;.txt&#34;, &#34;w&#34;) as f:
f.write(connect)
f.close()
return connect</code></pre>
</details>
<div class="desc"><p>Run a command or list of commands on the node and return the output.</p>
<h3 id="parameters">Parameters:</h3>
<pre><code>- commands (str/list): Commands to run on the node. Should be
str or a list of str. You can use variables
as {varname} and defining them in optional
parameter vars.
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- vars (dict): Dictionary containing the definition of variables
used in commands parameter.
Keys: Variable names.
Values: strings.
</code></pre>
<h3 id="optional-named-parameters">Optional Named Parameters:</h3>
<pre><code>- folder (str): Path where output log should be stored, leave
empty to disable logging.
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses "&gt;" or EOF while
routers use "&gt;" or "#". The default value should
work for most nodes. Change it if your connection
need some special symbol.
- stdout (bool):Set True to send the command output to stdout.
default False.
- timeout (int):Time in seconds for expect to wait for prompt/EOF.
default 10.
</code></pre>
<h3 id="returns">Returns:</h3>
<pre><code>str: Output of the commands you ran on the node.
</code></pre></div>
</dd>
<dt id="connpy.node.test"><code class="name flex">
<span>def <span class="ident">test</span></span>(<span>self,<br>commands,<br>expected,<br>vars=None,<br>*,<br>folder='',<br>prompt=&#x27;&gt;$|#$|\\$$|&gt;.$|#.$|\\$.$&#x27;,<br>timeout=10,<br>logger=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def test(self, commands, expected, vars = None,*, folder = &#39;&#39;, prompt = r&#39;&gt;$|#$|\$$|&gt;.$|#.$|\$.$&#39;, timeout = 10, logger = None):
&#39;&#39;&#39;
Run a command or list of commands on the node, then check if expected value appears on the output after the last command.
### Parameters:
- commands (str/list): Commands to run on the node. Should be
str or a list of str. You can use variables
as {varname} and defining them in optional
parameter vars.
- expected (str) : Expected text to appear after running
all the commands on the node.You can use
variables as {varname} and defining them
in optional parameter vars.
### Optional Parameters:
- vars (dict): Dictionary containing the definition of variables
used in commands and expected parameters.
Keys: Variable names.
Values: strings.
### Optional Named Parameters:
- folder (str): Path where output log should be stored, leave
empty to not store logs.
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses &#34;&gt;&#34; or EOF while
routers use &#34;&gt;&#34; or &#34;#&#34;. The default value should
work for most nodes. Change it if your connection
need some special symbol.
- timeout (int):Time in seconds for expect to wait for prompt/EOF.
default 10.
### Returns:
bool: true if expected value is found after running the commands
false if prompt is found before.
&#39;&#39;&#39;
now = datetime.datetime.now().strftime(&#34;%Y-%m-%d_%H-%M-%S&#34;)
connect = self._connect(timeout = timeout, logger = logger)
if connect == True:
if logger:
port_str = f&#34;:{self.port}&#34; if self.port and self.protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34;
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}&#34;)
# Attempt to set the terminal size
try:
self.child.setwinsize(65535, 65535)
except Exception:
try:
self.child.setwinsize(10000, 10000)
except Exception:
pass
if &#34;prompt&#34; in self.tags:
prompt = self.tags[&#34;prompt&#34;]
expects = [prompt, pexpect.EOF, pexpect.TIMEOUT]
output = &#39;&#39;
if not isinstance(commands, list):
commands = [commands]
if not isinstance(expected, list):
expected = [expected]
if &#34;screen_length_command&#34; in self.tags:
commands.insert(0, self.tags[&#34;screen_length_command&#34;])
self.mylog = io.BytesIO()
self.child.logfile_read = self.mylog
for c in commands:
if vars is not None:
try:
c = c.format(**vars)
except KeyError as e:
self.output = f&#34;Error: Variable {e} not defined in task or inventory&#34;
self.status = 1
return self.output
result = self.child.expect(expects, timeout = timeout)
self.child.sendline(c)
if result == 2:
break
if not result == 2:
result = self.child.expect(expects, timeout = timeout)
self.child.close()
output = self._logclean(self.mylog.getvalue().decode(), True)
if logger:
logger(&#34;output&#34;, output)
if folder != &#39;&#39;:
with open(folder + &#34;/&#34; + self.unique + &#34;_&#34; + now + &#34;.txt&#34;, &#34;w&#34;) as f:
f.write(output)
f.close()
self.output = output
if result in [0, 1]:
# lastcommand = commands[-1]
# if vars is not None:
# lastcommand = lastcommand.format(**vars)
# last_command_index = output.rfind(lastcommand)
# cleaned_output = output[last_command_index + len(lastcommand):].strip()
self.result = {}
for e in expected:
if vars is not None:
e = e.format(**vars)
updatedprompt = re.sub(r&#39;(?&lt;!\\)\$&#39;, &#39;&#39;, prompt)
newpattern = f&#34;.*({updatedprompt}).*{e}.*&#34;
cleaned_output = output
cleaned_output = re.sub(newpattern, &#39;&#39;, cleaned_output)
if e in cleaned_output:
self.result[e] = True
else:
self.result[e]= False
self.status = 0
return self.result
if result == 2:
self.result = None
self.status = 2
return output
else:
self.result = None
self.output = connect
self.status = 1
return connect</code></pre>
</details>
<div class="desc"><p>Run a command or list of commands on the node, then check if expected value appears on the output after the last command.</p>
<h3 id="parameters">Parameters:</h3>
<pre><code>- commands (str/list): Commands to run on the node. Should be
str or a list of str. You can use variables
as {varname} and defining them in optional
parameter vars.
- expected (str) : Expected text to appear after running
all the commands on the node.You can use
variables as {varname} and defining them
in optional parameter vars.
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- vars (dict): Dictionary containing the definition of variables
used in commands and expected parameters.
Keys: Variable names.
Values: strings.
</code></pre>
<h3 id="optional-named-parameters">Optional Named Parameters:</h3>
<pre><code>- folder (str): Path where output log should be stored, leave
empty to not store logs.
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses "&gt;" or EOF while
routers use "&gt;" or "#". The default value should
work for most nodes. Change it if your connection
need some special symbol.
- timeout (int):Time in seconds for expect to wait for prompt/EOF.
default 10.
</code></pre>
<h3 id="returns">Returns:</h3>
<pre><code>bool: true if expected value is found after running the commands
false if prompt is found before.
</code></pre></div>
</dd>
</dl>
</dd>
<dt id="connpy.nodes"><code class="flex name class">
<span>class <span class="ident">nodes</span></span>
<span>(</span><span>nodes: dict, config='')</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@ClassHook
class nodes:
&#39;&#39;&#39; This class generates a nodes object. Contains a list of node class objects and methods to run multiple tasks on nodes simultaneously.
### Attributes:
- nodelist (list): List of node class objects passed to the init
function.
- output (dict): Dictionary formed by nodes unique as keys,
output of the commands you ran on the node as
value. Created after running methods run or test.
- result (dict): Dictionary formed by nodes unique as keys, value
is True if expected value is found after running
the commands, False if prompt is found before.
Created after running method test.
- status (dict): Dictionary formed by nodes unique as keys, value:
0 if method run or test ended successfully.
1 if connection failed.
2 if expect timeouts without prompt or EOF.
- &lt;unique&gt; (obj): For each item in nodelist, there is an attribute
generated with the node unique.
&#39;&#39;&#39;
def __init__(self, nodes: dict, config = &#39;&#39;):
&#39;&#39;&#39;
### Parameters:
- nodes (dict): Dictionary formed by node information:
Keys: Unique name for each node.
Mandatory Subkeys: host(str).
Optional Subkeys: options(str), logs(str), password(str),
port(str), protocol(str), user(str).
For reference on subkeys check node class.
### Optional Parameters:
- config (obj): Pass the object created with class configfile with key
for decryption and extra configuration if you are using
connection manager.
&#39;&#39;&#39;
self.nodelist = []
self.config = config
for n in nodes:
this = node(n, **nodes[n], config = config)
self.nodelist.append(this)
setattr(self,n,this)
@MethodHook
def _splitlist(self, lst, n):
#split a list in lists of n members.
for i in range(0, len(lst), n):
yield lst[i:i + n]
@MethodHook
def run(self, commands, vars = None,*, folder = None, prompt = None, stdout = None, parallel = 10, timeout = None, on_complete = None, logger = None):
&#39;&#39;&#39;
Run a command or list of commands on all the nodes in nodelist.
### Parameters:
- commands (str/list): Commands to run on the nodes. Should be str or
list of str. You can use variables as {varname}
and defining them in optional parameter vars.
### Optional Parameters:
- vars (dict): Dictionary containing the definition of variables for
each node, used in commands parameter.
Keys should be formed by nodes unique names. Use
special key name __global__ for global variables.
Subkeys: Variable names.
Values: strings.
### Optional Named Parameters:
- folder (str): Path where output log should be stored, leave empty
to disable logging.
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses &#34;&gt;&#34; or EOF while routers
use &#34;&gt;&#34; or &#34;#&#34;. The default value should work for
most nodes. Change it if your connection need some
special symbol.
- stdout (bool): Set True to send the command output to stdout.
Default False.
- parallel (int): Number of nodes to run the commands simultaneously.
Default is 10, if there are more nodes that this
value, nodes are groups in groups with max this
number of members.
- timeout (int): Time in seconds for expect to wait for prompt/EOF.
default 10.
- on_complete (callable): Optional callback called when each node
finishes. Receives (unique, output, status).
Called from the node&#39;s thread so it must
be thread-safe.
###Returns:
dict: Dictionary formed by nodes unique as keys, Output of the
commands you ran on the node as value.
&#39;&#39;&#39;
args = {}
nodesargs = {}
args[&#34;commands&#34;] = commands
if folder != None:
args[&#34;folder&#34;] = folder
Path(folder).mkdir(parents=True, exist_ok=True)
if prompt != None:
args[&#34;prompt&#34;] = prompt
if stdout != None and on_complete is None:
args[&#34;stdout&#34;] = stdout
if timeout != None:
args[&#34;timeout&#34;] = timeout
output = {}
status = {}
tasks = []
def _run_node(node_obj, node_args, callback):
&#34;&#34;&#34;Wrapper that runs a node and fires the callback on completion.&#34;&#34;&#34;
node_obj.run(**node_args)
if callback:
callback(node_obj.unique, node_obj.output, node_obj.status)
for n in self.nodelist:
nodesargs[n.unique] = deepcopy(args)
if vars != None:
nodesargs[n.unique][&#34;vars&#34;] = {}
if &#34;__global__&#34; in vars.keys():
nodesargs[n.unique][&#34;vars&#34;].update(vars[&#34;__global__&#34;])
for var_key, var_val in vars.items():
if var_key == &#34;__global__&#34;:
continue
try:
if re.search(var_key, n.unique, re.IGNORECASE):
nodesargs[n.unique][&#34;vars&#34;].update(var_val)
except re.error:
if var_key == n.unique:
nodesargs[n.unique][&#34;vars&#34;].update(var_val)
# Pass the logger to the node
nodesargs[n.unique][&#34;logger&#34;] = logger
if on_complete:
tasks.append(threading.Thread(target=_run_node, args=(n, nodesargs[n.unique], on_complete)))
else:
tasks.append(threading.Thread(target=n.run, kwargs=nodesargs[n.unique]))
taskslist = list(self._splitlist(tasks, parallel))
for t in taskslist:
for i in t:
i.start()
for i in t:
i.join()
for i in self.nodelist:
output[i.unique] = i.output
status[i.unique] = i.status
self.output = output
self.status = status
return output
@MethodHook
def test(self, commands, expected, vars = None,*, folder = None, prompt = None, parallel = 10, timeout = None, on_complete = None, logger = None):
&#39;&#39;&#39;
Run a command or list of commands on all the nodes in nodelist, then check if expected value appears on the output after the last command.
### Parameters:
- commands (str/list): Commands to run on the node. Should be str or
list of str.
- expected (str) : Expected text to appear after running all the
commands on the node.
### Optional Parameters:
- vars (dict): Dictionary containing the definition of variables for
each node, used in commands and expected parameters.
Keys should be formed by nodes unique names. Use
special key name __global__ for global variables.
Subkeys: Variable names.
Values: strings.
### Optional Named Parameters:
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses &#34;&gt;&#34; or EOF while
routers use &#34;&gt;&#34; or &#34;#&#34;. The default value should
work for most nodes. Change it if your connection
need some special symbol.
- parallel (int): Number of nodes to run the commands simultaneously.
Default is 10, if there are more nodes that this
value, nodes are groups in groups with max this
number of members.
- timeout (int): Time in seconds for expect to wait for prompt/EOF.
default 10.
- on_complete (callable): Optional callback called when each node
finishes. Receives (unique, output, status).
Called from the node&#39;s thread so it must
be thread-safe.
### Returns:
dict: Dictionary formed by nodes unique as keys, value is True if
expected value is found after running the commands, False
if prompt is found before.
&#39;&#39;&#39;
args = {}
nodesargs = {}
args[&#34;commands&#34;] = commands
args[&#34;expected&#34;] = expected
if folder != None:
args[&#34;folder&#34;] = folder
Path(folder).mkdir(parents=True, exist_ok=True)
if prompt != None:
args[&#34;prompt&#34;] = prompt
if timeout != None:
args[&#34;timeout&#34;] = timeout
output = {}
result = {}
status = {}
tasks = []
def _test_node(node_obj, node_args, callback):
&#34;&#34;&#34;Wrapper that runs a node test and fires the callback on completion.&#34;&#34;&#34;
node_obj.test(**node_args)
if callback:
callback(node_obj.unique, node_obj.output, node_obj.status, node_obj.result)
for n in self.nodelist:
nodesargs[n.unique] = deepcopy(args)
if vars != None:
nodesargs[n.unique][&#34;vars&#34;] = {}
if &#34;__global__&#34; in vars.keys():
nodesargs[n.unique][&#34;vars&#34;].update(vars[&#34;__global__&#34;])
for var_key, var_val in vars.items():
if var_key == &#34;__global__&#34;:
continue
try:
if re.search(var_key, n.unique, re.IGNORECASE):
nodesargs[n.unique][&#34;vars&#34;].update(var_val)
except re.error:
if var_key == n.unique:
nodesargs[n.unique][&#34;vars&#34;].update(var_val)
nodesargs[n.unique][&#34;logger&#34;] = logger
if on_complete:
tasks.append(threading.Thread(target=_test_node, args=(n, nodesargs[n.unique], on_complete)))
else:
tasks.append(threading.Thread(target=n.test, kwargs=nodesargs[n.unique]))
taskslist = list(self._splitlist(tasks, parallel))
for t in taskslist:
for i in t:
i.start()
for i in t:
i.join()
for i in self.nodelist:
result[i.unique] = i.result
output[i.unique] = i.output
status[i.unique] = i.status
self.output = output
self.result = result
self.status = status
return result</code></pre>
</details>
<div class="desc"><p>This class generates a nodes object. Contains a list of node class objects and methods to run multiple tasks on nodes simultaneously.</p>
<h3 id="attributes">Attributes:</h3>
<pre><code>- nodelist (list): List of node class objects passed to the init
function.
- output (dict): Dictionary formed by nodes unique as keys,
output of the commands you ran on the node as
value. Created after running methods run or test.
- result (dict): Dictionary formed by nodes unique as keys, value
is True if expected value is found after running
the commands, False if prompt is found before.
Created after running method test.
- status (dict): Dictionary formed by nodes unique as keys, value:
0 if method run or test ended successfully.
1 if connection failed.
2 if expect timeouts without prompt or EOF.
- &lt;unique&gt; (obj): For each item in nodelist, there is an attribute
generated with the node unique.
</code></pre>
<h3 id="parameters">Parameters:</h3>
<pre><code>- nodes (dict): Dictionary formed by node information:
Keys: Unique name for each node.
Mandatory Subkeys: host(str).
Optional Subkeys: options(str), logs(str), password(str),
port(str), protocol(str), user(str).
For reference on subkeys check node class.
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- config (obj): Pass the object created with class configfile with key
for decryption and extra configuration if you are using
connection manager.
</code></pre></div>
<h3>Methods</h3>
<dl>
<dt id="connpy.nodes.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self,<br>commands,<br>vars=None,<br>*,<br>folder=None,<br>prompt=None,<br>stdout=None,<br>parallel=10,<br>timeout=None,<br>on_complete=None,<br>logger=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def run(self, commands, vars = None,*, folder = None, prompt = None, stdout = None, parallel = 10, timeout = None, on_complete = None, logger = None):
&#39;&#39;&#39;
Run a command or list of commands on all the nodes in nodelist.
### Parameters:
- commands (str/list): Commands to run on the nodes. Should be str or
list of str. You can use variables as {varname}
and defining them in optional parameter vars.
### Optional Parameters:
- vars (dict): Dictionary containing the definition of variables for
each node, used in commands parameter.
Keys should be formed by nodes unique names. Use
special key name __global__ for global variables.
Subkeys: Variable names.
Values: strings.
### Optional Named Parameters:
- folder (str): Path where output log should be stored, leave empty
to disable logging.
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses &#34;&gt;&#34; or EOF while routers
use &#34;&gt;&#34; or &#34;#&#34;. The default value should work for
most nodes. Change it if your connection need some
special symbol.
- stdout (bool): Set True to send the command output to stdout.
Default False.
- parallel (int): Number of nodes to run the commands simultaneously.
Default is 10, if there are more nodes that this
value, nodes are groups in groups with max this
number of members.
- timeout (int): Time in seconds for expect to wait for prompt/EOF.
default 10.
- on_complete (callable): Optional callback called when each node
finishes. Receives (unique, output, status).
Called from the node&#39;s thread so it must
be thread-safe.
###Returns:
dict: Dictionary formed by nodes unique as keys, Output of the
commands you ran on the node as value.
&#39;&#39;&#39;
args = {}
nodesargs = {}
args[&#34;commands&#34;] = commands
if folder != None:
args[&#34;folder&#34;] = folder
Path(folder).mkdir(parents=True, exist_ok=True)
if prompt != None:
args[&#34;prompt&#34;] = prompt
if stdout != None and on_complete is None:
args[&#34;stdout&#34;] = stdout
if timeout != None:
args[&#34;timeout&#34;] = timeout
output = {}
status = {}
tasks = []
def _run_node(node_obj, node_args, callback):
&#34;&#34;&#34;Wrapper that runs a node and fires the callback on completion.&#34;&#34;&#34;
node_obj.run(**node_args)
if callback:
callback(node_obj.unique, node_obj.output, node_obj.status)
for n in self.nodelist:
nodesargs[n.unique] = deepcopy(args)
if vars != None:
nodesargs[n.unique][&#34;vars&#34;] = {}
if &#34;__global__&#34; in vars.keys():
nodesargs[n.unique][&#34;vars&#34;].update(vars[&#34;__global__&#34;])
for var_key, var_val in vars.items():
if var_key == &#34;__global__&#34;:
continue
try:
if re.search(var_key, n.unique, re.IGNORECASE):
nodesargs[n.unique][&#34;vars&#34;].update(var_val)
except re.error:
if var_key == n.unique:
nodesargs[n.unique][&#34;vars&#34;].update(var_val)
# Pass the logger to the node
nodesargs[n.unique][&#34;logger&#34;] = logger
if on_complete:
tasks.append(threading.Thread(target=_run_node, args=(n, nodesargs[n.unique], on_complete)))
else:
tasks.append(threading.Thread(target=n.run, kwargs=nodesargs[n.unique]))
taskslist = list(self._splitlist(tasks, parallel))
for t in taskslist:
for i in t:
i.start()
for i in t:
i.join()
for i in self.nodelist:
output[i.unique] = i.output
status[i.unique] = i.status
self.output = output
self.status = status
return output</code></pre>
</details>
<div class="desc"><p>Run a command or list of commands on all the nodes in nodelist.</p>
<h3 id="parameters">Parameters:</h3>
<pre><code>- commands (str/list): Commands to run on the nodes. Should be str or
list of str. You can use variables as {varname}
and defining them in optional parameter vars.
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- vars (dict): Dictionary containing the definition of variables for
each node, used in commands parameter.
Keys should be formed by nodes unique names. Use
special key name __global__ for global variables.
Subkeys: Variable names.
Values: strings.
</code></pre>
<h3 id="optional-named-parameters">Optional Named Parameters:</h3>
<pre><code>- folder (str): Path where output log should be stored, leave empty
to disable logging.
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses "&gt;" or EOF while routers
use "&gt;" or "#". The default value should work for
most nodes. Change it if your connection need some
special symbol.
- stdout (bool): Set True to send the command output to stdout.
Default False.
- parallel (int): Number of nodes to run the commands simultaneously.
Default is 10, if there are more nodes that this
value, nodes are groups in groups with max this
number of members.
- timeout (int): Time in seconds for expect to wait for prompt/EOF.
default 10.
- on_complete (callable): Optional callback called when each node
finishes. Receives (unique, output, status).
Called from the node's thread so it must
be thread-safe.
</code></pre>
<h3 id="returns">Returns:</h3>
<pre><code>dict: Dictionary formed by nodes unique as keys, Output of the
commands you ran on the node as value.
</code></pre></div>
</dd>
<dt id="connpy.nodes.test"><code class="name flex">
<span>def <span class="ident">test</span></span>(<span>self,<br>commands,<br>expected,<br>vars=None,<br>*,<br>folder=None,<br>prompt=None,<br>parallel=10,<br>timeout=None,<br>on_complete=None,<br>logger=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@MethodHook
def test(self, commands, expected, vars = None,*, folder = None, prompt = None, parallel = 10, timeout = None, on_complete = None, logger = None):
&#39;&#39;&#39;
Run a command or list of commands on all the nodes in nodelist, then check if expected value appears on the output after the last command.
### Parameters:
- commands (str/list): Commands to run on the node. Should be str or
list of str.
- expected (str) : Expected text to appear after running all the
commands on the node.
### Optional Parameters:
- vars (dict): Dictionary containing the definition of variables for
each node, used in commands and expected parameters.
Keys should be formed by nodes unique names. Use
special key name __global__ for global variables.
Subkeys: Variable names.
Values: strings.
### Optional Named Parameters:
- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses &#34;&gt;&#34; or EOF while
routers use &#34;&gt;&#34; or &#34;#&#34;. The default value should
work for most nodes. Change it if your connection
need some special symbol.
- parallel (int): Number of nodes to run the commands simultaneously.
Default is 10, if there are more nodes that this
value, nodes are groups in groups with max this
number of members.
- timeout (int): Time in seconds for expect to wait for prompt/EOF.
default 10.
- on_complete (callable): Optional callback called when each node
finishes. Receives (unique, output, status).
Called from the node&#39;s thread so it must
be thread-safe.
### Returns:
dict: Dictionary formed by nodes unique as keys, value is True if
expected value is found after running the commands, False
if prompt is found before.
&#39;&#39;&#39;
args = {}
nodesargs = {}
args[&#34;commands&#34;] = commands
args[&#34;expected&#34;] = expected
if folder != None:
args[&#34;folder&#34;] = folder
Path(folder).mkdir(parents=True, exist_ok=True)
if prompt != None:
args[&#34;prompt&#34;] = prompt
if timeout != None:
args[&#34;timeout&#34;] = timeout
output = {}
result = {}
status = {}
tasks = []
def _test_node(node_obj, node_args, callback):
&#34;&#34;&#34;Wrapper that runs a node test and fires the callback on completion.&#34;&#34;&#34;
node_obj.test(**node_args)
if callback:
callback(node_obj.unique, node_obj.output, node_obj.status, node_obj.result)
for n in self.nodelist:
nodesargs[n.unique] = deepcopy(args)
if vars != None:
nodesargs[n.unique][&#34;vars&#34;] = {}
if &#34;__global__&#34; in vars.keys():
nodesargs[n.unique][&#34;vars&#34;].update(vars[&#34;__global__&#34;])
for var_key, var_val in vars.items():
if var_key == &#34;__global__&#34;:
continue
try:
if re.search(var_key, n.unique, re.IGNORECASE):
nodesargs[n.unique][&#34;vars&#34;].update(var_val)
except re.error:
if var_key == n.unique:
nodesargs[n.unique][&#34;vars&#34;].update(var_val)
nodesargs[n.unique][&#34;logger&#34;] = logger
if on_complete:
tasks.append(threading.Thread(target=_test_node, args=(n, nodesargs[n.unique], on_complete)))
else:
tasks.append(threading.Thread(target=n.test, kwargs=nodesargs[n.unique]))
taskslist = list(self._splitlist(tasks, parallel))
for t in taskslist:
for i in t:
i.start()
for i in t:
i.join()
for i in self.nodelist:
result[i.unique] = i.result
output[i.unique] = i.output
status[i.unique] = i.status
self.output = output
self.result = result
self.status = status
return result</code></pre>
</details>
<div class="desc"><p>Run a command or list of commands on all the nodes in nodelist, then check if expected value appears on the output after the last command.</p>
<h3 id="parameters">Parameters:</h3>
<pre><code>- commands (str/list): Commands to run on the node. Should be str or
list of str.
- expected (str) : Expected text to appear after running all the
commands on the node.
</code></pre>
<h3 id="optional-parameters">Optional Parameters:</h3>
<pre><code>- vars (dict): Dictionary containing the definition of variables for
each node, used in commands and expected parameters.
Keys should be formed by nodes unique names. Use
special key name __global__ for global variables.
Subkeys: Variable names.
Values: strings.
</code></pre>
<h3 id="optional-named-parameters">Optional Named Parameters:</h3>
<pre><code>- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses "&gt;" or EOF while
routers use "&gt;" or "#". The default value should
work for most nodes. Change it if your connection
need some special symbol.
- parallel (int): Number of nodes to run the commands simultaneously.
Default is 10, if there are more nodes that this
value, nodes are groups in groups with max this
number of members.
- timeout (int): Time in seconds for expect to wait for prompt/EOF.
default 10.
- on_complete (callable): Optional callback called when each node
finishes. Receives (unique, output, status).
Called from the node's thread so it must
be thread-safe.
</code></pre>
<h3 id="returns">Returns:</h3>
<pre><code>dict: Dictionary formed by nodes unique as keys, value is True if
expected value is found after running the commands, False
if prompt is found before.
</code></pre></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul>
<li><a href="#connpy">Connpy</a><ul>
<li><a href="#ai-copilot-new-in-v6">🤖 AI Copilot (New in v6)</a></li>
<li><a href="#core-features">Core Features</a></li>
<li><a href="#installation">Installation</a><ul>
<li><a href="#run-it-in-windowslinux-using-docker">Run it in Windows/Linux using Docker</a></li>
</ul>
</li>
<li><a href="#privacy-integration">🔒 Privacy &amp; Integration</a><ul>
<li><a href="#privacy-policy">Privacy Policy</a></li>
<li><a href="#google-integration">Google Integration</a></li>
</ul>
</li>
<li><a href="#usage">Usage</a><ul>
<li><a href="#basic-examples">Basic Examples:</a></li>
</ul>
</li>
<li><a href="#plugin-requirements-for-connpy">Plugin Requirements for Connpy</a><ul>
<li><a href="#remote-plugin-execution">Remote Plugin Execution</a></li>
<li><a href="#general-structure">General Structure</a></li>
<li><a href="#preload-modifications-and-hooks">Preload Modifications and Hooks</a></li>
<li><a href="#command-completion-support">Command Completion Support</a></li>
</ul>
</li>
<li><a href="#grpc-service-architecture">⚙️ gRPC Service Architecture</a></li>
<li><a href="#automation-module-api">🐍 Automation Module (API)</a><ul>
<li><a href="#basic-execution">Basic Execution</a></li>
<li><a href="#parallel-tasks-with-variables">Parallel Tasks with Variables</a></li>
<li><a href="#ai-programmatic-use">AI Programmatic Use</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<ul id="index">
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="connpy.cli" href="cli/index.html">connpy.cli</a></code></li>
<li><code><a title="connpy.grpc_layer" href="grpc_layer/index.html">connpy.grpc_layer</a></code></li>
<li><code><a title="connpy.mcp_client" href="mcp_client.html">connpy.mcp_client</a></code></li>
<li><code><a title="connpy.proto" href="proto/index.html">connpy.proto</a></code></li>
<li><code><a title="connpy.services" href="services/index.html">connpy.services</a></code></li>
<li><code><a title="connpy.tests" href="tests/index.html">connpy.tests</a></code></li>
<li><code><a title="connpy.tunnels" href="tunnels.html">connpy.tunnels</a></code></li>
<li><code><a title="connpy.utils" href="utils.html">connpy.utils</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="connpy.Plugins" href="#connpy.Plugins">Plugins</a></code></h4>
<ul class="">
<li><code><a title="connpy.Plugins.verify_script" href="#connpy.Plugins.verify_script">verify_script</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="connpy.ai" href="#connpy.ai">ai</a></code></h4>
<ul class="">
<li><code><a title="connpy.ai.SAFE_COMMANDS" href="#connpy.ai.SAFE_COMMANDS">SAFE_COMMANDS</a></code></li>
<li><code><a title="connpy.ai.aask_copilot" href="#connpy.ai.aask_copilot">aask_copilot</a></code></li>
<li><code><a title="connpy.ai.architect_system_prompt" href="#connpy.ai.architect_system_prompt">architect_system_prompt</a></code></li>
<li><code><a title="connpy.ai.ask" href="#connpy.ai.ask">ask</a></code></li>
<li><code><a title="connpy.ai.confirm" href="#connpy.ai.confirm">confirm</a></code></li>
<li><code><a title="connpy.ai.delete_session" href="#connpy.ai.delete_session">delete_session</a></code></li>
<li><code><a title="connpy.ai.engineer_system_prompt" href="#connpy.ai.engineer_system_prompt">engineer_system_prompt</a></code></li>
<li><code><a title="connpy.ai.get_last_session_id" href="#connpy.ai.get_last_session_id">get_last_session_id</a></code></li>
<li><code><a title="connpy.ai.get_node_info_tool" href="#connpy.ai.get_node_info_tool">get_node_info_tool</a></code></li>
<li><code><a title="connpy.ai.list_nodes_tool" href="#connpy.ai.list_nodes_tool">list_nodes_tool</a></code></li>
<li><code><a title="connpy.ai.list_sessions" href="#connpy.ai.list_sessions">list_sessions</a></code></li>
<li><code><a title="connpy.ai.load_session_data" href="#connpy.ai.load_session_data">load_session_data</a></code></li>
<li><code><a title="connpy.ai.manage_memory_tool" href="#connpy.ai.manage_memory_tool">manage_memory_tool</a></code></li>
<li><code><a title="connpy.ai.register_ai_tool" href="#connpy.ai.register_ai_tool">register_ai_tool</a></code></li>
<li><code><a title="connpy.ai.run_commands_tool" href="#connpy.ai.run_commands_tool">run_commands_tool</a></code></li>
<li><code><a title="connpy.ai.save_session" href="#connpy.ai.save_session">save_session</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="connpy.configfile" href="#connpy.configfile">configfile</a></code></h4>
<ul class="">
<li><code><a title="connpy.configfile.encrypt" href="#connpy.configfile.encrypt">encrypt</a></code></li>
<li><code><a title="connpy.configfile.getitem" href="#connpy.configfile.getitem">getitem</a></code></li>
<li><code><a title="connpy.configfile.getitems" href="#connpy.configfile.getitems">getitems</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="connpy.node" href="#connpy.node">node</a></code></h4>
<ul class="">
<li><code><a title="connpy.node.interact" href="#connpy.node.interact">interact</a></code></li>
<li><code><a title="connpy.node.run" href="#connpy.node.run">run</a></code></li>
<li><code><a title="connpy.node.test" href="#connpy.node.test">test</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="connpy.nodes" href="#connpy.nodes">nodes</a></code></h4>
<ul class="">
<li><code><a title="connpy.nodes.run" href="#connpy.nodes.run">run</a></code></li>
<li><code><a title="connpy.nodes.test" href="#connpy.nodes.test">test</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.5</a>.</p>
</footer>
</body>
</html>