Compare commits
28 Commits
1c814eb9fd
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 3ca6f497d1 | |||
| 1db4a045e5 | |||
| 7b01a0c05f | |||
| 5a8b744aa8 | |||
| 9446bafc0c | |||
| 64377f7f30 | |||
| e4fd1adba3 | |||
| b0a914ad7f | |||
| 05fb9951c6 | |||
| 12543c683e | |||
| 3ad4f6da1f | |||
| 5c4e2116c8 | |||
| 2666a3db1f | |||
| dba7e24dda | |||
| 1103393be6 | |||
| a08d84139d | |||
| d62af8b037 | |||
| 14a298dd4d | |||
| 61552cffa9 | |||
| c4d704f473 | |||
| f6078b6fde | |||
| 37db74f47d | |||
| 16868828c6 | |||
| a192bd1912 | |||
| c81f6e049f | |||
| 918fc9a07c | |||
| 7967c413c9 | |||
| 96049b4028 |
@@ -0,0 +1,22 @@
|
|||||||
|
.git
|
||||||
|
__pycache__
|
||||||
|
*.pyc
|
||||||
|
*.pyo
|
||||||
|
*.pyd
|
||||||
|
.pytest_cache
|
||||||
|
.venv
|
||||||
|
venv
|
||||||
|
env
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
build
|
||||||
|
*.egg-info
|
||||||
|
docker
|
||||||
|
docker-compose.yml
|
||||||
|
.gemini
|
||||||
|
.github
|
||||||
|
docs
|
||||||
|
scratch
|
||||||
|
testall
|
||||||
|
testremote
|
||||||
|
automation-template.yaml
|
||||||
+10
@@ -50,6 +50,7 @@ coverage.xml
|
|||||||
*.py,cover
|
*.py,cover
|
||||||
.hypothesis/
|
.hypothesis/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
|
scratch/
|
||||||
|
|
||||||
# Translations
|
# Translations
|
||||||
*.mo
|
*.mo
|
||||||
@@ -160,3 +161,12 @@ ssm_implemmetaiton_plan.md
|
|||||||
async_interact_plan.md
|
async_interact_plan.md
|
||||||
repo_consolidado_limpio.md
|
repo_consolidado_limpio.md
|
||||||
connpy_roadmap.md
|
connpy_roadmap.md
|
||||||
|
MULTI_USER_PLAN.md
|
||||||
|
COPILOT_PLAN.md
|
||||||
|
ARCHITECTURAL_DEBT_REFACTOR.md
|
||||||
|
COPILOT_UI_FEATURES.md
|
||||||
|
MULTI_USER_IMPLEMENTATION_STEPS.md
|
||||||
|
|
||||||
|
#themes
|
||||||
|
nord.yml
|
||||||
|
theme.py
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
include LICENSE
|
||||||
|
include README.md
|
||||||
|
include requirements.txt
|
||||||
|
recursive-include connpy/core_plugins *
|
||||||
|
recursive-include connpy/proto *
|
||||||
|
recursive-include connpy/grpc_layer *
|
||||||
|
recursive-exclude * __pycache__
|
||||||
|
recursive-exclude * *.py[co]
|
||||||
@@ -9,519 +9,182 @@
|
|||||||
[](https://github.com/fluzzi/connpy/blob/main/LICENSE)
|
[](https://github.com/fluzzi/connpy/blob/main/LICENSE)
|
||||||
[](https://pypi.org/pypi/connpy/)
|
[](https://pypi.org/pypi/connpy/)
|
||||||
|
|
||||||
Connpy is a SSH, SFTP, Telnet, kubectl, Docker pod, and AWS SSM connection manager and automation module for Linux, Mac, and Docker.
|
**Connpy** is a powerful Connection Manager and Network Automation Platform for Linux, Mac, and Docker. It provides a unified interface for **SSH, SFTP, Telnet, kubectl, Docker pods, and AWS SSM**.
|
||||||
|
|
||||||
|
The v6 release introduces the **AI Copilot**, an interactive terminal assistant that understands your network context and helps you manage your infrastructure more intelligently.
|
||||||
|
|
||||||
|
|
||||||
|
## 🤖 AI Copilot (New in v6)
|
||||||
|
The AI Copilot is deeply integrated into your terminal workflow:
|
||||||
|
- **Terminal Context Awareness**: The Copilot can "see" your screen output, helping you diagnose errors or analyze command results in real-time.
|
||||||
|
- **Hybrid Multi-Agent System**: Automatically escalates complex tasks between the **Network Engineer** (execution) and the **Network Architect** (strategy).
|
||||||
|
- **MCP Integration**: Dynamically load tools from external providers (6WIND, AWS, etc.) via the Model Context Protocol.
|
||||||
|
- **Interactive Chat**: Launch with `conn ai` for a collaborative troubleshooting session.
|
||||||
|
|
||||||
|
|
||||||
|
## Core Features
|
||||||
|
- **Multi-Protocol**: Native support for SSH, SFTP, Telnet, kubectl, Docker exec, and AWS SSM.
|
||||||
|
- **Context Management**: Set regex-based contexts to manage specific nodes across different environments (work, home, clients).
|
||||||
|
- **Advanced Inventory**:
|
||||||
|
- Organize nodes in folders (`@folder`) and subfolders (`@subfolder@folder`).
|
||||||
|
- Use Global Profiles (`@profilename`) to manage shared credentials easily.
|
||||||
|
- Bulk creation, copying, moving, and export/import of nodes.
|
||||||
|
- **Modern UI**: High-performance terminal experience with `prompt-toolkit`, including:
|
||||||
|
- Fuzzy search integration with `fzf`.
|
||||||
|
- Advanced tab completion.
|
||||||
|
- Syntax highlighting and customizable themes.
|
||||||
|
- **Automation Engine**: Run parallel tasks and playbooks on multiple devices with variable support.
|
||||||
|
- **Plugin System**: Build and execute custom Python scripts locally or on a remote gRPC server.
|
||||||
|
- **gRPC Architecture**: Fully decoupled Client/Server model for distributed management.
|
||||||
|
- **Privacy & Sync**: Local-first encrypted storage (RSA/OAEP) with optional Google Drive backup.
|
||||||
|
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
pip install connpy
|
pip install connpy
|
||||||
|
|
||||||
### Run it in Windows using docker
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Run it in Windows/Linux using Docker
|
||||||
|
```bash
|
||||||
git clone https://github.com/fluzzi/connpy
|
git clone https://github.com/fluzzi/connpy
|
||||||
docker compose -f path/to/folder/docker-compose.yml build
|
cd connpy
|
||||||
docker compose -f path/to/folder/docker-compose.yml run -it connpy-app
|
docker compose build
|
||||||
|
|
||||||
|
# Run it like a native app (completely silent)
|
||||||
|
docker compose 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 run --rm --remove-orphans connpy-app'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Connection manager
|
---
|
||||||
|
|
||||||
|
## 🔒 Privacy & Integration
|
||||||
|
|
||||||
### Privacy Policy
|
### Privacy Policy
|
||||||
|
Connpy is committed to protecting your privacy:
|
||||||
Connpy is committed to protecting your privacy. Our privacy policy explains how we handle user data:
|
- **Local Storage**: All server addresses, usernames, and passwords are encrypted and stored **only** on your machine. No data is transmitted to our servers.
|
||||||
|
- **Data Access**: Data is used solely for managing and automating your connections.
|
||||||
- **Data Access**: Connpy accesses data necessary for managing remote host connections, including server addresses, usernames, and passwords. This data is stored locally on your machine and is not transmitted or shared with any third parties.
|
|
||||||
- **Data Usage**: User data is used solely for the purpose of managing and automating SSH, Telnet, and SSM connections.
|
|
||||||
- **Data Storage**: All connection details are stored locally and securely on your device. We do not store or process this data on our servers.
|
|
||||||
- **Data Sharing**: We do not share any user data with third parties.
|
|
||||||
|
|
||||||
### Google Integration
|
### Google Integration
|
||||||
|
Used strictly for backup:
|
||||||
|
- **Backup**: Sync your encrypted configuration with your Google Drive account.
|
||||||
|
- **Scoped Access**: Connpy only accesses its own backup files.
|
||||||
|
|
||||||
Connpy integrates with Google services for backup purposes:
|
---
|
||||||
|
|
||||||
- **Configuration Backup**: The app allows users to store their device information in the app configuration. This configuration can be synced with Google services to create backups.
|
## Usage
|
||||||
- **Data Access**: Connpy only accesses its own files and does not access any other files on your Google account.
|
|
||||||
- **Data Usage**: The data is used solely for backup and restore purposes, ensuring that your device information and configurations are safe and recoverable.
|
|
||||||
- **Data Sharing**: Connpy does not share any user data with third parties, including Google. The backup data is only accessible by the user.
|
|
||||||
|
|
||||||
For more detailed information, please read our [Privacy Policy](https://connpy.gederico.dynu.net/fluzzi32/connpy/src/branch/main/PRIVATE_POLICY.md).
|
```bash
|
||||||
|
|
||||||
|
|
||||||
### Features
|
|
||||||
- Manage connections using SSH, SFTP, Telnet, kubectl, Docker exec, and AWS SSM.
|
|
||||||
- Set contexts to manage specific nodes from specific contexts (work/home/clients/etc).
|
|
||||||
- You can generate profiles and reference them from nodes using @profilename so you don't
|
|
||||||
need to edit multiple nodes when changing passwords or other information.
|
|
||||||
- Nodes can be stored on @folder or @subfolder@folder to organize your devices. They can
|
|
||||||
be referenced using node@subfolder@folder or node@folder.
|
|
||||||
- If you have too many nodes, get a completion script using: conn config --completion.
|
|
||||||
Or use fzf by installing pyfzf and running conn config --fzf true.
|
|
||||||
- Create in bulk, copy, move, export, and import nodes for easy management.
|
|
||||||
- Run automation scripts on network devices.
|
|
||||||
- Use AI with a multi-agent system (Engineer/Architect) to manage devices.
|
|
||||||
Supports any LLM provider via litellm (OpenAI, Anthropic, Google, etc.).
|
|
||||||
Features streaming responses, interactive chat, and extensible plugin tools.
|
|
||||||
- Add plugins with your own scripts, and execute them remotely.
|
|
||||||
- Fully decoupled gRPC Client/Server architecture.
|
|
||||||
- Unified UI with syntax highlighting and theming.
|
|
||||||
- Much more!
|
|
||||||
|
|
||||||
### Usage:
|
|
||||||
```
|
|
||||||
usage: conn [-h] [--add | --del | --mod | --show | --debug] [node|folder] [--sftp]
|
usage: conn [-h] [--add | --del | --mod | --show | --debug] [node|folder] [--sftp]
|
||||||
conn {profile,move,mv,copy,cp,list,ls,bulk,export,import,ai,run,api,plugin,config,sync,context} ...
|
conn {profile,move,copy,list,bulk,export,import,ai,run,api,plugin,config,sync,context} ...
|
||||||
|
|
||||||
positional arguments:
|
|
||||||
node|folder node[@subfolder][@folder]
|
|
||||||
Connect to specific node or show all matching nodes
|
|
||||||
[@subfolder][@folder]
|
|
||||||
Show all available connections globally or in specified path
|
|
||||||
|
|
||||||
options:
|
|
||||||
-h, --help show this help message and exit
|
|
||||||
-v, --version Show version
|
|
||||||
-a, --add Add new node[@subfolder][@folder] or [@subfolder]@folder
|
|
||||||
-r, --del, --rm Delete node[@subfolder][@folder] or [@subfolder]@folder
|
|
||||||
-e, --mod, --edit Modify node[@subfolder][@folder]
|
|
||||||
-s, --show Show node[@subfolder][@folder]
|
|
||||||
-d, --debug Display all conections steps
|
|
||||||
-t, --sftp Connects using sftp instead of ssh
|
|
||||||
--service-mode Set the backend service mode (local or remote)
|
|
||||||
--remote Connect to a remote connpy service via gRPC
|
|
||||||
--theme UI Output theme (dark, light, or path)
|
|
||||||
|
|
||||||
Commands:
|
|
||||||
profile Manage profiles
|
|
||||||
move(mv) Move node
|
|
||||||
copy(cp) Copy node
|
|
||||||
list(ls) List profiles, nodes or folders
|
|
||||||
bulk Add nodes in bulk
|
|
||||||
export Export connection folder to Yaml file
|
|
||||||
import Import connection folder to config from Yaml file
|
|
||||||
ai Make request to an AI
|
|
||||||
run Run scripts or commands on nodes
|
|
||||||
api Start and stop connpy api
|
|
||||||
plugin Manage plugins
|
|
||||||
config Manage app config
|
|
||||||
sync Sync config with Google
|
|
||||||
context Manage contexts with regex matching
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Manage profiles:
|
### Basic Examples:
|
||||||
```
|
```bash
|
||||||
usage: conn profile [-h] (--add | --del | --mod | --show) profile
|
# Add a folder and subfolder
|
||||||
|
|
||||||
positional arguments:
|
|
||||||
profile Name of profile to manage
|
|
||||||
|
|
||||||
options:
|
|
||||||
-h, --help show this help message and exit
|
|
||||||
-a, --add Add new profile
|
|
||||||
-r, --del, --rm Delete profile
|
|
||||||
-e, --mod, --edit Modify profile
|
|
||||||
-s, --show Show profile
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
### Examples:
|
|
||||||
```
|
|
||||||
#Add new profile
|
|
||||||
conn profile --add office-user
|
|
||||||
#Add new folder
|
|
||||||
conn --add @office
|
conn --add @office
|
||||||
#Add new subfolder
|
|
||||||
conn --add @datacenter@office
|
conn --add @datacenter@office
|
||||||
#Add node to subfolder
|
|
||||||
conn --add server@datacenter@office
|
# Add a node with a profile
|
||||||
#Add node to folder
|
conn --add server1@datacenter@office --profile @myuser
|
||||||
conn --add pc@office
|
|
||||||
#Show node information
|
# Connect to a node (fuzzy match)
|
||||||
conn --show server@datacenter@office
|
conn server1
|
||||||
#Connect to nodes
|
|
||||||
conn pc@office
|
# Start the AI Copilot
|
||||||
conn server
|
conn ai
|
||||||
#Create and set new context
|
|
||||||
conn context -a office .*@office
|
# Run a command on all nodes in a folder
|
||||||
conn context --set office
|
conn run @office "uptime"
|
||||||
#Run a command in a node
|
|
||||||
conn run server ls -la
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔌 Plugin System
|
||||||
|
Connpy supports a robust plugin architecture where scripts can run transparently on a remote gRPC server.
|
||||||
|
|
||||||
|
### Structure
|
||||||
|
Plugins must be Python files containing:
|
||||||
|
- **Class `Parser`**: Defines `argparse` arguments.
|
||||||
|
- **Class `Entrypoint`**: Execution logic.
|
||||||
|
- **Class `Preload`**: (Optional) Hooks and modifications to the core app.
|
||||||
|
|
||||||
|
See the [Plugin Requirements section](#plugin-requirements-for-connpy) for full technical details.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Plugin Requirements for Connpy
|
## Plugin Requirements for Connpy
|
||||||
|
|
||||||
### Remote Plugin Execution
|
### Remote Plugin Execution
|
||||||
When Connpy operates in remote mode, plugins are executed **transparently on the server**:
|
When Connpy operates in remote mode, plugins are executed **transparently on the server**:
|
||||||
- The client automatically downloads the plugin source code (`Parser` class context) to generate the local `argparse` structure and provide autocompletion.
|
- The client automatically downloads the plugin source code (`Parser` class context) to generate the local `argparse` structure and provide autocompletion.
|
||||||
- The execution phase (`Entrypoint` class) is redirected via gRPC streams to execute in the server's memory, ensuring the plugin runs securely against the server's inventory without passing sensitive data to the client.
|
- The execution phase (`Entrypoint` class) is redirected via gRPC streams to execute in the server's memory.
|
||||||
- You can manage remote plugins using the `--remote` flag (e.g. `connpy plugin --add myplugin script.py --remote`).
|
- You can manage remote plugins using the `--remote` flag.
|
||||||
|
|
||||||
### General Structure
|
### General Structure
|
||||||
- The plugin script must be a Python file.
|
- The plugin script must define specific classes:
|
||||||
- Only the following top-level elements are allowed in the plugin script:
|
1. **Class `Parser`**: Handles `argparse.ArgumentParser` initialization.
|
||||||
- Class definitions
|
2. **Class `Entrypoint`**: Main execution logic (receives `args`, `parser`, and `connapp`).
|
||||||
- Function definitions
|
3. **Class `Preload`**: (Optional) For modifying core app behavior or registering hooks.
|
||||||
- Import statements
|
|
||||||
- The `if __name__ == "__main__":` block for standalone execution
|
|
||||||
- Pass statements
|
|
||||||
|
|
||||||
### Specific Class Requirements
|
|
||||||
- The plugin script must define specific classes with particular attributes and methods. Each class serves a distinct role within the plugin's architecture:
|
|
||||||
1. **Class `Parser`**:
|
|
||||||
- **Purpose**: Handles parsing of command-line arguments.
|
|
||||||
- **Requirements**:
|
|
||||||
- Must contain only one method: `__init__`.
|
|
||||||
- The `__init__` method must initialize at least one attribute:
|
|
||||||
- `self.parser`: An instance of `argparse.ArgumentParser`.
|
|
||||||
2. **Class `Entrypoint`**:
|
|
||||||
- **Purpose**: Acts as the entry point for plugin execution, utilizing parsed arguments and integrating with the main application.
|
|
||||||
- **Requirements**:
|
|
||||||
- Must have an `__init__` method that accepts exactly three parameters besides `self`:
|
|
||||||
- `args`: Arguments passed to the plugin.
|
|
||||||
- The parser instance (typically `self.parser` from the `Parser` class).
|
|
||||||
- The Connapp instance to interact with the Connpy app.
|
|
||||||
3. **Class `Preload`**:
|
|
||||||
- **Purpose**: Performs any necessary preliminary setup or configuration independent of the main parsing and entry logic.
|
|
||||||
- **Requirements**:
|
|
||||||
- Contains at least an `__init__` method that accepts parameter connapp besides `self`.
|
|
||||||
|
|
||||||
### Class Dependencies and Combinations
|
|
||||||
- **Dependencies**:
|
|
||||||
- `Parser` and `Entrypoint` are interdependent and must both be present if one is included.
|
|
||||||
- `Preload` is independent and may exist alone or alongside the other classes.
|
|
||||||
- **Valid Combinations**:
|
|
||||||
- `Parser` and `Entrypoint` together.
|
|
||||||
- `Preload` alone.
|
|
||||||
- All three classes (`Parser`, `Entrypoint`, `Preload`).
|
|
||||||
|
|
||||||
### Preload Modifications and Hooks
|
### Preload Modifications and Hooks
|
||||||
|
You can customize the behavior of core classes using hooks:
|
||||||
In the `Preload` class of the plugin system, you have the ability to customize the behavior of existing classes and methods within the application through a robust hooking system. This documentation explains how to use the `modify`, `register_pre_hook`, and `register_post_hook` methods to tailor plugin functionality to your needs.
|
- **`modify(method)`**: Alter class instances (e.g., `connapp.config`, `connapp.ai`).
|
||||||
|
- **`register_pre_hook(method)`**: Logic to run before a method execution.
|
||||||
#### Modifying Classes with `modify`
|
- **`register_post_hook(method)`**: Logic to run after a method execution.
|
||||||
The `modify` method allows you to alter instances of a class at the time they are created or after their creation. This is particularly useful for setting or modifying configuration settings, altering default behaviors, or adding new functionalities to existing classes without changing the original class definitions.
|
|
||||||
|
|
||||||
- **Usage**: Modify a class to include additional configurations or changes
|
|
||||||
- **Modify Method Signature**:
|
|
||||||
- `modify(modification_method)`: A function that is invoked with an instance of the class as its argument. This function should perform any modifications directly on this instance.
|
|
||||||
- **Modification Method Signature**:
|
|
||||||
- **Arguments**:
|
|
||||||
- `cls`: This function accepts a single argument, the class instance, which it then modifies.
|
|
||||||
- **Modifiable Classes**:
|
|
||||||
- `connapp.config`
|
|
||||||
- `connapp.node`
|
|
||||||
- `connapp.nodes`
|
|
||||||
- `connapp.ai`
|
|
||||||
- ```python
|
|
||||||
def modify_config(cls):
|
|
||||||
# Example modification: adding a new attribute or modifying an existing one
|
|
||||||
cls.new_attribute = 'New Value'
|
|
||||||
|
|
||||||
class Preload:
|
|
||||||
def __init__(self, connapp):
|
|
||||||
# Applying modification to the config class instance
|
|
||||||
connapp.config.modify(modify_config)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Implementing Method Hooks
|
|
||||||
There are 2 methods that allows you to define custom logic to be executed before (`register_pre_hook`) or after (`register_post_hook`) the main logic of a method. This is particularly useful for logging, auditing, preprocessing inputs, postprocessing outputs or adding functionalities.
|
|
||||||
|
|
||||||
- **Usage**: Register hooks to methods to execute additional logic before or after the main method execution.
|
|
||||||
- **Registration Methods Signature**:
|
|
||||||
- `register_pre_hook(pre_hook_method)`: A function that is invoked before the main method is executed. This function should do preprocessing of the arguments.
|
|
||||||
- `register_post_hook(post_hook_method)`: A function that is invoked after the main method is executed. This function should do postprocessing of the outputs.
|
|
||||||
- **Method Signatures for Pre-Hooks**
|
|
||||||
- `pre_hook_method(*args, **kwargs)`
|
|
||||||
- **Arguments**:
|
|
||||||
- `*args`, `**kwargs`: The arguments and keyword arguments that will be passed to the method being hooked. The pre-hook function has the opportunity to inspect and modify these arguments before they are passed to the main method.
|
|
||||||
- **Return**:
|
|
||||||
- Must return a tuple `(args, kwargs)`, which will be used as the new arguments for the main method. If the original arguments are not modified, the function should return them as received.
|
|
||||||
- **Method Signatures for Post-Hooks**:
|
|
||||||
- `post_hook_method(*args, **kwargs)`
|
|
||||||
- **Arguments**:
|
|
||||||
- `*args`, `**kwargs`: The arguments and keyword arguments that were passed to the main method.
|
|
||||||
- `kwargs["result"]`: The value returned by the main method. This allows the post-hook to inspect and even alter the result before it is returned to the original caller.
|
|
||||||
- **Return**:
|
|
||||||
- Can return a modified result, which will replace the original result of the main method, or simply return `kwargs["result"]` to return the original method result.
|
|
||||||
- ```python
|
|
||||||
def pre_processing_hook(*args, **kwargs):
|
|
||||||
print("Pre-processing logic here")
|
|
||||||
# Modify arguments or perform any checks
|
|
||||||
return args, kwargs # Return modified or unmodified args and kwargs
|
|
||||||
|
|
||||||
def post_processing_hook(*args, **kwargs):
|
|
||||||
print("Post-processing logic here")
|
|
||||||
# Modify the result or perform any final logging or cleanup
|
|
||||||
return kwargs["result"] # Return the modified or unmodified result
|
|
||||||
|
|
||||||
class Preload:
|
|
||||||
def __init__(self, connapp):
|
|
||||||
# Registering a pre-hook
|
|
||||||
connapp.ai.some_method.register_pre_hook(pre_processing_hook)
|
|
||||||
|
|
||||||
# Registering a post-hook
|
|
||||||
connapp.node.another_method.register_post_hook(post_processing_hook)
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Executable Block
|
|
||||||
- The plugin script can include an executable block:
|
|
||||||
- `if __name__ == "__main__":`
|
|
||||||
- This block allows the plugin to be run as a standalone script for testing or independent use.
|
|
||||||
|
|
||||||
### Command Completion Support
|
### Command Completion Support
|
||||||
|
Plugins can provide intelligent tab completion:
|
||||||
|
1. **Tree-based Completion (Recommended)**: Define `_connpy_tree(info)` returning a navigation dictionary.
|
||||||
|
2. **Legacy Completion**: Define `_connpy_completion(wordsnumber, words, info)`.
|
||||||
|
|
||||||
Plugins can provide intelligent **tab completion** by defining autocompletion logic. There are two supported methods, with the tree-based approach being the most modern and recommended.
|
---
|
||||||
|
|
||||||
#### 1. Tree-based Completion (Recommended)
|
## ⚙️ gRPC Service Architecture
|
||||||
|
Connpy can operate in a decoupled mode:
|
||||||
|
1. **Start the API (Server)**: `conn api -s 50051`
|
||||||
|
2. **Configure the Client**:
|
||||||
|
```bash
|
||||||
|
conn config --service-mode remote
|
||||||
|
conn config --remote-host localhost:50051
|
||||||
|
```
|
||||||
|
All inventory management and execution will now happen on the server.
|
||||||
|
|
||||||
Define a function called `_connpy_tree` that returns a declarative navigation tree. This method is highly efficient, supports complex state loops, and is very simple to implement for most use cases.
|
---
|
||||||
|
|
||||||
|
## 🐍 Automation Module (API)
|
||||||
|
You can use `connpy` as a Python library for your own scripts.
|
||||||
|
|
||||||
|
### Basic Execution
|
||||||
```python
|
```python
|
||||||
def _connpy_tree(info=None):
|
|
||||||
nodes = info.get("nodes", [])
|
|
||||||
return {
|
|
||||||
"__exclude_used__": True, # Filter out words already typed
|
|
||||||
"__extra__": nodes, # Suggest nodes at this level
|
|
||||||
"--format": ["json", "yaml", "table"], # Fixed suggestions
|
|
||||||
"*": { # Wildcard matches any positional word
|
|
||||||
"interface1": None,
|
|
||||||
"interface2": None,
|
|
||||||
"--verbose": None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Keys**: Literal completions (exact matches).
|
|
||||||
- **`*` Key**: A wildcard that matches any positional word typed by the user.
|
|
||||||
- **`__extra__`**: A list or a callable `(words) -> list` that adds dynamic suggestions.
|
|
||||||
- **`__exclude_used__`**: (Boolean) If True, automatically filters out words already present in the command line.
|
|
||||||
|
|
||||||
#### 2. Legacy Function-based Completion
|
|
||||||
|
|
||||||
For backward compatibility or highly custom logic, you can define `_connpy_completion`.
|
|
||||||
|
|
||||||
```python
|
|
||||||
def _connpy_completion(wordsnumber, words, info=None):
|
|
||||||
if wordsnumber == 3:
|
|
||||||
return ["--help", "--verbose", "start", "stop"]
|
|
||||||
|
|
||||||
elif wordsnumber == 4 and words[2] == "start":
|
|
||||||
return info["nodes"] # Suggest node names
|
|
||||||
|
|
||||||
return []
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Description |
|
|
||||||
|----------------|-------------|
|
|
||||||
| `wordsnumber` | Integer indicating the total number of words on the command line. For plugins, this typically starts at 3. |
|
|
||||||
| `words` | A list of tokens (words) already typed. `words[0]` is always the name of the plugin. |
|
|
||||||
| `info` | A dictionary of structured context data (`nodes`, `folders`, `profiles`, `config`). |
|
|
||||||
|
|
||||||
> In this example, if the user types `connpy myplugin start ` and presses Tab, it will suggest node names.
|
|
||||||
|
|
||||||
### Handling Unknown Arguments
|
|
||||||
|
|
||||||
Plugins can choose to accept and process unknown arguments that are **not explicitly defined** in the parser. To enable this behavior, the plugin must define the following hidden argument in its `Parser` class:
|
|
||||||
|
|
||||||
```
|
|
||||||
self.parser.add_argument(
|
|
||||||
"--unknown-args",
|
|
||||||
action="store_true",
|
|
||||||
default=True,
|
|
||||||
help=argparse.SUPPRESS
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Behavior:
|
|
||||||
|
|
||||||
- When this argument is present, Connpy will parse the known arguments and capture any extra (unknown) ones.
|
|
||||||
- These unknown arguments will be passed to the plugin as `args.unknown_args` inside the `Entrypoint`.
|
|
||||||
- If the user does not pass any unknown arguments, `args.unknown_args` will contain the default value (`True`, unless overridden).
|
|
||||||
|
|
||||||
#### Example:
|
|
||||||
|
|
||||||
If a plugin accepts unknown tcpdump flags like this:
|
|
||||||
|
|
||||||
```
|
|
||||||
connpy myplugin -nn -s0
|
|
||||||
```
|
|
||||||
|
|
||||||
And defines the hidden `--unknown-args` flag as shown above, then:
|
|
||||||
|
|
||||||
- `args.unknown_args` inside `Entrypoint.__init__()` will be: `['-nn', '-s0']`
|
|
||||||
|
|
||||||
> This allows the plugin to receive and process arguments intended for external tools (e.g., `tcpdump`) without argparse raising an error.
|
|
||||||
|
|
||||||
#### Note:
|
|
||||||
|
|
||||||
If a plugin does **not** define `--unknown-args`, any extra arguments passed will cause argparse to fail with an unrecognized arguments error.
|
|
||||||
|
|
||||||
### Script Verification
|
|
||||||
- The `verify_script` method in `plugins.py` is used to check the plugin script's compliance with these standards.
|
|
||||||
- Non-compliant scripts will be rejected to ensure consistency and proper functionality within the plugin system.
|
|
||||||
|
|
||||||
### Example Script
|
|
||||||
|
|
||||||
For a practical example of how to write a compatible plugin script, please refer to the following example:
|
|
||||||
|
|
||||||
[Example Plugin Script](https://github.com/fluzzi/awspy)
|
|
||||||
|
|
||||||
This script demonstrates the required structure and implementation details according to the plugin system's standards.
|
|
||||||
|
|
||||||
## Automation module usage
|
|
||||||
### Standalone module
|
|
||||||
```
|
|
||||||
import connpy
|
import connpy
|
||||||
router = connpy.node("uniqueName","ip/host", user="username", password="password")
|
router = connpy.node("uniqueName", "1.1.1.1", user="admin")
|
||||||
router.run(["term len 0","show run"])
|
router.run(["show ip int brief"])
|
||||||
print(router.output)
|
print(router.output)
|
||||||
hasip = router.test("show ip int brief","1.1.1.1")
|
|
||||||
if hasip:
|
|
||||||
print("Router has ip 1.1.1.1")
|
|
||||||
else:
|
|
||||||
print("router does not have ip 1.1.1.1")
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using manager configuration
|
### Parallel Tasks with Variables
|
||||||
```
|
```python
|
||||||
import connpy
|
|
||||||
conf = connpy.configfile()
|
|
||||||
device = conf.getitem("router@office")
|
|
||||||
router = connpy.node("unique name", **device, config=conf)
|
|
||||||
result = router.run("show ip int brief")
|
|
||||||
print(result)
|
|
||||||
```
|
|
||||||
### Running parallel tasks on multiple devices
|
|
||||||
```
|
|
||||||
import connpy
|
|
||||||
conf = connpy.configfile()
|
|
||||||
#You can get the nodes from the config from a folder and fitlering in it
|
|
||||||
nodes = conf.getitem("@office", ["router1", "router2", "router3"])
|
|
||||||
#You can also get each node individually:
|
|
||||||
nodes = {}
|
|
||||||
nodes["router1"] = conf.getitem("router1@office")
|
|
||||||
nodes["router2"] = conf.getitem("router2@office")
|
|
||||||
nodes["router10"] = conf.getitem("router10@datacenter")
|
|
||||||
#Also, you can create the nodes manually:
|
|
||||||
nodes = {}
|
|
||||||
nodes["router1"] = {"host": "1.1.1.1", "user": "user", "password": "password1"}
|
|
||||||
nodes["router2"] = {"host": "1.1.1.2", "user": "user", "password": "password2"}
|
|
||||||
nodes["router3"] = {"host": "1.1.1.2", "user": "user", "password": "password3"}
|
|
||||||
#Finally you run some tasks on the nodes
|
|
||||||
mynodes = connpy.nodes(nodes, config = conf)
|
|
||||||
result = mynodes.test(["show ip int br"], "1.1.1.2")
|
|
||||||
for i in result:
|
|
||||||
print("---" + i + "---")
|
|
||||||
print(result[i])
|
|
||||||
print()
|
|
||||||
# Or for one specific node
|
|
||||||
mynodes.router1.run(["term len 0". "show run"], folder = "/home/user/logs")
|
|
||||||
```
|
|
||||||
### Using variables
|
|
||||||
```
|
|
||||||
import connpy
|
import connpy
|
||||||
config = connpy.configfile()
|
config = connpy.configfile()
|
||||||
nodes = config.getitem("@office", ["router1", "router2", "router3"])
|
nodes = config.getitem("@office", ["router1", "router2"])
|
||||||
commands = []
|
|
||||||
commands.append("config t")
|
|
||||||
commands.append("interface lo {id}")
|
|
||||||
commands.append("ip add {ip} {mask}")
|
|
||||||
commands.append("end")
|
|
||||||
variables = {}
|
|
||||||
variables["router1@office"] = {"ip": "10.57.57.1"}
|
|
||||||
variables["router2@office"] = {"ip": "10.57.57.2"}
|
|
||||||
variables["router3@office"] = {"ip": "10.57.57.3"}
|
|
||||||
variables["__global__"] = {"id": "57"}
|
|
||||||
variables["__global__"]["mask"] = "255.255.255.255"
|
|
||||||
expected = "!"
|
|
||||||
routers = connpy.nodes(nodes, config=config)
|
routers = connpy.nodes(nodes, config=config)
|
||||||
routers.run(commands, variables)
|
|
||||||
routers.test("ping {ip}", expected, variables)
|
variables = {
|
||||||
for key in routers.result:
|
"router1@office": {"id": "1"},
|
||||||
print(key, ' ---> ', ("pass" if routers.result[key] else "fail"))
|
"__global__": {"mask": "255.255.255.0"}
|
||||||
|
}
|
||||||
|
routers.run(["interface lo{id}", "ip address 10.0.0.{id} {mask}"], variables)
|
||||||
```
|
```
|
||||||
### Using AI
|
|
||||||
The AI module uses a multi-agent architecture with an **Engineer** (fast execution) and an **Architect** (strategic reasoning). It supports any LLM provider through [litellm](https://github.com/BerriAI/litellm).
|
### AI Programmatic Use
|
||||||
```python
|
```python
|
||||||
import connpy
|
import connpy
|
||||||
conf = connpy.configfile()
|
myai = connpy.ai(connpy.configfile())
|
||||||
# Uses models and API keys from config, or override them:
|
response = myai.ask("What is the status of the BGP neighbors in the office?")
|
||||||
myai = connpy.ai(conf, engineer_model="gemini/gemini-2.5-flash", engineer_api_key="your-key")
|
|
||||||
result = myai.ask("go to router1 and show me the running configuration")
|
|
||||||
print(result["response"])
|
|
||||||
# Streaming is enabled by default for CLI, disable for programmatic use:
|
|
||||||
result = myai.ask("show interfaces on all routers", stream=False)
|
|
||||||
print(result["response"])
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### AI Plugin Tool Registration
|
---
|
||||||
Plugins can extend the AI system by registering custom tools via the `Preload` class:
|
*For detailed developer notes and plugin hooks documentation, see the [Documentation](https://fluzzi.github.io/connpy/).*
|
||||||
```python
|
|
||||||
def _register_my_tools(ai_instance):
|
|
||||||
tool_def = {
|
|
||||||
"type": "function",
|
|
||||||
"function": {
|
|
||||||
"name": "my_custom_tool",
|
|
||||||
"description": "Does something useful.",
|
|
||||||
"parameters": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {"query": {"type": "string"}},
|
|
||||||
"required": ["query"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ai_instance.register_ai_tool(
|
|
||||||
tool_definition=tool_def,
|
|
||||||
handler=my_handler_function,
|
|
||||||
target="engineer", # or "architect" or "both"
|
|
||||||
engineer_prompt="- My tool: does X.",
|
|
||||||
architect_prompt=" * My tool (my_custom_tool)."
|
|
||||||
)
|
|
||||||
|
|
||||||
class Preload:
|
|
||||||
def __init__(self, connapp):
|
|
||||||
connapp.ai.modify(_register_my_tools)
|
|
||||||
```
|
|
||||||
## gRPC Service Architecture
|
|
||||||
Connpy features a completely decoupled gRPC Client/Server architecture. You can run Connpy as a standalone background service and connect to it remotely via the CLI or other clients.
|
|
||||||
|
|
||||||
### 1. Start the Server
|
|
||||||
Start the gRPC service by running:
|
|
||||||
```bash
|
|
||||||
connpy api -s 50051
|
|
||||||
```
|
|
||||||
The server will handle all configurations, connections, AI sessions, and plugin execution locally on the machine it runs on.
|
|
||||||
|
|
||||||
### 2. Connect the Client
|
|
||||||
Configure your local CLI client to connect to the remote server:
|
|
||||||
```bash
|
|
||||||
connpy config --service-mode remote
|
|
||||||
connpy config --remote-host localhost:50051
|
|
||||||
```
|
|
||||||
Once configured, all commands (`connpy node`, `connpy list`, `connpy ai`, etc.) will execute transparently on the remote server via thin-client proxies. You can revert back to standalone execution at any time by running `connpy config --service-mode local`.
|
|
||||||
|
|
||||||
### Programmatic Access (gRPC & SOA)
|
|
||||||
If you wish to build your own application (Web, Desktop, or Scripts) using the Connpy backend, you can use the `ServiceProvider` to interact with either a local or remote service transparently.
|
|
||||||
|
|
||||||
```python
|
|
||||||
import connpy
|
|
||||||
from connpy.services.provider import ServiceProvider
|
|
||||||
|
|
||||||
# Initialize local config
|
|
||||||
config = connpy.configfile()
|
|
||||||
|
|
||||||
# Connect to the remote gRPC service
|
|
||||||
services = ServiceProvider(
|
|
||||||
config,
|
|
||||||
mode="remote",
|
|
||||||
remote_host="localhost:50051"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Use any service (the logic is identical to local mode)
|
|
||||||
nodes = services.nodes.list_nodes()
|
|
||||||
for name in nodes:
|
|
||||||
print(f"Found node: {name}")
|
|
||||||
|
|
||||||
# Run a command remotely via streaming
|
|
||||||
for chunk in services.execution.run_commands(nodes=["server1"], commands=["uptime"]):
|
|
||||||
print(chunk["output"], end="")
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+137
-431
@@ -1,476 +1,182 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
'''
|
'''
|
||||||
## Connection manager
|
<p align="center">
|
||||||
|
<img src="https://nginx.gederico.dynu.net/images/CONNPY-resized.png" alt="App Logo">
|
||||||
|
</p>
|
||||||
|
|
||||||
Connpy is a SSH, SFTP, Telnet, kubectl, Docker pod, and AWS SSM connection manager and automation module for Linux, Mac, and Docker.
|
|
||||||
|
|
||||||
### Features
|
# Connpy
|
||||||
- Manage connections using SSH, SFTP, Telnet, kubectl, Docker exec, and AWS SSM.
|
[](https://pypi.org/pypi/connpy/)
|
||||||
- Set contexts to manage specific nodes from specific contexts (work/home/clients/etc).
|
[](https://pypi.org/pypi/connpy/)
|
||||||
- You can generate profiles and reference them from nodes using @profilename so you don't
|
[](https://github.com/fluzzi/connpy/blob/main/LICENSE)
|
||||||
need to edit multiple nodes when changing passwords or other information.
|
[](https://pypi.org/pypi/connpy/)
|
||||||
- Nodes can be stored on @folder or @subfolder@folder to organize your devices. They can
|
|
||||||
be referenced using node@subfolder@folder or node@folder.
|
|
||||||
- If you have too many nodes, get a completion script using: conn config --completion.
|
|
||||||
Or use fzf by installing pyfzf and running conn config --fzf true.
|
|
||||||
- Create in bulk, copy, move, export, and import nodes for easy management.
|
|
||||||
- Run automation scripts on network devices.
|
|
||||||
- Use AI with a multi-agent system (Engineer/Architect) to help you manage your devices.
|
|
||||||
Supports any LLM provider via litellm (OpenAI, Anthropic, Google, etc.).
|
|
||||||
- Add plugins with your own scripts, and execute them remotely.
|
|
||||||
- Fully decoupled gRPC Client/Server architecture.
|
|
||||||
- Unified UI with syntax highlighting and theming.
|
|
||||||
- Much more!
|
|
||||||
|
|
||||||
### Usage
|
**Connpy** is a powerful Connection Manager and Network Automation Platform for Linux, Mac, and Docker. It provides a unified interface for **SSH, SFTP, Telnet, kubectl, Docker pods, and AWS SSM**.
|
||||||
|
|
||||||
|
The v6 release introduces the **AI Copilot**, an interactive terminal assistant that understands your network context and helps you manage your infrastructure more intelligently.
|
||||||
|
|
||||||
|
|
||||||
|
## 🤖 AI Copilot (New in v6)
|
||||||
|
The AI Copilot is deeply integrated into your terminal workflow:
|
||||||
|
- **Terminal Context Awareness**: The Copilot can "see" your screen output, helping you diagnose errors or analyze command results in real-time.
|
||||||
|
- **Hybrid Multi-Agent System**: Automatically escalates complex tasks between the **Network Engineer** (execution) and the **Network Architect** (strategy).
|
||||||
|
- **MCP Integration**: Dynamically load tools from external providers (6WIND, AWS, etc.) via the Model Context Protocol.
|
||||||
|
- **Interactive Chat**: Launch with `conn ai` for a collaborative troubleshooting session.
|
||||||
|
|
||||||
|
|
||||||
|
## Core Features
|
||||||
|
- **Multi-Protocol**: Native support for SSH, SFTP, Telnet, kubectl, Docker exec, and AWS SSM.
|
||||||
|
- **Context Management**: Set regex-based contexts to manage specific nodes across different environments (work, home, clients).
|
||||||
|
- **Advanced Inventory**:
|
||||||
|
- Organize nodes in folders (`@folder`) and subfolders (`@subfolder@folder`).
|
||||||
|
- Use Global Profiles (`@profilename`) to manage shared credentials easily.
|
||||||
|
- Bulk creation, copying, moving, and export/import of nodes.
|
||||||
|
- **Modern UI**: High-performance terminal experience with `prompt-toolkit`, including:
|
||||||
|
- Fuzzy search integration with `fzf`.
|
||||||
|
- Advanced tab completion.
|
||||||
|
- Syntax highlighting and customizable themes.
|
||||||
|
- **Automation Engine**: Run parallel tasks and playbooks on multiple devices with variable support.
|
||||||
|
- **Plugin System**: Build and execute custom Python scripts locally or on a remote gRPC server.
|
||||||
|
- **gRPC Architecture**: Fully decoupled Client/Server model for distributed management.
|
||||||
|
- **Privacy & Sync**: Local-first encrypted storage (RSA/OAEP) with optional Google Drive backup.
|
||||||
|
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install connpy
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Run it in Windows/Linux using Docker
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/fluzzi/connpy
|
||||||
|
cd connpy
|
||||||
|
docker compose build
|
||||||
|
|
||||||
|
# Run it like a native app (completely silent)
|
||||||
|
docker compose 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 run --rm --remove-orphans connpy-app'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔒 Privacy & Integration
|
||||||
|
|
||||||
|
### Privacy Policy
|
||||||
|
Connpy is committed to protecting your privacy:
|
||||||
|
- **Local Storage**: All server addresses, usernames, and passwords are encrypted and stored **only** on your machine. No data is transmitted to our servers.
|
||||||
|
- **Data Access**: Data is used solely for managing and automating your connections.
|
||||||
|
|
||||||
|
### Google Integration
|
||||||
|
Used strictly for backup:
|
||||||
|
- **Backup**: Sync your encrypted configuration with your Google Drive account.
|
||||||
|
- **Scoped Access**: Connpy only accesses its own backup files.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
usage: conn [-h] [--add | --del | --mod | --show | --debug] [node|folder] [--sftp]
|
usage: conn [-h] [--add | --del | --mod | --show | --debug] [node|folder] [--sftp]
|
||||||
conn {profile,move,mv,copy,cp,list,ls,bulk,export,import,ai,run,api,plugin,config,sync,context} ...
|
conn {profile,move,copy,list,bulk,export,import,ai,run,api,plugin,config,sync,context} ...
|
||||||
|
|
||||||
positional arguments:
|
|
||||||
node|folder node[@subfolder][@folder]
|
|
||||||
Connect to specific node or show all matching nodes
|
|
||||||
[@subfolder][@folder]
|
|
||||||
Show all available connections globally or in specified path
|
|
||||||
|
|
||||||
options:
|
|
||||||
-h, --help show this help message and exit
|
|
||||||
-v, --version Show version
|
|
||||||
-a, --add Add new node[@subfolder][@folder] or [@subfolder]@folder
|
|
||||||
-r, --del, --rm Delete node[@subfolder][@folder] or [@subfolder]@folder
|
|
||||||
-e, --mod, --edit Modify node[@subfolder][@folder]
|
|
||||||
-s, --show Show node[@subfolder][@folder]
|
|
||||||
-d, --debug Display all conections steps
|
|
||||||
-t, --sftp Connects using sftp instead of ssh
|
|
||||||
--service-mode Set the backend service mode (local or remote)
|
|
||||||
--remote Connect to a remote connpy service via gRPC
|
|
||||||
--theme UI Output theme (dark, light, or path)
|
|
||||||
|
|
||||||
Commands:
|
|
||||||
profile Manage profiles
|
|
||||||
move(mv) Move node
|
|
||||||
copy(cp) Copy node
|
|
||||||
list(ls) List profiles, nodes or folders
|
|
||||||
bulk Add nodes in bulk
|
|
||||||
export Export connection folder to Yaml file
|
|
||||||
import Import connection folder to config from Yaml file
|
|
||||||
ai Make request to an AI
|
|
||||||
run Run scripts or commands on nodes
|
|
||||||
api Start and stop connpy api
|
|
||||||
plugin Manage plugins
|
|
||||||
config Manage app config
|
|
||||||
sync Sync config with Google
|
|
||||||
context Manage contexts with regex matching
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Manage profiles
|
### Basic Examples:
|
||||||
```
|
```bash
|
||||||
usage: conn profile [-h] (--add | --del | --mod | --show) profile
|
# Add a folder and subfolder
|
||||||
|
|
||||||
positional arguments:
|
|
||||||
profile Name of profile to manage
|
|
||||||
|
|
||||||
options:
|
|
||||||
-h, --help show this help message and exit
|
|
||||||
-a, --add Add new profile
|
|
||||||
-r, --del, --rm Delete profile
|
|
||||||
-e, --mod, --edit Modify profile
|
|
||||||
-s, --show Show profile
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
```
|
|
||||||
#Add new profile
|
|
||||||
conn profile --add office-user
|
|
||||||
#Add new folder
|
|
||||||
conn --add @office
|
conn --add @office
|
||||||
#Add new subfolder
|
|
||||||
conn --add @datacenter@office
|
conn --add @datacenter@office
|
||||||
#Add node to subfolder
|
|
||||||
conn --add server@datacenter@office
|
# Add a node with a profile
|
||||||
#Add node to folder
|
conn --add server1@datacenter@office --profile @myuser
|
||||||
conn --add pc@office
|
|
||||||
#Show node information
|
# Connect to a node (fuzzy match)
|
||||||
conn --show server@datacenter@office
|
conn server1
|
||||||
#Connect to nodes
|
|
||||||
conn pc@office
|
# Start the AI Copilot
|
||||||
conn server
|
conn ai
|
||||||
#Create and set new context
|
|
||||||
conn context -a office .*@office
|
# Run a command on all nodes in a folder
|
||||||
conn context --set office
|
conn run @office "uptime"
|
||||||
#Run a command in a node
|
|
||||||
conn run server ls -la
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Plugin Requirements for Connpy
|
## Plugin Requirements for Connpy
|
||||||
|
|
||||||
### Remote Plugin Execution
|
### Remote Plugin Execution
|
||||||
When Connpy operates in remote mode, plugins are executed **transparently on the server**:
|
When Connpy operates in remote mode, plugins are executed **transparently on the server**:
|
||||||
- The client automatically downloads the plugin source code (`Parser` class context) to generate the local `argparse` structure and provide autocompletion.
|
- The client automatically downloads the plugin source code (`Parser` class context) to generate the local `argparse` structure and provide autocompletion.
|
||||||
- The execution phase (`Entrypoint` class) is redirected via gRPC streams to execute in the server's memory, ensuring the plugin runs securely against the server's inventory without passing sensitive data to the client.
|
- The execution phase (`Entrypoint` class) is redirected via gRPC streams to execute in the server's memory.
|
||||||
- You can manage remote plugins using the `--remote` flag (e.g. `connpy plugin --add myplugin script.py --remote`).
|
- You can manage remote plugins using the `--remote` flag.
|
||||||
|
|
||||||
### General Structure
|
### General Structure
|
||||||
- The plugin script must be a Python file.
|
- The plugin script must define specific classes:
|
||||||
- Only the following top-level elements are allowed in the plugin script:
|
1. **Class `Parser`**: Handles `argparse.ArgumentParser` initialization.
|
||||||
- Class definitions
|
2. **Class `Entrypoint`**: Main execution logic (receives `args`, `parser`, and `connapp`).
|
||||||
- Function definitions
|
3. **Class `Preload`**: (Optional) For modifying core app behavior or registering hooks.
|
||||||
- Import statements
|
|
||||||
- The `if __name__ == "__main__":` block for standalone execution
|
|
||||||
- Pass statements
|
|
||||||
|
|
||||||
### Specific Class Requirements
|
|
||||||
- The plugin script must define specific classes with particular attributes and methods. Each class serves a distinct role within the plugin's architecture:
|
|
||||||
1. **Class `Parser`**:
|
|
||||||
- **Purpose**: Handles parsing of command-line arguments.
|
|
||||||
- **Requirements**:
|
|
||||||
- Must contain only one method: `__init__`.
|
|
||||||
- The `__init__` method must initialize at least one attribute:
|
|
||||||
- `self.parser`: An instance of `argparse.ArgumentParser`.
|
|
||||||
2. **Class `Entrypoint`**:
|
|
||||||
- **Purpose**: Acts as the entry point for plugin execution, utilizing parsed arguments and integrating with the main application.
|
|
||||||
- **Requirements**:
|
|
||||||
- Must have an `__init__` method that accepts exactly three parameters besides `self`:
|
|
||||||
- `args`: Arguments passed to the plugin.
|
|
||||||
- The parser instance (typically `self.parser` from the `Parser` class).
|
|
||||||
- The Connapp instance to interact with the Connpy app.
|
|
||||||
3. **Class `Preload`**:
|
|
||||||
- **Purpose**: Performs any necessary preliminary setup or configuration independent of the main parsing and entry logic.
|
|
||||||
- **Requirements**:
|
|
||||||
- Contains at least an `__init__` method that accepts parameter connapp besides `self`.
|
|
||||||
|
|
||||||
### Class Dependencies and Combinations
|
|
||||||
- **Dependencies**:
|
|
||||||
- `Parser` and `Entrypoint` are interdependent and must both be present if one is included.
|
|
||||||
- `Preload` is independent and may exist alone or alongside the other classes.
|
|
||||||
- **Valid Combinations**:
|
|
||||||
- `Parser` and `Entrypoint` together.
|
|
||||||
- `Preload` alone.
|
|
||||||
- All three classes (`Parser`, `Entrypoint`, `Preload`).
|
|
||||||
|
|
||||||
### Preload Modifications and Hooks
|
### Preload Modifications and Hooks
|
||||||
|
You can customize the behavior of core classes using hooks:
|
||||||
In the `Preload` class of the plugin system, you have the ability to customize the behavior of existing classes and methods within the application through a robust hooking system. This documentation explains how to use the `modify`, `register_pre_hook`, and `register_post_hook` methods to tailor plugin functionality to your needs.
|
- **`modify(method)`**: Alter class instances (e.g., `connapp.config`, `connapp.ai`).
|
||||||
|
- **`register_pre_hook(method)`**: Logic to run before a method execution.
|
||||||
#### Modifying Classes with `modify`
|
- **`register_post_hook(method)`**: Logic to run after a method execution.
|
||||||
The `modify` method allows you to alter instances of a class at the time they are created or after their creation. This is particularly useful for setting or modifying configuration settings, altering default behaviors, or adding new functionalities to existing classes without changing the original class definitions.
|
|
||||||
|
|
||||||
- **Usage**: Modify a class to include additional configurations or changes
|
|
||||||
- **Modify Method Signature**:
|
|
||||||
- `modify(modification_method)`: A function that is invoked with an instance of the class as its argument. This function should perform any modifications directly on this instance.
|
|
||||||
- **Modification Method Signature**:
|
|
||||||
- **Arguments**:
|
|
||||||
- `cls`: This function accepts a single argument, the class instance, which it then modifies.
|
|
||||||
- **Modifiable Classes**:
|
|
||||||
- `connapp.config`
|
|
||||||
- `connapp.node`
|
|
||||||
- `connapp.nodes`
|
|
||||||
- `connapp.ai`
|
|
||||||
- ```python
|
|
||||||
def modify_config(cls):
|
|
||||||
# Example modification: adding a new attribute or modifying an existing one
|
|
||||||
cls.new_attribute = 'New Value'
|
|
||||||
|
|
||||||
class Preload:
|
|
||||||
def __init__(self, connapp):
|
|
||||||
# Applying modification to the config class instance
|
|
||||||
connapp.config.modify(modify_config)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Implementing Method Hooks
|
|
||||||
There are 2 methods that allows you to define custom logic to be executed before (`register_pre_hook`) or after (`register_post_hook`) the main logic of a method. This is particularly useful for logging, auditing, preprocessing inputs, postprocessing outputs or adding functionalities.
|
|
||||||
|
|
||||||
- **Usage**: Register hooks to methods to execute additional logic before or after the main method execution.
|
|
||||||
- **Registration Methods Signature**:
|
|
||||||
- `register_pre_hook(pre_hook_method)`: A function that is invoked before the main method is executed. This function should do preprocessing of the arguments.
|
|
||||||
- `register_post_hook(post_hook_method)`: A function that is invoked after the main method is executed. This function should do postprocessing of the outputs.
|
|
||||||
- **Method Signatures for Pre-Hooks**
|
|
||||||
- `pre_hook_method(*args, **kwargs)`
|
|
||||||
- **Arguments**:
|
|
||||||
- `*args`, `**kwargs`: The arguments and keyword arguments that will be passed to the method being hooked. The pre-hook function has the opportunity to inspect and modify these arguments before they are passed to the main method.
|
|
||||||
- **Return**:
|
|
||||||
- Must return a tuple `(args, kwargs)`, which will be used as the new arguments for the main method. If the original arguments are not modified, the function should return them as received.
|
|
||||||
- **Method Signatures for Post-Hooks**:
|
|
||||||
- `post_hook_method(*args, **kwargs)`
|
|
||||||
- **Arguments**:
|
|
||||||
- `*args`, `**kwargs`: The arguments and keyword arguments that were passed to the main method.
|
|
||||||
- `kwargs["result"]`: The value returned by the main method. This allows the post-hook to inspect and even alter the result before it is returned to the original caller.
|
|
||||||
- **Return**:
|
|
||||||
- Can return a modified result, which will replace the original result of the main method, or simply return `kwargs["result"]` to return the original method result.
|
|
||||||
- ```python
|
|
||||||
def pre_processing_hook(*args, **kwargs):
|
|
||||||
print("Pre-processing logic here")
|
|
||||||
# Modify arguments or perform any checks
|
|
||||||
return args, kwargs # Return modified or unmodified args and kwargs
|
|
||||||
|
|
||||||
def post_processing_hook(*args, **kwargs):
|
|
||||||
print("Post-processing logic here")
|
|
||||||
# Modify the result or perform any final logging or cleanup
|
|
||||||
return kwargs["result"] # Return the modified or unmodified result
|
|
||||||
|
|
||||||
class Preload:
|
|
||||||
def __init__(self, connapp):
|
|
||||||
# Registering a pre-hook
|
|
||||||
connapp.ai.some_method.register_pre_hook(pre_processing_hook)
|
|
||||||
|
|
||||||
# Registering a post-hook
|
|
||||||
connapp.node.another_method.register_post_hook(post_processing_hook)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Executable Block
|
|
||||||
- The plugin script can include an executable block:
|
|
||||||
- `if __name__ == "__main__":`
|
|
||||||
- This block allows the plugin to be run as a standalone script for testing or independent use.
|
|
||||||
|
|
||||||
### Command Completion Support
|
### Command Completion Support
|
||||||
|
Plugins can provide intelligent tab completion:
|
||||||
|
1. **Tree-based Completion (Recommended)**: Define `_connpy_tree(info)` returning a navigation dictionary.
|
||||||
|
2. **Legacy Completion**: Define `_connpy_completion(wordsnumber, words, info)`.
|
||||||
|
|
||||||
Plugins can provide intelligent **tab completion** by defining autocompletion logic. There are two supported methods, with the tree-based approach being the most modern and recommended.
|
---
|
||||||
|
|
||||||
#### 1. Tree-based Completion (Recommended)
|
## ⚙️ gRPC Service Architecture
|
||||||
|
Connpy can operate in a decoupled mode:
|
||||||
Define a function called `_connpy_tree` that returns a declarative navigation tree. This method is highly efficient, supports complex state loops, and is very simple to implement for most use cases.
|
1. **Start the API (Server)**: `conn api -s 50051`
|
||||||
|
2. **Configure the Client**:
|
||||||
```python
|
|
||||||
def _connpy_tree(info=None):
|
|
||||||
nodes = info.get("nodes", [])
|
|
||||||
return {
|
|
||||||
"__exclude_used__": True, # Filter out words already typed
|
|
||||||
"__extra__": nodes, # Suggest nodes at this level
|
|
||||||
"--format": ["json", "yaml", "table"], # Fixed suggestions
|
|
||||||
"*": { # Wildcard matches any positional word
|
|
||||||
"interface1": None,
|
|
||||||
"interface2": None,
|
|
||||||
"--verbose": None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Keys**: Literal completions (exact matches).
|
|
||||||
- **`*` Key**: A wildcard that matches any positional word typed by the user.
|
|
||||||
- **`__extra__`**: A list or a callable `(words) -> list` that adds dynamic suggestions.
|
|
||||||
- **`__exclude_used__`**: (Boolean) If True, automatically filters out words already present in the command line.
|
|
||||||
|
|
||||||
#### 2. Legacy Function-based Completion
|
|
||||||
|
|
||||||
For backward compatibility or highly custom logic, you can define `_connpy_completion`.
|
|
||||||
|
|
||||||
```python
|
|
||||||
def _connpy_completion(wordsnumber, words, info=None):
|
|
||||||
if wordsnumber == 3:
|
|
||||||
return ["--help", "--verbose", "start", "stop"]
|
|
||||||
|
|
||||||
elif wordsnumber == 4 and words[2] == "start":
|
|
||||||
return info["nodes"] # Suggest node names
|
|
||||||
|
|
||||||
return []
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Description |
|
|
||||||
|----------------|-------------|
|
|
||||||
| `wordsnumber` | Integer indicating the total number of words on the command line. For plugins, this typically starts at 3. |
|
|
||||||
| `words` | A list of tokens (words) already typed. `words[0]` is always the name of the plugin. |
|
|
||||||
| `info` | A dictionary of structured context data (`nodes`, `folders`, `profiles`, `config`). |
|
|
||||||
|
|
||||||
> In this example, if the user types `connpy myplugin start ` and presses Tab, it will suggest node names.
|
|
||||||
|
|
||||||
### Handling Unknown Arguments
|
|
||||||
|
|
||||||
Plugins can choose to accept and process unknown arguments that are **not explicitly defined** in the parser. To enable this behavior, the plugin must define the following hidden argument in its `Parser` class:
|
|
||||||
|
|
||||||
```
|
|
||||||
self.parser.add_argument(
|
|
||||||
"--unknown-args",
|
|
||||||
action="store_true",
|
|
||||||
default=True,
|
|
||||||
help=argparse.SUPPRESS
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Behavior:
|
|
||||||
|
|
||||||
- When this argument is present, Connpy will parse the known arguments and capture any extra (unknown) ones.
|
|
||||||
- These unknown arguments will be passed to the plugin as `args.unknown_args` inside the `Entrypoint`.
|
|
||||||
- If the user does not pass any unknown arguments, `args.unknown_args` will contain the default value (`True`, unless overridden).
|
|
||||||
|
|
||||||
#### Example:
|
|
||||||
|
|
||||||
If a plugin accepts unknown tcpdump flags like this:
|
|
||||||
|
|
||||||
```
|
|
||||||
connpy myplugin -nn -s0
|
|
||||||
```
|
|
||||||
|
|
||||||
And defines the hidden `--unknown-args` flag as shown above, then:
|
|
||||||
|
|
||||||
- `args.unknown_args` inside `Entrypoint.__init__()` will be: `['-nn', '-s0']`
|
|
||||||
|
|
||||||
> This allows the plugin to receive and process arguments intended for external tools (e.g., `tcpdump`) without argparse raising an error.
|
|
||||||
|
|
||||||
#### Note:
|
|
||||||
|
|
||||||
If a plugin does **not** define `--unknown-args`, any extra arguments passed will cause argparse to fail with an unrecognized arguments error.
|
|
||||||
|
|
||||||
### Script Verification
|
|
||||||
- The `verify_script` method in `plugins.py` is used to check the plugin script's compliance with these standards.
|
|
||||||
- Non-compliant scripts will be rejected to ensure consistency and proper functionality within the plugin system.
|
|
||||||
-
|
|
||||||
### Example Script
|
|
||||||
|
|
||||||
For a practical example of how to write a compatible plugin script, please refer to the following example:
|
|
||||||
|
|
||||||
[Example Plugin Script](https://github.com/fluzzi/awspy)
|
|
||||||
|
|
||||||
This script demonstrates the required structure and implementation details according to the plugin system's standards.
|
|
||||||
|
|
||||||
## gRPC Service Architecture
|
|
||||||
Connpy features a completely decoupled gRPC Client/Server architecture. You can run Connpy as a standalone background service and connect to it remotely via the CLI or other clients.
|
|
||||||
|
|
||||||
### 1. Start the Server
|
|
||||||
Start the gRPC service by running:
|
|
||||||
```bash
|
```bash
|
||||||
connpy api -s 50051
|
conn config --service-mode remote
|
||||||
|
conn config --remote-host localhost:50051
|
||||||
```
|
```
|
||||||
The server will handle all configurations, connections, AI sessions, and plugin execution locally on the machine it runs on.
|
All inventory management and execution will now happen on the server.
|
||||||
|
|
||||||
### 2. Connect the Client
|
---
|
||||||
Configure your local CLI client to connect to the remote server:
|
|
||||||
```bash
|
|
||||||
connpy config --service-mode remote
|
|
||||||
connpy config --remote-host localhost:50051
|
|
||||||
```
|
|
||||||
Once configured, all commands (`connpy node`, `connpy list`, `connpy ai`, etc.) will execute transparently on the remote server via thin-client proxies. You can revert back to standalone execution at any time by running `connpy config --service-mode local`.
|
|
||||||
|
|
||||||
### Programmatic Access (gRPC & SOA)
|
## 🐍 Automation Module (API)
|
||||||
Developers can build their own applications using the Connpy backend by utilizing the `ServiceProvider`:
|
You can use `connpy` as a Python library for your own scripts.
|
||||||
|
|
||||||
|
### Basic Execution
|
||||||
```python
|
```python
|
||||||
from connpy.services.provider import ServiceProvider
|
|
||||||
services = ServiceProvider(config, mode="remote", remote_host="localhost:50051")
|
|
||||||
nodes = services.nodes.list_nodes()
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Automation module
|
|
||||||
The automation module
|
|
||||||
### Standalone module
|
|
||||||
```
|
|
||||||
import connpy
|
import connpy
|
||||||
router = connpy.node("uniqueName","ip/host", user="user", password="pass")
|
router = connpy.node("uniqueName", "1.1.1.1", user="admin")
|
||||||
router.run(["term len 0","show run"])
|
router.run(["show ip int brief"])
|
||||||
print(router.output)
|
print(router.output)
|
||||||
hasip = router.test("show ip int brief","1.1.1.1")
|
|
||||||
if hasip:
|
|
||||||
print("Router has ip 1.1.1.1")
|
|
||||||
else:
|
|
||||||
print("router does not have ip 1.1.1.1")
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using manager configuration
|
### Parallel Tasks with Variables
|
||||||
```
|
```python
|
||||||
import connpy
|
|
||||||
conf = connpy.configfile()
|
|
||||||
device = conf.getitem("server@office")
|
|
||||||
server = connpy.node("unique name", **device, config=conf)
|
|
||||||
result = server.run(["cd /", "ls -la"])
|
|
||||||
print(result)
|
|
||||||
```
|
|
||||||
### Running parallel tasks
|
|
||||||
```
|
|
||||||
import connpy
|
|
||||||
conf = connpy.configfile()
|
|
||||||
#You can get the nodes from the config from a folder and fitlering in it
|
|
||||||
nodes = conf.getitem("@office", ["router1", "router2", "router3"])
|
|
||||||
#You can also get each node individually:
|
|
||||||
nodes = {}
|
|
||||||
nodes["router1"] = conf.getitem("router1@office")
|
|
||||||
nodes["router2"] = conf.getitem("router2@office")
|
|
||||||
nodes["router10"] = conf.getitem("router10@datacenter")
|
|
||||||
#Also, you can create the nodes manually:
|
|
||||||
nodes = {}
|
|
||||||
nodes["router1"] = {"host": "1.1.1.1", "user": "user", "password": "pass1"}
|
|
||||||
nodes["router2"] = {"host": "1.1.1.2", "user": "user", "password": "pass2"}
|
|
||||||
nodes["router3"] = {"host": "1.1.1.2", "user": "user", "password": "pass3"}
|
|
||||||
#Finally you run some tasks on the nodes
|
|
||||||
mynodes = connpy.nodes(nodes, config = conf)
|
|
||||||
result = mynodes.test(["show ip int br"], "1.1.1.2")
|
|
||||||
for i in result:
|
|
||||||
print("---" + i + "---")
|
|
||||||
print(result[i])
|
|
||||||
print()
|
|
||||||
# Or for one specific node
|
|
||||||
mynodes.router1.run(["term len 0". "show run"], folder = "/home/user/logs")
|
|
||||||
```
|
|
||||||
### Using variables
|
|
||||||
```
|
|
||||||
import connpy
|
import connpy
|
||||||
config = connpy.configfile()
|
config = connpy.configfile()
|
||||||
nodes = config.getitem("@office", ["router1", "router2", "router3"])
|
nodes = config.getitem("@office", ["router1", "router2"])
|
||||||
commands = []
|
|
||||||
commands.append("config t")
|
|
||||||
commands.append("interface lo {id}")
|
|
||||||
commands.append("ip add {ip} {mask}")
|
|
||||||
commands.append("end")
|
|
||||||
variables = {}
|
|
||||||
variables["router1@office"] = {"ip": "10.57.57.1"}
|
|
||||||
variables["router2@office"] = {"ip": "10.57.57.2"}
|
|
||||||
variables["router3@office"] = {"ip": "10.57.57.3"}
|
|
||||||
variables["__global__"] = {"id": "57"}
|
|
||||||
variables["__global__"]["mask"] = "255.255.255.255"
|
|
||||||
expected = "!"
|
|
||||||
routers = connpy.nodes(nodes, config=config)
|
routers = connpy.nodes(nodes, config=config)
|
||||||
routers.run(commands, variables)
|
|
||||||
routers.test("ping {ip}", expected, variables)
|
variables = {
|
||||||
for key in routers.result:
|
"router1@office": {"id": "1"},
|
||||||
print(key, ' ---> ', ("pass" if routers.result[key] else "fail"))
|
"__global__": {"mask": "255.255.255.0"}
|
||||||
```
|
}
|
||||||
### Using AI
|
routers.run(["interface lo{id}", "ip address 10.0.0.{id} {mask}"], variables)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### AI Programmatic Use
|
||||||
|
```python
|
||||||
import connpy
|
import connpy
|
||||||
conf = connpy.configfile()
|
myai = connpy.ai(connpy.configfile())
|
||||||
# Uses models and API keys from config, or override them:
|
response = myai.ask("What is the status of the BGP neighbors in the office?")
|
||||||
myai = connpy.ai(conf, engineer_model="gemini/gemini-2.5-flash", engineer_api_key="your-key")
|
|
||||||
result = myai.ask("go to router1 and show me the running configuration")
|
|
||||||
print(result["response"])
|
|
||||||
# Streaming is enabled by default for CLI, disable for programmatic use:
|
|
||||||
result = myai.ask("show interfaces on all routers", stream=False)
|
|
||||||
print(result["response"])
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### AI Plugin Tool Registration
|
---
|
||||||
Plugins can register custom tools with the AI system using `register_ai_tool()` in their `Preload` class:
|
*For detailed developer notes and plugin hooks documentation, see the [Documentation](https://fluzzi.github.io/connpy/).*
|
||||||
```
|
|
||||||
def _register_my_tools(ai_instance):
|
|
||||||
tool_def = {
|
|
||||||
"type": "function",
|
|
||||||
"function": {
|
|
||||||
"name": "my_custom_tool",
|
|
||||||
"description": "Does something useful.",
|
|
||||||
"parameters": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {"query": {"type": "string"}},
|
|
||||||
"required": ["query"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ai_instance.register_ai_tool(
|
|
||||||
tool_definition=tool_def,
|
|
||||||
handler=my_handler_function,
|
|
||||||
target="engineer", # or "architect" or "both"
|
|
||||||
engineer_prompt="- My tool: does X.",
|
|
||||||
architect_prompt=" * My tool (my_custom_tool)."
|
|
||||||
)
|
|
||||||
|
|
||||||
class Preload:
|
|
||||||
def __init__(self, connapp):
|
|
||||||
connapp.ai.modify(_register_my_tools)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Developer Notes (SOA Architecture)
|
|
||||||
As of version 2.0, Connpy has migrated to a **Service-Oriented Architecture (SOA)**:
|
|
||||||
- **`connpy/cli/`**: Contains all CLI handlers. These are responsible for argument parsing, user interaction (via `inquirer`), and visual output (via `printer`).
|
|
||||||
- **`connpy/services/`**: Contains pure logic services (Node, Profile, Execution, etc.).
|
|
||||||
- **Zero-Print Policy**: Services must never use `print()`. All output must be returned as data structures or generators to the caller (CLI handlers).
|
|
||||||
- **ServiceProvider**: Access services via `connapp.services`. This allows transparent switching between local and remote (gRPC) backends without modifying CLI logic.
|
|
||||||
'''
|
'''
|
||||||
from .core import node,nodes
|
from .core import node,nodes
|
||||||
from .configfile import configfile
|
from .configfile import configfile
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
__version__ = "5.1b6"
|
__version__ = "6.0.0b11"
|
||||||
|
|||||||
+433
-38
@@ -3,8 +3,11 @@ import sys
|
|||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import datetime
|
import datetime
|
||||||
|
import threading
|
||||||
|
import asyncio
|
||||||
from textwrap import dedent
|
from textwrap import dedent
|
||||||
from .core import nodes
|
from .core import nodes
|
||||||
|
from .mcp_client import MCPClientManager
|
||||||
|
|
||||||
_litellm_initialized = False
|
_litellm_initialized = False
|
||||||
|
|
||||||
@@ -37,6 +40,61 @@ from rich.rule import Rule
|
|||||||
console = printer.console
|
console = printer.console
|
||||||
|
|
||||||
|
|
||||||
|
_ai_loop = None
|
||||||
|
_ai_thread = None
|
||||||
|
_ai_lock = threading.Lock()
|
||||||
|
|
||||||
|
def _get_ai_loop():
|
||||||
|
global _ai_loop, _ai_thread
|
||||||
|
with _ai_lock:
|
||||||
|
if _ai_loop is None:
|
||||||
|
_ai_loop = asyncio.new_event_loop()
|
||||||
|
_ai_thread = threading.Thread(target=_ai_loop.run_forever, name="ConnpyAILoop", daemon=True)
|
||||||
|
_ai_thread.start()
|
||||||
|
return _ai_loop
|
||||||
|
|
||||||
|
def run_ai_async(coro):
|
||||||
|
"""Run a coroutine in the dedicated AI background loop."""
|
||||||
|
loop = _get_ai_loop()
|
||||||
|
return asyncio.run_coroutine_threadsafe(coro, loop)
|
||||||
|
|
||||||
|
|
||||||
|
def cleanup():
|
||||||
|
"""Safely close any global litellm sessions in the dedicated AI loop."""
|
||||||
|
global _ai_loop
|
||||||
|
if _ai_loop:
|
||||||
|
try:
|
||||||
|
future = asyncio.run_coroutine_threadsafe(_async_cleanup(), _ai_loop)
|
||||||
|
future.result(timeout=5)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def _async_cleanup():
|
||||||
|
"""Internal async cleanup for litellm sessions."""
|
||||||
|
try:
|
||||||
|
import litellm
|
||||||
|
# 1. Close synchronous session
|
||||||
|
if hasattr(litellm, "client_session") and litellm.client_session:
|
||||||
|
try:
|
||||||
|
if hasattr(litellm.client_session, "close"):
|
||||||
|
res = litellm.client_session.close()
|
||||||
|
if asyncio.iscoroutine(res): await res
|
||||||
|
except: pass
|
||||||
|
litellm.client_session = None
|
||||||
|
|
||||||
|
# 2. Close asynchronous session
|
||||||
|
if hasattr(litellm, "aclient_session") and litellm.aclient_session:
|
||||||
|
try:
|
||||||
|
session = litellm.aclient_session
|
||||||
|
litellm.aclient_session = None
|
||||||
|
if hasattr(session, "close"):
|
||||||
|
await session.close()
|
||||||
|
except: pass
|
||||||
|
except ImportError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
@ClassHook
|
@ClassHook
|
||||||
class ai:
|
class ai:
|
||||||
"""Hybrid Multi-Agent System: Selective Escalation with Role Persistence."""
|
"""Hybrid Multi-Agent System: Selective Escalation with Role Persistence."""
|
||||||
@@ -60,7 +118,7 @@ class ai:
|
|||||||
aiconfig = self.config.config.get("ai", {})
|
aiconfig = self.config.config.get("ai", {})
|
||||||
|
|
||||||
# Modelos (Prioridad: Argumento -> Config -> Default)
|
# Modelos (Prioridad: Argumento -> Config -> Default)
|
||||||
self.engineer_model = engineer_model or aiconfig.get("engineer_model") or "gemini/gemini-3.1-flash-lite-preview"
|
self.engineer_model = engineer_model or aiconfig.get("engineer_model") or "gemini/gemini-3.1-flash-lite"
|
||||||
self.architect_model = architect_model or aiconfig.get("architect_model") or "anthropic/claude-sonnet-4-6"
|
self.architect_model = architect_model or aiconfig.get("architect_model") or "anthropic/claude-sonnet-4-6"
|
||||||
|
|
||||||
# API Keys (Prioridad: Argumento -> Config)
|
# API Keys (Prioridad: Argumento -> Config)
|
||||||
@@ -87,6 +145,9 @@ class ai:
|
|||||||
self.engineer_prompt_extensions = [] # Extra text for engineer prompt
|
self.engineer_prompt_extensions = [] # Extra text for engineer prompt
|
||||||
self.architect_prompt_extensions = [] # Extra text for architect prompt
|
self.architect_prompt_extensions = [] # Extra text for architect prompt
|
||||||
|
|
||||||
|
# MCP Manager
|
||||||
|
self.mcp_manager = MCPClientManager(self.config)
|
||||||
|
|
||||||
# Long-term memory
|
# Long-term memory
|
||||||
self.memory_path = os.path.join(self.config.defaultdir, "ai_memory.md")
|
self.memory_path = os.path.join(self.config.defaultdir, "ai_memory.md")
|
||||||
self.long_term_memory = ""
|
self.long_term_memory = ""
|
||||||
@@ -144,6 +205,7 @@ class ai:
|
|||||||
- COMPLETE MISSIONS: Execute ALL steps of a mission before reporting back.
|
- 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.
|
- DIAGRAM: Use ASCII art or Unicode box-drawing characters directly in your responses to visualize topologies or paths when helpful.
|
||||||
- EVIDENCE: Include 'Key Snippets' from tool outputs. Be token-efficient.
|
- EVIDENCE: Include 'Key Snippets' from tool outputs. Be token-efficient.
|
||||||
|
- LANGUAGE: You MUST respond in the same language used by the user in their question or instruction.
|
||||||
- NO WANDERING: Do not speculate. If stuck, report attempts.
|
- NO WANDERING: Do not speculate. If stuck, report attempts.
|
||||||
- SAFETY: When you use 'run_commands' with configuration commands, the system automatically prompts the user for confirmation. Just execute - don't ask permission first.
|
- SAFETY: When you use 'run_commands' with configuration commands, the system automatically prompts the user for confirmation. Just execute - don't ask permission first.
|
||||||
{architect_instructions}
|
{architect_instructions}
|
||||||
@@ -161,6 +223,7 @@ class ai:
|
|||||||
- ENGINEER CAPABILITIES: Your Engineer can:
|
- ENGINEER CAPABILITIES: Your Engineer can:
|
||||||
* Filter nodes (list_nodes), Run CLI commands (run_commands), Get metadata (get_node_info).
|
* Filter nodes (list_nodes), Run CLI commands (run_commands), Get metadata (get_node_info).
|
||||||
- ANALYSIS: Review technical findings to identify patterns or design failures.
|
- ANALYSIS: Review technical findings to identify patterns or design failures.
|
||||||
|
- LANGUAGE: You MUST respond in the same language used by the user in their question or instruction.
|
||||||
- MEMORY: Update long-term facts ONLY when the user explicitly requests it.
|
- MEMORY: Update long-term facts ONLY when the user explicitly requests it.
|
||||||
|
|
||||||
CRITICAL - EFFICIENT DELEGATION:
|
CRITICAL - EFFICIENT DELEGATION:
|
||||||
@@ -236,7 +299,6 @@ class ai:
|
|||||||
- response: reconstructed ModelResponse (same as non-streaming)
|
- response: reconstructed ModelResponse (same as non-streaming)
|
||||||
- streamed: True if text was rendered to console during streaming
|
- streamed: True if text was rendered to console during streaming
|
||||||
"""
|
"""
|
||||||
from rich.live import Live
|
|
||||||
|
|
||||||
stream_resp = completion(model=model, messages=messages, tools=tools, api_key=api_key, stream=True, **kwargs)
|
stream_resp = completion(model=model, messages=messages, tools=tools, api_key=api_key, stream=True, **kwargs)
|
||||||
|
|
||||||
@@ -244,7 +306,7 @@ class ai:
|
|||||||
full_content = ""
|
full_content = ""
|
||||||
is_streaming_text = False
|
is_streaming_text = False
|
||||||
has_tool_calls = False
|
has_tool_calls = False
|
||||||
live_display = None
|
header_printed = False
|
||||||
|
|
||||||
# Determine styling based on current brain
|
# Determine styling based on current brain
|
||||||
role_label = "Network Architect" if "architect" in label.lower() else "Network Engineer"
|
role_label = "Network Architect" if "architect" in label.lower() else "Network Engineer"
|
||||||
@@ -271,36 +333,40 @@ class ai:
|
|||||||
raise KeyboardInterrupt
|
raise KeyboardInterrupt
|
||||||
chunk_callback(delta.content)
|
chunk_callback(delta.content)
|
||||||
|
|
||||||
if not debug and not chunk_callback:
|
if not chunk_callback:
|
||||||
if not is_streaming_text:
|
if not is_streaming_text:
|
||||||
# Stop spinner before starting live display
|
|
||||||
if status:
|
if status:
|
||||||
|
try:
|
||||||
status.stop()
|
status.stop()
|
||||||
live_display = Live(
|
except Exception:
|
||||||
Panel(Markdown(full_content), title=title, border_style=border, expand=False),
|
pass
|
||||||
console=self.console,
|
|
||||||
refresh_per_second=8,
|
# Create a stable, direct Console to bypass _ConsoleProxy recreation bugs
|
||||||
transient=False
|
from rich.console import Console as RichConsole
|
||||||
)
|
from rich.rule import Rule
|
||||||
live_display.start()
|
from .printer import connpy_theme, get_original_stdout, IncrementalMarkdownParser
|
||||||
|
stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
|
||||||
|
|
||||||
|
stable_console.print(Rule(f"[bold {border}]{title}[/bold {border}]", style=border))
|
||||||
|
header_printed = True
|
||||||
|
md_parser = IncrementalMarkdownParser(console=stable_console)
|
||||||
is_streaming_text = True
|
is_streaming_text = True
|
||||||
else:
|
|
||||||
live_display.update(
|
md_parser.feed(delta.content)
|
||||||
Panel(Markdown(full_content), title=title, border_style=border, expand=False)
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if not chunks:
|
if not chunks:
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
if live_display:
|
if header_printed:
|
||||||
# Render final state with complete content
|
|
||||||
try:
|
try:
|
||||||
live_display.update(
|
md_parser.flush()
|
||||||
Panel(Markdown(full_content), title=title, border_style=border, expand=False)
|
from rich.console import Console as RichConsole
|
||||||
)
|
from rich.rule import Rule
|
||||||
|
from .printer import connpy_theme, get_original_stdout
|
||||||
|
stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
|
||||||
|
stable_console.print(Rule(style=border))
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
live_display.stop()
|
|
||||||
|
|
||||||
# Rebuild complete response from chunks
|
# Rebuild complete response from chunks
|
||||||
try:
|
try:
|
||||||
@@ -463,7 +529,7 @@ class ai:
|
|||||||
tail_limit = int(final_limit * 0.4)
|
tail_limit = int(final_limit * 0.4)
|
||||||
return (text[:head_limit] + f"\n\n[... OUTPUT TRUNCATED ...]\n\n" + text[-tail_limit:])
|
return (text[:head_limit] + f"\n\n[... OUTPUT TRUNCATED ...]\n\n" + text[-tail_limit:])
|
||||||
|
|
||||||
def _print_debug_observation(self, fn, obs):
|
def _print_debug_observation(self, fn, obs, status=None):
|
||||||
"""Prints a tool observation in a readable way during debug mode."""
|
"""Prints a tool observation in a readable way during debug mode."""
|
||||||
# Try to parse as JSON if it's a string
|
# Try to parse as JSON if it's a string
|
||||||
if isinstance(obs, str):
|
if isinstance(obs, str):
|
||||||
@@ -487,6 +553,7 @@ class ai:
|
|||||||
content = Text("Empty data set")
|
content = Text("Empty data set")
|
||||||
else:
|
else:
|
||||||
# Add a small spacer instead of a Rule for cleaner look
|
# Add a small spacer instead of a Rule for cleaner look
|
||||||
|
from rich.console import Group
|
||||||
content = Group(*elements)
|
content = Group(*elements)
|
||||||
elif isinstance(obs_data, list):
|
elif isinstance(obs_data, list):
|
||||||
content = Text("\n".join(f"• {item}" for item in obs_data))
|
content = Text("\n".join(f"• {item}" for item in obs_data))
|
||||||
@@ -494,8 +561,19 @@ class ai:
|
|||||||
content = Text(str(obs_data))
|
content = Text(str(obs_data))
|
||||||
|
|
||||||
title = f"[bold]{fn}[/bold]"
|
title = f"[bold]{fn}[/bold]"
|
||||||
|
|
||||||
|
# Stop status before printing panel to avoid ghosting
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
|
||||||
self.console.print(Panel(content, title=title, border_style="ai_status"))
|
self.console.print(Panel(content, title=title, border_style="ai_status"))
|
||||||
|
|
||||||
|
# Resume status
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
|
|
||||||
def manage_memory_tool(self, content, action="append"):
|
def manage_memory_tool(self, content, action="append"):
|
||||||
"""Save or update long-term memory. Only use when user explicitly requests it."""
|
"""Save or update long-term memory. Only use when user explicitly requests it."""
|
||||||
if not content or not content.strip():
|
if not content or not content.strip():
|
||||||
@@ -596,7 +674,7 @@ class ai:
|
|||||||
self.console.print("[pass]✓ Trust Mode Enabled. All future commands in this session will execute without confirmation.[/pass]")
|
self.console.print("[pass]✓ Trust Mode Enabled. All future commands in this session will execute without confirmation.[/pass]")
|
||||||
elif user_resp_lower in ['y', 'yes']:
|
elif user_resp_lower in ['y', 'yes']:
|
||||||
self.console.print("[pass]✓ Executing...[/pass]")
|
self.console.print("[pass]✓ Executing...[/pass]")
|
||||||
elif user_resp_lower in ['n', 'no', '']:
|
elif user_resp_lower in ['n', 'no', '', 'cancel']:
|
||||||
self.console.print("[fail]✗ Execution rejected by user.[/fail]")
|
self.console.print("[fail]✗ Execution rejected by user.[/fail]")
|
||||||
return "Error: User rejected execution."
|
return "Error: User rejected execution."
|
||||||
else:
|
else:
|
||||||
@@ -692,19 +770,25 @@ class ai:
|
|||||||
cmd_str = cmds[0] if cmds else ""
|
cmd_str = cmds[0] if cmds else ""
|
||||||
status.update(f"[ai_status]Engineer: [CMD] {cmd_str}")
|
status.update(f"[ai_status]Engineer: [CMD] {cmd_str}")
|
||||||
elif fn == "get_node_info": status.update(f"[ai_status]Engineer: [INSPECT] {args.get('node_name','')}")
|
elif fn == "get_node_info": status.update(f"[ai_status]Engineer: [INSPECT] {args.get('node_name','')}")
|
||||||
|
elif fn.startswith("mcp_"):
|
||||||
|
server = fn.split("__")[0].replace("mcp_", "")
|
||||||
|
tool = fn.split("__")[1] if "__" in fn else fn
|
||||||
|
status.update(f"[ai_status]Engineer: [MCP:{server}] {tool}")
|
||||||
elif fn in self.tool_status_formatters: status.update(self.tool_status_formatters[fn](args))
|
elif fn in self.tool_status_formatters: status.update(self.tool_status_formatters[fn](args))
|
||||||
|
|
||||||
if debug:
|
if debug:
|
||||||
self._print_debug_observation(f"Decision: {fn}", args)
|
self._print_debug_observation(f"Decision: {fn}", args, status=status)
|
||||||
|
|
||||||
if fn == "list_nodes": obs = self.list_nodes_tool(**args)
|
if fn == "list_nodes": obs = self.list_nodes_tool(**args)
|
||||||
elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
|
elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
|
||||||
elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
|
elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
|
||||||
|
elif fn.startswith("mcp_"):
|
||||||
|
obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
|
||||||
elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
|
elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
|
||||||
else: obs = f"Error: Unknown tool '{fn}'."
|
else: obs = f"Error: Unknown tool '{fn}'."
|
||||||
|
|
||||||
if debug:
|
if debug:
|
||||||
self._print_debug_observation(f"Observation: {fn}", obs)
|
self._print_debug_observation(f"Observation: {fn}", obs, status=status)
|
||||||
|
|
||||||
# Ensure observation is a string and truncated for the LLM
|
# Ensure observation is a string and truncated for the LLM
|
||||||
obs_str = obs if isinstance(obs, str) else json.dumps(obs)
|
obs_str = obs if isinstance(obs, str) else json.dumps(obs)
|
||||||
@@ -720,14 +804,22 @@ class ai:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f"Engineer failed: {str(e)}", usage
|
return f"Engineer failed: {str(e)}", usage
|
||||||
|
|
||||||
def _get_engineer_tools(self):
|
def _get_engineer_tools(self, os_filter: str = None):
|
||||||
"""Define tools available to the Engineer."""
|
"""Define tools available to the Engineer."""
|
||||||
base_tools = [
|
base_tools = [
|
||||||
{"type": "function", "function": {"name": "list_nodes", "description": "Lists available nodes in the inventory.", "parameters": {"type": "object", "properties": {"filter_pattern": {"type": "string", "description": "Regex to filter nodes (e.g. '.*', 'border.*')."}}}}},
|
{"type": "function", "function": {"name": "list_nodes", "description": "[Universal Platform] Lists available nodes in the inventory.", "parameters": {"type": "object", "properties": {"filter_pattern": {"type": "string", "description": "Regex to filter nodes (e.g. '.*', 'border.*')."}}}}},
|
||||||
{"type": "function", "function": {"name": "run_commands", "description": "Runs one or more commands on matched nodes. MANDATORY: You MUST call 'list_nodes' first to verify the target list.", "parameters": {"type": "object", "properties": {"nodes_filter": {"type": "string", "description": "Exact node name or verified filter pattern."}, "commands": {"type": "array", "items": {"type": "string"}, "description": "List of commands (e.g. ['show ip route', 'show int desc'])."}}, "required": ["nodes_filter", "commands"]}}},
|
{"type": "function", "function": {"name": "run_commands", "description": "[Universal Platform] Runs one or more commands on matched nodes. MANDATORY: You MUST call 'list_nodes' first to verify the target list.", "parameters": {"type": "object", "properties": {"nodes_filter": {"type": "string", "description": "Exact node name or verified filter pattern."}, "commands": {"type": "array", "items": {"type": "string"}, "description": "List of commands (e.g. ['show ip route', 'show int desc'])."}}, "required": ["nodes_filter", "commands"]}}},
|
||||||
{"type": "function", "function": {"name": "get_node_info", "description": "Gets full metadata for a specific node.", "parameters": {"type": "object", "properties": {"node_name": {"type": "string"}}, "required": ["node_name"]}}}
|
{"type": "function", "function": {"name": "get_node_info", "description": "[Universal Platform] Gets full metadata for a specific node.", "parameters": {"type": "object", "properties": {"node_name": {"type": "string"}}, "required": ["node_name"]}}}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# Add dynamic tools from MCP
|
||||||
|
try:
|
||||||
|
mcp_tools = run_ai_async(self.mcp_manager.get_tools_for_llm(os_filter=os_filter)).result(timeout=10)
|
||||||
|
base_tools.extend(mcp_tools)
|
||||||
|
except Exception as e:
|
||||||
|
# Silently fail for LLM tools
|
||||||
|
pass
|
||||||
|
|
||||||
if self.architect_key:
|
if self.architect_key:
|
||||||
base_tools.extend([
|
base_tools.extend([
|
||||||
{"type": "function", "function": {"name": "consult_architect", "description": "Ask the Strategic Reasoning Engine for advice on complex design, architecture, or troubleshooting decisions. You remain in control and will present the response to the user. Use this for: configuration planning, design validation, complex troubleshooting.", "parameters": {"type": "object", "properties": {"question": {"type": "string", "description": "Strategic question or decision needed."}, "technical_summary": {"type": "string", "description": "Technical findings and context gathered so far."}}, "required": ["question", "technical_summary"]}}},
|
{"type": "function", "function": {"name": "consult_architect", "description": "Ask the Strategic Reasoning Engine for advice on complex design, architecture, or troubleshooting decisions. You remain in control and will present the response to the user. Use this for: configuration planning, design validation, complex troubleshooting.", "parameters": {"type": "object", "properties": {"question": {"type": "string", "description": "Strategic question or decision needed."}, "technical_summary": {"type": "string", "description": "Technical findings and context gathered so far."}}, "required": ["question", "technical_summary"]}}},
|
||||||
@@ -974,7 +1066,7 @@ class ai:
|
|||||||
streamed_response = False
|
streamed_response = False
|
||||||
try:
|
try:
|
||||||
safe_messages = self._sanitize_messages(messages)
|
safe_messages = self._sanitize_messages(messages)
|
||||||
if stream and (not debug or chunk_callback):
|
if stream:
|
||||||
response, streamed_response = self._stream_completion(
|
response, streamed_response = self._stream_completion(
|
||||||
model=model, messages=safe_messages, tools=tools, api_key=key,
|
model=model, messages=safe_messages, tools=tools, api_key=key,
|
||||||
status=status, label=label, debug=debug, num_retries=3,
|
status=status, label=label, debug=debug, num_retries=3,
|
||||||
@@ -1013,11 +1105,17 @@ class ai:
|
|||||||
if msg_dict.get("tool_calls") and msg_dict.get("content") == "": msg_dict["content"] = None
|
if msg_dict.get("tool_calls") and msg_dict.get("content") == "": msg_dict["content"] = None
|
||||||
messages.append(msg_dict)
|
messages.append(msg_dict)
|
||||||
|
|
||||||
if debug and resp_msg.content:
|
if debug and resp_msg.content and not streamed_response:
|
||||||
# In CLI debug mode, only print intermediate reasoning if there are tool calls.
|
# In CLI debug mode, only print intermediate reasoning if there are tool calls AND it wasn't already streamed.
|
||||||
# If there are no tool calls, this content is the final answer and will be printed by the caller.
|
# If there are no tool calls, this content is the final answer and will be printed by the caller.
|
||||||
if resp_msg.tool_calls:
|
if resp_msg.tool_calls:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
self.console.print(Panel(Markdown(resp_msg.content), title=f"[{current_brain}][bold]{label} Reasoning[/bold][/{current_brain}]", border_style="architect" if current_brain == "architect" else "engineer"))
|
self.console.print(Panel(Markdown(resp_msg.content), title=f"[{current_brain}][bold]{label} Reasoning[/bold][/{current_brain}]", border_style="architect" if current_brain == "architect" else "engineer"))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
|
|
||||||
if not resp_msg.tool_calls: break
|
if not resp_msg.tool_calls: break
|
||||||
|
|
||||||
@@ -1038,7 +1136,7 @@ class ai:
|
|||||||
elif fn == "manage_memory_tool": status.update(f"[architect]Architect: [UPDATING MEMORY]")
|
elif fn == "manage_memory_tool": status.update(f"[architect]Architect: [UPDATING MEMORY]")
|
||||||
|
|
||||||
if debug:
|
if debug:
|
||||||
self._print_debug_observation(f"Decision: {fn}", args)
|
self._print_debug_observation(f"Decision: {fn}", args, status=status)
|
||||||
|
|
||||||
if fn == "delegate_to_engineer":
|
if fn == "delegate_to_engineer":
|
||||||
obs, eng_usage = self._engineer_loop(args["task"], status=status, debug=debug, chat_history=messages[:-1])
|
obs, eng_usage = self._engineer_loop(args["task"], status=status, debug=debug, chat_history=messages[:-1])
|
||||||
@@ -1057,7 +1155,14 @@ class ai:
|
|||||||
num_retries=3
|
num_retries=3
|
||||||
)
|
)
|
||||||
obs = claude_resp.choices[0].message.content
|
obs = claude_resp.choices[0].message.content
|
||||||
if debug: self.console.print(Panel(Markdown(obs), title="[architect]Architect Consultation[/architect]", border_style="architect"))
|
if debug:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
self.console.print(Panel(Markdown(obs), title="[architect]Architect Consultation[/architect]", border_style="architect"))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if status: status.update("[unavailable]Architect unavailable! Engineer continuing alone...")
|
if status: status.update("[unavailable]Architect unavailable! Engineer continuing alone...")
|
||||||
obs = f"Architect unavailable ({str(e)}). Proceeding with your best technical judgment."
|
obs = f"Architect unavailable ({str(e)}). Proceeding with your best technical judgment."
|
||||||
@@ -1074,7 +1179,14 @@ class ai:
|
|||||||
handover_msg = f"HANDOVER FROM EXECUTION ENGINE\n\nReason: {args['reason']}\n\nContext: {args['context']}\n\nYou are now in control of this conversation."
|
handover_msg = f"HANDOVER FROM EXECUTION ENGINE\n\nReason: {args['reason']}\n\nContext: {args['context']}\n\nYou are now in control of this conversation."
|
||||||
pending_user_message = handover_msg
|
pending_user_message = handover_msg
|
||||||
obs = "Control transferred to Architect. Handover context will be provided."
|
obs = "Control transferred to Architect. Handover context will be provided."
|
||||||
if debug: self.console.print(Panel(Text(handover_msg), title="[architect]Escalation to Architect[/architect]", border_style="architect"))
|
if debug:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
self.console.print(Panel(Text(handover_msg), title="[architect]Escalation to Architect[/architect]", border_style="architect"))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
|
|
||||||
elif fn == "return_to_engineer":
|
elif fn == "return_to_engineer":
|
||||||
if status: status.update("[engineer]Transferring control back to Engineer...")
|
if status: status.update("[engineer]Transferring control back to Engineer...")
|
||||||
@@ -1088,17 +1200,26 @@ class ai:
|
|||||||
handover_msg = f"HANDOVER FROM ARCHITECT\n\nSummary: {args['summary']}\n\nYou are now back in control. Continue handling the user's requests."
|
handover_msg = f"HANDOVER FROM ARCHITECT\n\nSummary: {args['summary']}\n\nYou are now back in control. Continue handling the user's requests."
|
||||||
pending_user_message = handover_msg
|
pending_user_message = handover_msg
|
||||||
obs = "Control returned to Engineer. Handover summary will be provided."
|
obs = "Control returned to Engineer. Handover summary will be provided."
|
||||||
if debug: self.console.print(Panel(Text(handover_msg), title="[engineer]Return to Engineer[/engineer]", border_style="engineer"))
|
if debug:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
self.console.print(Panel(Text(handover_msg), title="[engineer]Return to Engineer[/engineer]", border_style="engineer"))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
|
|
||||||
elif fn == "list_nodes": obs = self.list_nodes_tool(**args)
|
elif fn == "list_nodes": obs = self.list_nodes_tool(**args)
|
||||||
elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
|
elif fn == "run_commands": obs = self.run_commands_tool(**args, status=status)
|
||||||
elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
|
elif fn == "get_node_info": obs = self.get_node_info_tool(**args)
|
||||||
elif fn == "manage_memory_tool": obs = self.manage_memory_tool(**args)
|
elif fn == "manage_memory_tool": obs = self.manage_memory_tool(**args)
|
||||||
|
elif fn.startswith("mcp_"):
|
||||||
|
obs = run_ai_async(self.mcp_manager.call_tool(fn, args)).result(timeout=60)
|
||||||
elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
|
elif fn in self.external_tool_handlers: obs = self.external_tool_handlers[fn](self, **args)
|
||||||
else: obs = f"Error: {fn} unknown."
|
else: obs = f"Error: {fn} unknown."
|
||||||
|
|
||||||
if debug and fn not in ["delegate_to_engineer", "consult_architect", "escalate_to_architect", "return_to_engineer"]:
|
if debug and fn not in ["delegate_to_engineer", "consult_architect", "escalate_to_architect", "return_to_engineer"]:
|
||||||
self._print_debug_observation(f"Observation: {fn}", obs)
|
self._print_debug_observation(f"Observation: {fn}", obs, status=status)
|
||||||
|
|
||||||
# Ensure observation is a string and truncated for the LLM
|
# Ensure observation is a string and truncated for the LLM
|
||||||
obs_str = obs if isinstance(obs, str) else json.dumps(obs)
|
obs_str = obs if isinstance(obs, str) else json.dumps(obs)
|
||||||
@@ -1160,5 +1281,279 @@ class ai:
|
|||||||
"streamed": streamed_response
|
"streamed": streamed_response
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@MethodHook
|
||||||
|
async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from litellm import acompletion
|
||||||
|
import asyncio
|
||||||
|
import warnings
|
||||||
|
import aiohttp
|
||||||
|
|
||||||
|
# Suppress unawaited coroutine warnings from LiteLLM's internal streaming logic during sudden cancellation
|
||||||
|
warnings.filterwarnings("ignore", message="coroutine '.*async_streaming.*' was never awaited", category=RuntimeWarning)
|
||||||
|
|
||||||
|
node_info = node_info or {}
|
||||||
|
os_info = node_info.get("os", "unknown")
|
||||||
|
node_name = node_info.get("name", "unknown")
|
||||||
|
persona = node_info.get("persona", "engineer")
|
||||||
|
memories = node_info.get("memories", [])
|
||||||
|
|
||||||
|
vendor_reference = ""
|
||||||
|
if os_info and os_info != "unknown":
|
||||||
|
try:
|
||||||
|
os_filename = os_info.lower().replace(" ", "_")
|
||||||
|
ref_path = os.path.join(self.config.defaultdir, "ai_references", f"{os_filename}.md")
|
||||||
|
if os.path.exists(ref_path):
|
||||||
|
with open(ref_path, "r") as f:
|
||||||
|
vendor_reference = f.read().strip()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if persona == "architect":
|
||||||
|
system_prompt = f"""Role: NETWORK ARCHITECT. You act as a senior strategic advisor during a live SSH session.
|
||||||
|
Rules:
|
||||||
|
1. MANDATORY: You MUST respond in the same language used by the user in their question.
|
||||||
|
2. Answer the user's question directly and EXCLUSIVELY based on the Terminal Context.
|
||||||
|
3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information.
|
||||||
|
4. Focus on the "why" and "how". Analyze topologies, design patterns, and validate configurations.
|
||||||
|
5. Do NOT provide commands to execute unless specifically requested. Instead, explain the consequences and best practices.
|
||||||
|
6. Keep your guide concise and authoritative.
|
||||||
|
7. You MUST output your response in the following strict format:
|
||||||
|
<guide>
|
||||||
|
Your brief tactical guide in markdown.
|
||||||
|
</guide>
|
||||||
|
<commands>
|
||||||
|
</commands>
|
||||||
|
<risk>
|
||||||
|
low
|
||||||
|
</risk>
|
||||||
|
8. Risk level is usually "low" for read-only/no commands.
|
||||||
|
|
||||||
|
Terminal Context:
|
||||||
|
{terminal_buffer}
|
||||||
|
|
||||||
|
Device OS: {os_info}
|
||||||
|
Node: {node_name}"""
|
||||||
|
else:
|
||||||
|
system_prompt = f"""Role: TERMINAL COPILOT. You assist a network engineer during a live SSH session.
|
||||||
|
Rules:
|
||||||
|
1. MANDATORY: You MUST respond in the same language used by the user in their question.
|
||||||
|
2. EXTREMELY IMPORTANT: Answer EXCLUSIVELY based on the provided Terminal Context.
|
||||||
|
3. NO HALLUCINATIONS. The Terminal Context is a live buffer. If it contains only a shell prompt (like 'iol#' or 'admin@vrouter>') and no command output, it means YOU DON'T HAVE DATA. In this case, YOU MUST NOT invent any information. Instead, explicitly state that you don't see the data and offer the correct CLI commands to retrieve it.
|
||||||
|
4. If the user asks you to analyze, parse, or extract data from the Terminal Context, DO IT directly in the <guide> section (you can use markdown tables or lists). Do NOT just give them a command to do it themselves.
|
||||||
|
5. If the user wants to execute an action, provide the required CLI commands inside a <commands> block, one command per line. If no commands are needed, leave it empty or omit the block.
|
||||||
|
6. ULTRA-CONCISE. Keep your guide to the point.
|
||||||
|
7. You MUST output your response in the following strict format:
|
||||||
|
<guide>
|
||||||
|
Your brief tactical guide in markdown. 3-4 sentences max.
|
||||||
|
</guide>
|
||||||
|
<commands>
|
||||||
|
command 1
|
||||||
|
command 2
|
||||||
|
</commands>
|
||||||
|
<risk>
|
||||||
|
low, high, or destructive
|
||||||
|
</risk>
|
||||||
|
8. Risk level: "low" for read-only/no commands, "high" for config changes, "destructive" for potentially dangerous ops.
|
||||||
|
|
||||||
|
Terminal Context:
|
||||||
|
{terminal_buffer}
|
||||||
|
|
||||||
|
Device OS: {os_info}
|
||||||
|
Node: {node_name}"""
|
||||||
|
|
||||||
|
if vendor_reference:
|
||||||
|
system_prompt += f"\n\nVendor Command Reference:\n{vendor_reference}"
|
||||||
|
|
||||||
|
if memories:
|
||||||
|
system_prompt += "\n\nSession Memory (Important Facts):\n"
|
||||||
|
for m in memories:
|
||||||
|
system_prompt += f"- {m}\n"
|
||||||
|
|
||||||
|
# Fetch MCP tools for the current OS
|
||||||
|
mcp_tools = []
|
||||||
|
try:
|
||||||
|
mcp_tools = await self.mcp_manager.get_tools_for_llm(os_filter=os_info)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if mcp_tools:
|
||||||
|
system_prompt += f"\n\nAvailable MCP Tools: {', '.join([t['function']['name'] for t in mcp_tools])}"
|
||||||
|
system_prompt += "\nUse these tools to validate syntax or find exact commands if needed before providing the final guide."
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt},
|
||||||
|
{"role": "user", "content": user_question}
|
||||||
|
]
|
||||||
|
|
||||||
|
iteration = 0
|
||||||
|
max_iterations = 5 # Allow up to 5 iterations for tool usage
|
||||||
|
|
||||||
|
# Use models based on persona
|
||||||
|
current_model = self.architect_model if persona == "architect" else self.engineer_model
|
||||||
|
current_key = self.architect_key if persona == "architect" else self.engineer_key
|
||||||
|
|
||||||
|
try:
|
||||||
|
while iteration < 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 = ""
|
||||||
|
streamed_guide = ""
|
||||||
|
tool_calls = []
|
||||||
|
|
||||||
|
async for chunk in response:
|
||||||
|
delta = chunk.choices[0].delta
|
||||||
|
|
||||||
|
# Accumulate tool calls
|
||||||
|
if hasattr(delta, 'tool_calls') and delta.tool_calls:
|
||||||
|
for tc in delta.tool_calls:
|
||||||
|
idx = tc.index
|
||||||
|
if idx >= len(tool_calls):
|
||||||
|
tool_calls.append({"id": tc.id, "type": "function", "function": {"name": tc.function.name or "", "arguments": tc.function.arguments or ""}})
|
||||||
|
else:
|
||||||
|
if tc.id: tool_calls[idx]["id"] = tc.id
|
||||||
|
if tc.function.name: tool_calls[idx]["function"]["name"] = tc.function.name
|
||||||
|
if tc.function.arguments: tool_calls[idx]["function"]["arguments"] += tc.function.arguments
|
||||||
|
|
||||||
|
if hasattr(delta, 'content') and delta.content:
|
||||||
|
full_content += delta.content
|
||||||
|
|
||||||
|
if chunk_callback and not tool_calls: # Only stream if not using tools
|
||||||
|
start_idx = full_content.find("<guide>")
|
||||||
|
if start_idx != -1:
|
||||||
|
after_start = full_content[start_idx + 7:]
|
||||||
|
end_idx = after_start.find("</guide>")
|
||||||
|
|
||||||
|
if end_idx != -1:
|
||||||
|
current_guide = after_start[:end_idx]
|
||||||
|
else:
|
||||||
|
current_guide = after_start
|
||||||
|
if current_guide.endswith("<"): current_guide = current_guide[:-1]
|
||||||
|
elif current_guide.endswith("</"): current_guide = current_guide[:-2]
|
||||||
|
elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
|
||||||
|
elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
|
||||||
|
elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
|
||||||
|
elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
|
||||||
|
elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
|
||||||
|
|
||||||
|
new_text = current_guide[len(streamed_guide):]
|
||||||
|
if new_text:
|
||||||
|
chunk_callback(new_text)
|
||||||
|
streamed_guide += new_text
|
||||||
|
|
||||||
|
if not tool_calls:
|
||||||
|
break
|
||||||
|
|
||||||
|
# Execute tool calls
|
||||||
|
messages.append({"role": "assistant", "content": full_content or None, "tool_calls": tool_calls})
|
||||||
|
for tc in tool_calls:
|
||||||
|
fn = tc["function"]["name"]
|
||||||
|
args = json.loads(tc["function"]["arguments"])
|
||||||
|
|
||||||
|
if "mcp_" in fn:
|
||||||
|
try:
|
||||||
|
obs = await asyncio.wait_for(self.mcp_manager.call_tool(fn, args), timeout=30.0)
|
||||||
|
except Exception as e:
|
||||||
|
obs = f"Error calling MCP tool: {e}"
|
||||||
|
else:
|
||||||
|
obs = f"Error: Tool {fn} not allowed in Copilot."
|
||||||
|
|
||||||
|
messages.append({"tool_call_id": tc["id"], "role": "tool", "name": fn, "content": self._truncate(str(obs))})
|
||||||
|
|
||||||
|
# If we hit the limit and it was still using tools, force a final answer
|
||||||
|
if tool_calls and iteration >= max_iterations:
|
||||||
|
messages.append({"role": "user", "content": "Tool limit reached. Provide your final tactical guide now based on the findings."})
|
||||||
|
response = await acompletion(
|
||||||
|
model=self.engineer_model,
|
||||||
|
messages=messages,
|
||||||
|
tools=None,
|
||||||
|
api_key=self.engineer_key,
|
||||||
|
stream=True
|
||||||
|
)
|
||||||
|
|
||||||
|
full_content = ""
|
||||||
|
streamed_guide = ""
|
||||||
|
async for chunk in response:
|
||||||
|
delta = chunk.choices[0].delta
|
||||||
|
if hasattr(delta, 'content') and delta.content:
|
||||||
|
full_content += delta.content
|
||||||
|
if chunk_callback:
|
||||||
|
start_idx = full_content.find("<guide>")
|
||||||
|
if start_idx != -1:
|
||||||
|
after_start = full_content[start_idx + 7:]
|
||||||
|
end_idx = after_start.find("</guide>")
|
||||||
|
if end_idx != -1:
|
||||||
|
current_guide = after_start[:end_idx]
|
||||||
|
else:
|
||||||
|
current_guide = after_start
|
||||||
|
if current_guide.endswith("<"): current_guide = current_guide[:-1]
|
||||||
|
elif current_guide.endswith("</"): current_guide = current_guide[:-2]
|
||||||
|
elif current_guide.endswith("</g"): current_guide = current_guide[:-3]
|
||||||
|
elif current_guide.endswith("</gu"): current_guide = current_guide[:-4]
|
||||||
|
elif current_guide.endswith("</gui"): current_guide = current_guide[:-5]
|
||||||
|
elif current_guide.endswith("</guid"): current_guide = current_guide[:-6]
|
||||||
|
elif current_guide.endswith("</guide"): current_guide = current_guide[:-7]
|
||||||
|
new_text = current_guide[len(streamed_guide):]
|
||||||
|
if new_text:
|
||||||
|
chunk_callback(new_text)
|
||||||
|
streamed_guide += new_text
|
||||||
|
|
||||||
|
guide = ""
|
||||||
|
commands = []
|
||||||
|
risk_level = "low"
|
||||||
|
|
||||||
|
guide_match = re.search(r"<guide>(.*?)</guide>", full_content, re.DOTALL)
|
||||||
|
if guide_match:
|
||||||
|
guide = guide_match.group(1).strip()
|
||||||
|
|
||||||
|
cmd_match = re.search(r"<commands>(.*?)</commands>", full_content, re.DOTALL)
|
||||||
|
if cmd_match:
|
||||||
|
cmds_raw = cmd_match.group(1).strip()
|
||||||
|
if cmds_raw:
|
||||||
|
commands = [c.strip() for c in cmds_raw.split('\n') if c.strip()]
|
||||||
|
|
||||||
|
risk_match = re.search(r"<risk>(.*?)</risk>", full_content, re.DOTALL)
|
||||||
|
if risk_match:
|
||||||
|
risk_level = risk_match.group(1).strip().lower()
|
||||||
|
|
||||||
|
if not guide and full_content and not ("<guide>" in full_content):
|
||||||
|
guide = full_content.strip()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"commands": commands,
|
||||||
|
"guide": guide,
|
||||||
|
"risk_level": risk_level,
|
||||||
|
"error": None
|
||||||
|
}
|
||||||
|
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
# Client cancelled the request via gRPC or local interrupt
|
||||||
|
if 'response' in locals():
|
||||||
|
try:
|
||||||
|
if hasattr(response, 'aclose'):
|
||||||
|
# Fire and forget the close to avoid blocking the cancel
|
||||||
|
asyncio.create_task(response.aclose())
|
||||||
|
elif hasattr(response, 'close'):
|
||||||
|
response.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"commands": [],
|
||||||
|
"guide": "",
|
||||||
|
"risk_level": "low",
|
||||||
|
"error": str(e)
|
||||||
|
}
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
def confirm(self, user_input): return True
|
def confirm(self, user_input): return True
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ def debug_api(port=8048, config=None):
|
|||||||
printer.info(f"gRPC Server running in debug mode on port {port}...")
|
printer.info(f"gRPC Server running in debug mode on port {port}...")
|
||||||
_wait_for_termination()
|
_wait_for_termination()
|
||||||
server.stop(0)
|
server.stop(0)
|
||||||
|
from .ai import cleanup
|
||||||
|
cleanup()
|
||||||
|
|
||||||
def start_server(port=8048, config=None):
|
def start_server(port=8048, config=None):
|
||||||
try:
|
try:
|
||||||
@@ -67,6 +69,9 @@ def start_server(port=8048, config=None):
|
|||||||
conf = config or configfile()
|
conf = config or configfile()
|
||||||
server = serve(conf, port=port, debug=False)
|
server = serve(conf, port=port, debug=False)
|
||||||
_wait_for_termination()
|
_wait_for_termination()
|
||||||
|
server.stop(0)
|
||||||
|
from .ai import cleanup
|
||||||
|
cleanup()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
printer.error(f"Background API failed to start: {e}")
|
printer.error(f"Background API failed to start: {e}")
|
||||||
os._exit(1)
|
os._exit(1)
|
||||||
|
|||||||
+116
-3
@@ -32,6 +32,9 @@ class AIHandler:
|
|||||||
printer.error(str(e))
|
printer.error(str(e))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if args.mcp is not None:
|
||||||
|
return self.configure_mcp(args)
|
||||||
|
|
||||||
# Determinar session_id para retomar
|
# Determinar session_id para retomar
|
||||||
session_id = None
|
session_id = None
|
||||||
if args.resume:
|
if args.resume:
|
||||||
@@ -88,7 +91,6 @@ class AIHandler:
|
|||||||
if "usage" in result:
|
if "usage" in result:
|
||||||
u = result["usage"]
|
u = result["usage"]
|
||||||
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
||||||
console.print()
|
|
||||||
|
|
||||||
def interactive_chat(self, args, session_id):
|
def interactive_chat(self, args, session_id):
|
||||||
history = None
|
history = None
|
||||||
@@ -111,7 +113,7 @@ class AIHandler:
|
|||||||
try:
|
try:
|
||||||
user_query = Prompt.ask("[user_prompt]User[/user_prompt]")
|
user_query = Prompt.ask("[user_prompt]User[/user_prompt]")
|
||||||
if not user_query.strip(): continue
|
if not user_query.strip(): continue
|
||||||
if user_query.lower() in ['exit', 'quit', 'bye']: break
|
if user_query.lower() in ['exit', 'quit', 'bye', 'cancel']: break
|
||||||
|
|
||||||
with console.status("[ai_status]Agent is thinking...") as status:
|
with console.status("[ai_status]Agent is thinking...") as status:
|
||||||
result = self.app.myai.ask(user_query, chat_history=history, status=status, debug=args.debug, trust=args.trust, **self.ai_overrides)
|
result = self.app.myai.ask(user_query, chat_history=history, status=status, debug=args.debug, trust=args.trust, **self.ai_overrides)
|
||||||
@@ -132,7 +134,118 @@ class AIHandler:
|
|||||||
if "usage" in result:
|
if "usage" in result:
|
||||||
u = result["usage"]
|
u = result["usage"]
|
||||||
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
||||||
console.print()
|
|
||||||
except (KeyboardInterrupt, EOFError):
|
except (KeyboardInterrupt, EOFError):
|
||||||
console.print("\n[dim]Session closed.[/dim]")
|
console.print("\n[dim]Session closed.[/dim]")
|
||||||
break
|
break
|
||||||
|
|
||||||
|
def configure_mcp(self, args):
|
||||||
|
"""Handle MCP server configuration via CLI tokens or interactive wizard."""
|
||||||
|
mcp_args = args.mcp
|
||||||
|
|
||||||
|
# 1. Non-interactive CLI Mode (if arguments are provided)
|
||||||
|
if mcp_args:
|
||||||
|
action = mcp_args[0].lower()
|
||||||
|
|
||||||
|
if action == "list":
|
||||||
|
settings = self.app.services.config_svc.get_settings()
|
||||||
|
mcp_servers = settings.get("ai", {}).get("mcp_servers", {})
|
||||||
|
if not mcp_servers:
|
||||||
|
printer.info("No MCP servers configured.")
|
||||||
|
else:
|
||||||
|
columns = ["Name", "URL", "Enabled", "Auto-load OS"]
|
||||||
|
rows = []
|
||||||
|
for name, cfg in mcp_servers.items():
|
||||||
|
rows.append([
|
||||||
|
name,
|
||||||
|
cfg.get("url", ""),
|
||||||
|
"[green]Yes[/green]" if cfg.get("enabled", True) else "[red]No[/red]",
|
||||||
|
cfg.get("auto_load_on_os", "Any")
|
||||||
|
])
|
||||||
|
printer.table("Configured MCP Servers", columns, rows)
|
||||||
|
return
|
||||||
|
|
||||||
|
elif action == "add":
|
||||||
|
if len(mcp_args) < 3:
|
||||||
|
printer.error("Usage: connpy ai --mcp add <name> <url> [os_filter]")
|
||||||
|
return
|
||||||
|
name, url = mcp_args[1], mcp_args[2]
|
||||||
|
os_filter = mcp_args[3] if len(mcp_args) > 3 else None
|
||||||
|
try:
|
||||||
|
self.app.services.ai.configure_mcp(name, url=url, auto_load_on_os=os_filter)
|
||||||
|
printer.success(f"MCP server '{name}' added/updated.")
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
elif action == "remove":
|
||||||
|
if len(mcp_args) < 2:
|
||||||
|
printer.error("Usage: connpy ai --mcp remove <name>")
|
||||||
|
return
|
||||||
|
name = mcp_args[1]
|
||||||
|
try:
|
||||||
|
self.app.services.ai.configure_mcp(name, remove=True)
|
||||||
|
printer.success(f"MCP server '{name}' removed.")
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
elif action in ["enable", "disable"]:
|
||||||
|
if len(mcp_args) < 2:
|
||||||
|
printer.error(f"Usage: connpy ai --mcp {action} <name>")
|
||||||
|
return
|
||||||
|
name = mcp_args[1]
|
||||||
|
enabled = (action == "enable")
|
||||||
|
try:
|
||||||
|
self.app.services.ai.configure_mcp(name, enabled=enabled)
|
||||||
|
printer.success(f"MCP server '{name}' {'enabled' if enabled else 'disabled'}.")
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
else:
|
||||||
|
printer.error(f"Unknown MCP action: {action}")
|
||||||
|
printer.info("Available actions: list, add, remove, enable, disable")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2. Interactive Wizard Mode (if no arguments provided)
|
||||||
|
# Import forms dynamically to avoid circular dependencies if any
|
||||||
|
if not hasattr(self.app, "cli_forms"):
|
||||||
|
from .forms import Forms
|
||||||
|
self.app.cli_forms = Forms(self.app)
|
||||||
|
|
||||||
|
settings = self.app.services.config_svc.get_settings()
|
||||||
|
mcp_servers = settings.get("ai", {}).get("mcp_servers", {})
|
||||||
|
|
||||||
|
result = self.app.cli_forms.mcp_wizard(mcp_servers)
|
||||||
|
if not result:
|
||||||
|
return
|
||||||
|
|
||||||
|
action = result["action"]
|
||||||
|
try:
|
||||||
|
if action == "list":
|
||||||
|
# Recursive call to the non-interactive list logic
|
||||||
|
args.mcp = ["list"]
|
||||||
|
return self.configure_mcp(args)
|
||||||
|
|
||||||
|
elif action == "add":
|
||||||
|
self.app.services.ai.configure_mcp(
|
||||||
|
result["name"],
|
||||||
|
url=result["url"],
|
||||||
|
enabled=result["enabled"],
|
||||||
|
auto_load_on_os=result["os"]
|
||||||
|
)
|
||||||
|
printer.success(f"MCP server '{result['name']}' saved.")
|
||||||
|
|
||||||
|
elif action == "update": # Used for toggle
|
||||||
|
self.app.services.ai.configure_mcp(
|
||||||
|
result["name"],
|
||||||
|
enabled=result["enabled"]
|
||||||
|
)
|
||||||
|
printer.success(f"MCP server '{result['name']}' updated.")
|
||||||
|
|
||||||
|
elif action == "remove":
|
||||||
|
self.app.services.ai.configure_mcp(result["name"], remove=True)
|
||||||
|
printer.success(f"MCP server '{result['name']}' removed.")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
|||||||
@@ -197,3 +197,84 @@ class Forms:
|
|||||||
answer["tags"] = ast.literal_eval(answer["tags"])
|
answer["tags"] = ast.literal_eval(answer["tags"])
|
||||||
|
|
||||||
return answer
|
return answer
|
||||||
|
|
||||||
|
def mcp_wizard(self, mcp_servers):
|
||||||
|
"""Interactive wizard to manage MCP servers."""
|
||||||
|
from .helpers import theme
|
||||||
|
|
||||||
|
while True:
|
||||||
|
options = [
|
||||||
|
("List Configured Servers", "list"),
|
||||||
|
("Add/Update Server", "add"),
|
||||||
|
("Enable/Disable Server", "toggle"),
|
||||||
|
("Remove Server", "remove"),
|
||||||
|
("Back", "exit")
|
||||||
|
]
|
||||||
|
|
||||||
|
questions = [
|
||||||
|
inquirer.List("action", message="MCP Configuration", choices=options)
|
||||||
|
]
|
||||||
|
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if not answers or answers["action"] == "exit":
|
||||||
|
return None
|
||||||
|
|
||||||
|
action = answers["action"]
|
||||||
|
|
||||||
|
if action == "list":
|
||||||
|
if not mcp_servers:
|
||||||
|
print("\nNo MCP servers configured.\n")
|
||||||
|
else:
|
||||||
|
return {"action": "list"}
|
||||||
|
|
||||||
|
elif action == "add":
|
||||||
|
questions = [
|
||||||
|
inquirer.Text("name", message="Server Name (identifier)"),
|
||||||
|
inquirer.Text("url", message="SSE URL (e.g., http://localhost:8000/sse)"),
|
||||||
|
inquirer.Confirm("enabled", message="Enabled?", default=True),
|
||||||
|
inquirer.Text("auto_load_os", message="Auto-load on specific OS (blank for any)")
|
||||||
|
]
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if answers:
|
||||||
|
return {
|
||||||
|
"action": "add",
|
||||||
|
"name": answers["name"],
|
||||||
|
"url": answers["url"],
|
||||||
|
"enabled": answers["enabled"],
|
||||||
|
"os": answers["auto_load_os"]
|
||||||
|
}
|
||||||
|
|
||||||
|
elif action == "toggle":
|
||||||
|
if not mcp_servers:
|
||||||
|
print("\nNo servers to toggle.\n")
|
||||||
|
continue
|
||||||
|
|
||||||
|
choices = []
|
||||||
|
for name, cfg in mcp_servers.items():
|
||||||
|
status = "[Enabled]" if cfg.get("enabled", True) else "[Disabled]"
|
||||||
|
choices.append((f"{name} {status}", name))
|
||||||
|
|
||||||
|
questions = [
|
||||||
|
inquirer.List("name", message="Select server to toggle", choices=choices + [("Cancel", None)])
|
||||||
|
]
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if answers and answers["name"]:
|
||||||
|
current = mcp_servers[answers["name"]].get("enabled", True)
|
||||||
|
return {
|
||||||
|
"action": "update",
|
||||||
|
"name": answers["name"],
|
||||||
|
"enabled": not current
|
||||||
|
}
|
||||||
|
|
||||||
|
elif action == "remove":
|
||||||
|
if not mcp_servers:
|
||||||
|
print("\nNo servers to remove.\n")
|
||||||
|
continue
|
||||||
|
|
||||||
|
questions = [
|
||||||
|
inquirer.List("name", message="Select server to remove", choices=list(mcp_servers.keys()) + ["Cancel"])
|
||||||
|
]
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if answers and answers["name"] != "Cancel":
|
||||||
|
return {"action": "remove", "name": answers["name"]}
|
||||||
|
return None
|
||||||
|
|||||||
@@ -55,6 +55,10 @@ Here are some important instructions and tips for configuring your new node:
|
|||||||
- `prompt`: Replaces default app prompt to identify the end of output or where the user can start inputting commands.
|
- `prompt`: Replaces default app prompt to identify the end of output or where the user can start inputting commands.
|
||||||
- `kube_command`: Replaces the default command (`/bin/bash`) for `kubectl exec`.
|
- `kube_command`: Replaces the default command (`/bin/bash`) for `kubectl exec`.
|
||||||
- `docker_command`: Replaces the default command for `docker exec`.
|
- `docker_command`: Replaces the default command for `docker exec`.
|
||||||
|
- `region`: AWS Region used for `aws ssm start-session`.
|
||||||
|
- `profile`: AWS Profile used for `aws ssm start-session`.
|
||||||
|
- `ssh_options`: Additional SSH options injected when an SSM node is used as a jumphost (e.g., `-i ~/.ssh/key.pem`).
|
||||||
|
- `nc_command`: Replaces the default `nc` command used when bridging connections through Docker or Kubernetes (e.g., `ip netns exec global-vrf nc`).
|
||||||
"""
|
"""
|
||||||
if type == "bashcompletion":
|
if type == "bashcompletion":
|
||||||
return '''
|
return '''
|
||||||
@@ -153,9 +157,7 @@ tasks:
|
|||||||
nodes: #List of nodes to work on. Mandatory
|
nodes: #List of nodes to work on. Mandatory
|
||||||
- 'router1@office' #You can add specific nodes
|
- 'router1@office' #You can add specific nodes
|
||||||
- '@aws' #entire folders or subfolders
|
- '@aws' #entire folders or subfolders
|
||||||
- '@office': #or filter inside a folder or subfolder
|
- 'router.*@office' #or use regex to filter inside a folder
|
||||||
- 'router2'
|
|
||||||
- 'router7'
|
|
||||||
|
|
||||||
commands: #List of commands to send, use {name} to pass variables
|
commands: #List of commands to send, use {name} to pass variables
|
||||||
- 'term len 0'
|
- 'term len 0'
|
||||||
@@ -181,7 +183,7 @@ tasks:
|
|||||||
vrouterN@aws:
|
vrouterN@aws:
|
||||||
id: 5
|
id: 5
|
||||||
|
|
||||||
output: /home/user/logs #Type of output, if null you only get Connection and test result. Choices are: null,stdout,/path/to/folder. Folder path only works on 'run' action.
|
output: /home/user/logs #Type of output, if null you only get Connection and test result. Choices are: null,stdout,/path/to/folder. Folder path works on both 'run' and 'test' actions.
|
||||||
|
|
||||||
options:
|
options:
|
||||||
prompt: r'>$|#$|\$$|>.$|#.$|\$.$' #Optional prompt to check on your devices, default should work on most devices.
|
prompt: r'>$|#$|\$$|>.$|#.$|\$.$' #Optional prompt to check on your devices, default should work on most devices.
|
||||||
@@ -193,9 +195,6 @@ tasks:
|
|||||||
nodes:
|
nodes:
|
||||||
- 'router1@office'
|
- 'router1@office'
|
||||||
- '@aws'
|
- '@aws'
|
||||||
- '@office':
|
|
||||||
- 'router2'
|
|
||||||
- 'router7'
|
|
||||||
commands:
|
commands:
|
||||||
- 'ping 10.100.100.{id}'
|
- 'ping 10.100.100.{id}'
|
||||||
expected: '!' #Expected text to find when running test action. Mandatory for 'test'
|
expected: '!' #Expected text to find when running test action. Mandatory for 'test'
|
||||||
|
|||||||
+62
-15
@@ -1,6 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import yaml
|
import yaml
|
||||||
|
import threading
|
||||||
from rich.rule import Rule
|
from rich.rule import Rule
|
||||||
from .. import printer
|
from .. import printer
|
||||||
from ..services.exceptions import ConnpyError
|
from ..services.exceptions import ConnpyError
|
||||||
@@ -9,6 +10,7 @@ from .help_text import get_instructions
|
|||||||
class RunHandler:
|
class RunHandler:
|
||||||
def __init__(self, app):
|
def __init__(self, app):
|
||||||
self.app = app
|
self.app = app
|
||||||
|
self.print_lock = threading.Lock()
|
||||||
|
|
||||||
def dispatch(self, args):
|
def dispatch(self, args):
|
||||||
if len(args.data) > 1:
|
if len(args.data) > 1:
|
||||||
@@ -22,19 +24,40 @@ class RunHandler:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
header_printed = False
|
header_printed = False
|
||||||
# Inline execution with streaming results
|
|
||||||
|
if hasattr(args, 'test_expected') and args.test_expected:
|
||||||
|
# Mode: Test
|
||||||
|
def _on_node_complete(unique, node_output, node_status, node_result):
|
||||||
|
nonlocal header_printed
|
||||||
|
with self.print_lock:
|
||||||
|
if not header_printed:
|
||||||
|
printer.console.print(Rule("OUTPUT", style="header"))
|
||||||
|
header_printed = True
|
||||||
|
printer.test_panel(unique, node_output, node_status, node_result)
|
||||||
|
|
||||||
|
results = self.app.services.execution.test_commands(
|
||||||
|
nodes_filter=nodes_filter,
|
||||||
|
commands=commands,
|
||||||
|
expected=args.test_expected,
|
||||||
|
on_node_complete=_on_node_complete
|
||||||
|
)
|
||||||
|
printer.test_summary(results)
|
||||||
|
else:
|
||||||
|
# Mode: Normal Run
|
||||||
def _on_node_complete(unique, node_output, node_status):
|
def _on_node_complete(unique, node_output, node_status):
|
||||||
nonlocal header_printed
|
nonlocal header_printed
|
||||||
|
with self.print_lock:
|
||||||
if not header_printed:
|
if not header_printed:
|
||||||
printer.console.print(Rule("OUTPUT", style="header"))
|
printer.console.print(Rule("OUTPUT", style="header"))
|
||||||
header_printed = True
|
header_printed = True
|
||||||
printer.node_panel(unique, node_output, node_status)
|
printer.node_panel(unique, node_output, node_status)
|
||||||
|
|
||||||
self.app.services.execution.run_commands(
|
results = self.app.services.execution.run_commands(
|
||||||
nodes_filter=nodes_filter,
|
nodes_filter=nodes_filter,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
on_node_complete=_on_node_complete
|
on_node_complete=_on_node_complete
|
||||||
)
|
)
|
||||||
|
printer.run_summary(results)
|
||||||
|
|
||||||
except ConnpyError as e:
|
except ConnpyError as e:
|
||||||
printer.error(str(e))
|
printer.error(str(e))
|
||||||
@@ -64,56 +87,80 @@ class RunHandler:
|
|||||||
sys.exit(10)
|
sys.exit(10)
|
||||||
|
|
||||||
def cli_run(self, script):
|
def cli_run(self, script):
|
||||||
|
name = script.get("name", "Task")
|
||||||
try:
|
try:
|
||||||
action = script["action"]
|
action = script["action"]
|
||||||
nodelist = script["nodes"]
|
nodelist = script["nodes"]
|
||||||
commands = script["commands"]
|
commands = script["commands"]
|
||||||
variables = script.get("variables")
|
variables = script.get("variables")
|
||||||
output_cfg = script["output"]
|
output_cfg = script["output"]
|
||||||
name = script.get("name", "Task")
|
|
||||||
options = script.get("options", {})
|
options = script.get("options", {})
|
||||||
except KeyError as e:
|
except KeyError as e:
|
||||||
printer.error(f"'{e.args[0]}' is mandatory in script")
|
printer.error(f"[{name}] '{e.args[0]}' is mandatory in script")
|
||||||
sys.exit(11)
|
sys.exit(11)
|
||||||
|
|
||||||
stdout = (output_cfg == "stdout")
|
stdout = (output_cfg == "stdout")
|
||||||
folder = output_cfg if output_cfg not in [None, "stdout"] else None
|
folder = output_cfg if output_cfg not in [None, "stdout"] else None
|
||||||
prompt = options.get("prompt")
|
prompt = options.get("prompt")
|
||||||
printer.header(name.upper())
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
header_printed = False
|
||||||
if action == "run":
|
if action == "run":
|
||||||
# If stdout is true, we stream results as they arrive
|
# If stdout is true, we stream results as they arrive
|
||||||
on_complete = printer.node_panel if stdout else None
|
def _on_run_complete(unique, node_output, node_status):
|
||||||
|
nonlocal header_printed
|
||||||
|
if stdout:
|
||||||
|
with self.print_lock:
|
||||||
|
if not header_printed:
|
||||||
|
printer.console.print(Rule(name.upper(), style="header"))
|
||||||
|
header_printed = True
|
||||||
|
printer.node_panel(unique, node_output, node_status)
|
||||||
|
|
||||||
results = self.app.services.execution.run_commands(
|
results = self.app.services.execution.run_commands(
|
||||||
nodes_filter=nodelist,
|
nodes_filter=nodelist,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
variables=variables,
|
variables=variables,
|
||||||
parallel=options.get("parallel", 10),
|
parallel=options.get("parallel", 10),
|
||||||
timeout=options.get("timeout", 10),
|
timeout=options.get("timeout", 20),
|
||||||
folder=folder,
|
folder=folder,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
on_node_complete=on_complete
|
on_node_complete=_on_run_complete
|
||||||
)
|
)
|
||||||
# If not streaming, we could print a summary table here if needed
|
# Final Summary
|
||||||
if not stdout:
|
if not stdout and not folder:
|
||||||
for unique, output in results.items():
|
with self.print_lock:
|
||||||
|
printer.console.print(Rule(name.upper(), style="header"))
|
||||||
|
for unique, data in results.items():
|
||||||
|
output = data["output"] if isinstance(data, dict) else data
|
||||||
printer.node_panel(unique, output, 0)
|
printer.node_panel(unique, output, 0)
|
||||||
|
|
||||||
|
# ALWAYS show the aggregate execution summary at the end
|
||||||
|
printer.run_summary(results)
|
||||||
|
|
||||||
elif action == "test":
|
elif action == "test":
|
||||||
expected = script.get("expected", [])
|
expected = script.get("expected", [])
|
||||||
on_complete = printer.test_panel if stdout else None
|
# Show test_panel per node ONLY if stdout is True
|
||||||
|
def _on_test_complete(unique, node_output, node_status, node_result):
|
||||||
|
nonlocal header_printed
|
||||||
|
if stdout:
|
||||||
|
with self.print_lock:
|
||||||
|
if not header_printed:
|
||||||
|
printer.console.print(Rule(name.upper(), style="header"))
|
||||||
|
header_printed = True
|
||||||
|
printer.test_panel(unique, node_output, node_status, node_result)
|
||||||
|
|
||||||
results = self.app.services.execution.test_commands(
|
results = self.app.services.execution.test_commands(
|
||||||
nodes_filter=nodelist,
|
nodes_filter=nodelist,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
expected=expected,
|
expected=expected,
|
||||||
variables=variables,
|
variables=variables,
|
||||||
parallel=options.get("parallel", 10),
|
parallel=options.get("parallel", 10),
|
||||||
timeout=options.get("timeout", 10),
|
timeout=options.get("timeout", 20),
|
||||||
|
folder=folder,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
on_node_complete=on_complete
|
on_node_complete=_on_test_complete
|
||||||
)
|
)
|
||||||
if not stdout:
|
# ALWAYS show the aggregate summary at the end
|
||||||
printer.test_summary(results)
|
printer.test_summary(results)
|
||||||
|
|
||||||
except ConnpyError as e:
|
except ConnpyError as e:
|
||||||
|
|||||||
@@ -0,0 +1,497 @@
|
|||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import asyncio
|
||||||
|
import fcntl
|
||||||
|
import termios
|
||||||
|
import tty
|
||||||
|
from typing import Any, Dict, List, Optional, Callable
|
||||||
|
from textwrap import dedent
|
||||||
|
|
||||||
|
from rich.console import Console
|
||||||
|
from rich.panel import Panel
|
||||||
|
from rich.markdown import Markdown
|
||||||
|
from prompt_toolkit import PromptSession
|
||||||
|
from prompt_toolkit.key_binding import KeyBindings
|
||||||
|
from prompt_toolkit.formatted_text import HTML
|
||||||
|
from prompt_toolkit.history import InMemoryHistory
|
||||||
|
|
||||||
|
from ..printer import connpy_theme
|
||||||
|
from connpy.utils import log_cleaner
|
||||||
|
from ..services.ai_service import AIService
|
||||||
|
|
||||||
|
class CopilotInterface:
|
||||||
|
def __init__(self, config, history=None, pt_input=None, pt_output=None, rich_file=None, session_state=None):
|
||||||
|
self.config = config
|
||||||
|
self.history = history or InMemoryHistory()
|
||||||
|
self.pt_input = pt_input
|
||||||
|
self.pt_output = pt_output
|
||||||
|
self.ai_service = AIService(config)
|
||||||
|
self.session_state = session_state if session_state is not None else {
|
||||||
|
'persona': 'engineer',
|
||||||
|
'trust_mode': False,
|
||||||
|
'memories': [],
|
||||||
|
'os': None,
|
||||||
|
'prompt': None
|
||||||
|
}
|
||||||
|
|
||||||
|
if rich_file:
|
||||||
|
self.console = Console(theme=connpy_theme, force_terminal=True, file=rich_file)
|
||||||
|
else:
|
||||||
|
self.console = Console(theme=connpy_theme)
|
||||||
|
|
||||||
|
self.mode_range, self.mode_single, self.mode_lines = 0, 1, 2
|
||||||
|
|
||||||
|
def _get_theme_color(self, style_name: str, fallback: str = "white") -> str:
|
||||||
|
"""Extract Hex or ANSI color name from the active rich theme."""
|
||||||
|
try:
|
||||||
|
style = connpy_theme.styles.get(style_name)
|
||||||
|
if style and style.color:
|
||||||
|
# If it's a standard color like 'green', Rich might return its hex triplet
|
||||||
|
if style.color.is_default: return fallback
|
||||||
|
return style.color.triplet.hex if style.color.triplet else style.color.name
|
||||||
|
except: pass
|
||||||
|
return fallback
|
||||||
|
|
||||||
|
async def run_session(self,
|
||||||
|
raw_bytes: bytes,
|
||||||
|
node_info: dict,
|
||||||
|
on_ai_call: Callable,
|
||||||
|
cmd_byte_positions: List[tuple] = None,
|
||||||
|
blocks: List[tuple] = None):
|
||||||
|
"""
|
||||||
|
Runs the interactive Copilot session.
|
||||||
|
on_ai_call: async function(active_buffer, question) -> result_dict
|
||||||
|
"""
|
||||||
|
from rich.rule import Rule
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Prepare UI state
|
||||||
|
buffer = log_cleaner(raw_bytes.decode(errors='replace'))
|
||||||
|
|
||||||
|
# Use pre-calculated blocks if provided (remote mode), otherwise calculate locally (local mode)
|
||||||
|
if blocks is None:
|
||||||
|
last_line = buffer.split('\n')[-1].strip() if buffer.strip() else "(prompt)"
|
||||||
|
blocks = self.ai_service.build_context_blocks(raw_bytes, cmd_byte_positions, node_info, last_line=last_line)
|
||||||
|
|
||||||
|
state = {
|
||||||
|
'context_cmd': 1,
|
||||||
|
'total_cmds': len(blocks),
|
||||||
|
'total_lines': len(buffer.split('\n')),
|
||||||
|
'context_lines': min(50, len(buffer.split('\n'))),
|
||||||
|
'context_mode': self.mode_range,
|
||||||
|
'cancelled': False,
|
||||||
|
'toolbar_msg': '',
|
||||||
|
'msg_expiry': 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# 1. Visual Separation
|
||||||
|
self.console.print("") # Salto de línea real
|
||||||
|
self.console.print(Rule(title="[bold cyan] AI TERMINAL COPILOT [/bold cyan]", style="cyan"))
|
||||||
|
self.console.print(Panel(
|
||||||
|
"[dim]Type your question. Enter to send, Escape/Ctrl+C to cancel. Type / for commands.\n"
|
||||||
|
"Tab to change context mode. Ctrl+\u2191/\u2193 to adjust context. \u2191\u2193 for question history.[/dim]",
|
||||||
|
border_style="cyan"
|
||||||
|
))
|
||||||
|
self.console.print("\n") # Pequeño espacio antes del prompt del copilot
|
||||||
|
|
||||||
|
bindings = KeyBindings()
|
||||||
|
@bindings.add('c-up')
|
||||||
|
def _(event):
|
||||||
|
if state['context_mode'] == self.mode_lines:
|
||||||
|
state['context_lines'] = min(state['context_lines'] + 50, state['total_lines'])
|
||||||
|
else:
|
||||||
|
state['context_cmd'] = min(state['context_cmd'] + 1, state['total_cmds'])
|
||||||
|
event.app.invalidate()
|
||||||
|
@bindings.add('c-down')
|
||||||
|
def _(event):
|
||||||
|
if state['context_mode'] == self.mode_lines:
|
||||||
|
state['context_lines'] = max(state['context_lines'] - 50, min(50, state['total_lines']))
|
||||||
|
else:
|
||||||
|
state['context_cmd'] = max(state['context_cmd'] - 1, 1)
|
||||||
|
event.app.invalidate()
|
||||||
|
@bindings.add('tab')
|
||||||
|
def _(event):
|
||||||
|
buf = event.current_buffer
|
||||||
|
# If typing a slash command (no spaces yet), use tab to autocomplete inline
|
||||||
|
if buf.text.startswith('/') and ' ' not in buf.text:
|
||||||
|
buf.complete_next()
|
||||||
|
else:
|
||||||
|
state['context_mode'] = (state['context_mode'] + 1) % 3
|
||||||
|
event.app.invalidate()
|
||||||
|
@bindings.add('escape', eager=True)
|
||||||
|
@bindings.add('c-c')
|
||||||
|
def _(event):
|
||||||
|
state['cancelled'] = True
|
||||||
|
event.app.exit(result='')
|
||||||
|
|
||||||
|
def get_active_buffer():
|
||||||
|
if state['context_mode'] == self.mode_lines:
|
||||||
|
return '\n'.join(buffer.split('\n')[-state['context_lines']:])
|
||||||
|
idx = max(0, state['total_cmds'] - state['context_cmd'])
|
||||||
|
start, end, preview = blocks[idx]
|
||||||
|
if state['context_mode'] == self.mode_single:
|
||||||
|
active_raw = raw_bytes[start:end]
|
||||||
|
else:
|
||||||
|
active_raw = raw_bytes[start:]
|
||||||
|
return preview + "\n" + log_cleaner(active_raw.decode(errors='replace'))
|
||||||
|
|
||||||
|
def get_prompt_text():
|
||||||
|
import html
|
||||||
|
# Always use user_prompt color for the Ask prompt
|
||||||
|
color = self._get_theme_color("user_prompt", "cyan")
|
||||||
|
|
||||||
|
if state['context_mode'] == self.mode_lines:
|
||||||
|
text = html.escape(f"Ask [Ctx: {state['context_lines']}/{state['total_lines']}L]: ")
|
||||||
|
return HTML(f'<style fg="{color}">{text}</style>')
|
||||||
|
active = get_active_buffer()
|
||||||
|
lines_count = len(active.split('\n'))
|
||||||
|
mode_str = {self.mode_range: "Range", self.mode_single: "Cmd"}[state['context_mode']]
|
||||||
|
text = html.escape(f"Ask [{mode_str} {state['context_cmd']} ~{lines_count}L]: ")
|
||||||
|
return HTML(f'<style fg="{color}">{text}</style>')
|
||||||
|
|
||||||
|
from prompt_toolkit.application.current import get_app
|
||||||
|
|
||||||
|
def get_toolbar():
|
||||||
|
import html
|
||||||
|
app = get_app()
|
||||||
|
c_warning = self._get_theme_color("warning", "yellow")
|
||||||
|
|
||||||
|
if app and app.current_buffer:
|
||||||
|
text = app.current_buffer.text
|
||||||
|
# Solo mostrar ayuda de comandos si estamos escribiendo el primer comando y no hay espacios
|
||||||
|
if text.startswith('/') and ' ' not in text:
|
||||||
|
commands = ['/os', '/prompt', '/architect', '/engineer', '/trust', '/untrust', '/memorize', '/clear']
|
||||||
|
matches = [c for c in commands if c.startswith(text.lower())]
|
||||||
|
if matches:
|
||||||
|
m_text = html.escape(f"Available: {' '.join(matches)}")
|
||||||
|
return HTML(f'<style fg="{c_warning}">{m_text}</style>' + " " * 20)
|
||||||
|
|
||||||
|
m_label = {self.mode_range: "RANGE", self.mode_single: "SINGLE", self.mode_lines: "LINES"}[state['context_mode']]
|
||||||
|
if state['context_mode'] == self.mode_lines:
|
||||||
|
base_str = f'\u25b6 Ctrl+\u2191/\u2193 adjusts by 50 lines [Tab: {m_label}]'
|
||||||
|
else:
|
||||||
|
idx = max(0, state['total_cmds'] - state['context_cmd'])
|
||||||
|
|
||||||
|
def clean_preview(text):
|
||||||
|
# Limpia saltos de línea y el prompt inicial (todo hasta #, > o $) para que quede solo el comando
|
||||||
|
original = text.strip().replace('\r', '').replace('\n', ' ')
|
||||||
|
cleaned = re.sub(r'^.*?[#>\$]\s*', '', original)
|
||||||
|
# Si limpiar el prompt nos deja con un string vacío (ej: era solo "iol#"), devolvemos el original
|
||||||
|
return cleaned if cleaned else original
|
||||||
|
|
||||||
|
if state['context_mode'] == self.mode_range:
|
||||||
|
range_blocks = blocks[idx:]
|
||||||
|
# Si hay más de un bloque, el último es siempre el prompt vacío/actual. Lo omitimos visualmente.
|
||||||
|
if len(range_blocks) > 1:
|
||||||
|
range_blocks = range_blocks[:-1]
|
||||||
|
|
||||||
|
# Limpiar y truncar comandos muy largos para que no rompan la UI
|
||||||
|
previews = []
|
||||||
|
for b in range_blocks:
|
||||||
|
p = clean_preview(b[2])
|
||||||
|
if p:
|
||||||
|
# Truncar comandos individuales largos
|
||||||
|
if len(p) > 25: p = p[:22] + "..."
|
||||||
|
previews.append(p)
|
||||||
|
|
||||||
|
if not previews:
|
||||||
|
desc = clean_preview(blocks[idx][2])
|
||||||
|
elif len(previews) <= 3:
|
||||||
|
desc = " + ".join(previews)
|
||||||
|
else:
|
||||||
|
desc = f"{previews[0]} + {previews[1]} + {previews[2]} ... (+{len(previews)-3})"
|
||||||
|
else:
|
||||||
|
# Modo SINGLE original
|
||||||
|
desc = clean_preview(blocks[idx][2])
|
||||||
|
|
||||||
|
base_str = f'\u25b6 {desc} [Tab: {m_label}]'
|
||||||
|
|
||||||
|
# Wrap base_str in a style to maintain consistency and avoid glitches
|
||||||
|
# The fg color will be inherited from bottom-toolbar global style if not specified here
|
||||||
|
base_html = f'<span>{html.escape(base_str)}</span>'
|
||||||
|
|
||||||
|
res_html = base_html
|
||||||
|
if state.get('toolbar_msg'):
|
||||||
|
if time.time() < state.get('msg_expiry', 0):
|
||||||
|
msg = html.escape(state['toolbar_msg'])
|
||||||
|
res_html = f'<style fg="{c_warning}">⚙️ {msg}</style> | ' + base_html
|
||||||
|
else:
|
||||||
|
state['toolbar_msg'] = ''
|
||||||
|
|
||||||
|
# Pad with spaces to ensure the line is cleared when the message disappears
|
||||||
|
return HTML(res_html + " " * 20)
|
||||||
|
|
||||||
|
from prompt_toolkit.completion import Completer, Completion
|
||||||
|
class SlashCommandCompleter(Completer):
|
||||||
|
def get_completions(self, document, complete_event):
|
||||||
|
text = document.text_before_cursor
|
||||||
|
if text.startswith('/'):
|
||||||
|
parts = text.split()
|
||||||
|
# Only autocomplete the first word
|
||||||
|
if len(parts) <= 1 or (len(parts) == 1 and not text.endswith(' ')):
|
||||||
|
cmd_part = parts[0] if parts else text
|
||||||
|
commands = [
|
||||||
|
('/os', 'Set device OS (e.g. cisco_ios)'),
|
||||||
|
('/prompt', 'Override prompt regex'),
|
||||||
|
('/architect', 'Switch to Architect persona'),
|
||||||
|
('/engineer', 'Switch to Engineer persona'),
|
||||||
|
('/trust', 'Enable auto-execute'),
|
||||||
|
('/untrust', 'Disable auto-execute'),
|
||||||
|
('/memorize', 'Add fact to memory'),
|
||||||
|
('/clear', 'Clear memory')
|
||||||
|
]
|
||||||
|
for cmd, desc in commands:
|
||||||
|
if cmd.startswith(cmd_part.lower()):
|
||||||
|
yield Completion(cmd, start_position=-len(cmd_part), display_meta=desc)
|
||||||
|
|
||||||
|
copilot_completer = SlashCommandCompleter()
|
||||||
|
|
||||||
|
while True:
|
||||||
|
# 2. Ask question
|
||||||
|
from prompt_toolkit.styles import Style
|
||||||
|
c_contrast = self._get_theme_color("contrast", "gray")
|
||||||
|
ui_style = Style.from_dict({
|
||||||
|
'bottom-toolbar': f'fg:{c_contrast}',
|
||||||
|
})
|
||||||
|
|
||||||
|
session = PromptSession(
|
||||||
|
history=self.history,
|
||||||
|
input=self.pt_input,
|
||||||
|
output=self.pt_output,
|
||||||
|
completer=copilot_completer,
|
||||||
|
reserve_space_for_menu=0,
|
||||||
|
style=ui_style
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
# Usamos un try/finally interno para asegurar que si algo falla en prompt_async,
|
||||||
|
# no nos quedemos con la terminal en un estado extraño.
|
||||||
|
question = await session.prompt_async(
|
||||||
|
get_prompt_text,
|
||||||
|
key_bindings=bindings,
|
||||||
|
bottom_toolbar=get_toolbar
|
||||||
|
)
|
||||||
|
except (KeyboardInterrupt, EOFError):
|
||||||
|
state['cancelled'] = True
|
||||||
|
question = ""
|
||||||
|
|
||||||
|
if state['cancelled'] or not question.strip() or question.strip().lower() in ['cancel', 'exit', 'quit']:
|
||||||
|
return "cancel", None, None
|
||||||
|
|
||||||
|
# 3. Process Input via AIService
|
||||||
|
directive = self.ai_service.process_copilot_input(question, self.session_state)
|
||||||
|
|
||||||
|
if directive["action"] == "state_update":
|
||||||
|
state['toolbar_msg'] = directive['message']
|
||||||
|
state['msg_expiry'] = time.time() + 3 # 3 seconds timeout
|
||||||
|
|
||||||
|
async def delayed_refresh():
|
||||||
|
await asyncio.sleep(3.1)
|
||||||
|
# Only invalidate if the message hasn't been replaced by a newer one
|
||||||
|
if state.get('toolbar_msg') == directive['message']:
|
||||||
|
state['toolbar_msg'] = '' # Explicitly clear
|
||||||
|
try:
|
||||||
|
from prompt_toolkit.application.current import get_app
|
||||||
|
app = get_app()
|
||||||
|
if app: app.invalidate()
|
||||||
|
except: pass
|
||||||
|
asyncio.create_task(delayed_refresh())
|
||||||
|
|
||||||
|
# Mover el cursor arriba y limpiar la línea para que el nuevo prompt reemplace al anterior
|
||||||
|
sys.stdout.write('\x1b[1A\x1b[2K')
|
||||||
|
sys.stdout.flush()
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
# Limpiar el mensaje de la barra cuando se hace una pregunta real
|
||||||
|
state['toolbar_msg'] = ''
|
||||||
|
|
||||||
|
clean_question = directive.get("clean_prompt", question)
|
||||||
|
overrides = directive.get("overrides", {})
|
||||||
|
|
||||||
|
# Merge node_info with session_state and overrides
|
||||||
|
merged_node_info = node_info.copy()
|
||||||
|
if self.session_state['os']: merged_node_info['os'] = self.session_state['os']
|
||||||
|
if self.session_state['prompt']: merged_node_info['prompt'] = self.session_state['prompt']
|
||||||
|
merged_node_info['persona'] = self.session_state['persona']
|
||||||
|
merged_node_info['trust'] = self.session_state['trust_mode']
|
||||||
|
merged_node_info['memories'] = list(self.session_state['memories'])
|
||||||
|
|
||||||
|
for k, v in overrides.items():
|
||||||
|
merged_node_info[k] = v
|
||||||
|
|
||||||
|
# Enrich question
|
||||||
|
past = self.history.get_strings()
|
||||||
|
if len(past) > 1:
|
||||||
|
clean_past = [q for q in past[-6:-1] if not q.startswith('/')]
|
||||||
|
if clean_past:
|
||||||
|
history_text = "\n".join(f"- {q}" for q in clean_past)
|
||||||
|
clean_question = f"Previous questions:\n{history_text}\n\nCurrent Question:\n{clean_question}"
|
||||||
|
|
||||||
|
# 3. AI Execution
|
||||||
|
# Use persona from overrides (one-shot) or from session state
|
||||||
|
active_persona = merged_node_info.get('persona', self.session_state.get('persona', 'engineer'))
|
||||||
|
persona_color = self._get_theme_color(active_persona, fallback="cyan")
|
||||||
|
persona_title = "Network Architect" if active_persona == "architect" else "Network Engineer"
|
||||||
|
|
||||||
|
active_buffer = get_active_buffer()
|
||||||
|
live_text = ""
|
||||||
|
first_chunk = True
|
||||||
|
|
||||||
|
from rich.rule import Rule
|
||||||
|
from rich.status import Status
|
||||||
|
from connpy.printer import IncrementalMarkdownParser
|
||||||
|
|
||||||
|
md_parser = IncrementalMarkdownParser(console=self.console)
|
||||||
|
|
||||||
|
status_spinner = Status(
|
||||||
|
f"[bold {persona_color}]{persona_title}:[/bold {persona_color}] [dim]Thinking...[/dim]",
|
||||||
|
console=self.console,
|
||||||
|
spinner="dots"
|
||||||
|
)
|
||||||
|
status_spinner.start()
|
||||||
|
|
||||||
|
def on_chunk(text):
|
||||||
|
nonlocal live_text, first_chunk
|
||||||
|
if first_chunk:
|
||||||
|
status_spinner.stop()
|
||||||
|
# Print header rule before first chunk arrives
|
||||||
|
self.console.print(Rule(
|
||||||
|
f"[bold {persona_color}]{persona_title}[/bold {persona_color}]",
|
||||||
|
style=persona_color
|
||||||
|
))
|
||||||
|
first_chunk = False
|
||||||
|
live_text += text
|
||||||
|
md_parser.feed(text)
|
||||||
|
|
||||||
|
# Check for interruption during AI call
|
||||||
|
ai_task = asyncio.create_task(on_ai_call(active_buffer, clean_question, on_chunk, merged_node_info))
|
||||||
|
|
||||||
|
try:
|
||||||
|
while not ai_task.done():
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
result = await ai_task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
status_spinner.stop()
|
||||||
|
return "cancel", None, None
|
||||||
|
|
||||||
|
# Ensure spinner is stopped if no chunks arrived
|
||||||
|
if first_chunk:
|
||||||
|
status_spinner.stop()
|
||||||
|
|
||||||
|
# Close the streamed output with a Rule
|
||||||
|
if not first_chunk:
|
||||||
|
md_parser.flush()
|
||||||
|
self.console.print(Rule(style=persona_color))
|
||||||
|
|
||||||
|
if not result or result.get("error"):
|
||||||
|
if first_chunk and result and result.get("error"):
|
||||||
|
self.console.print(f"[red]Error: {result['error']}[/red]")
|
||||||
|
return "cancel", None, None
|
||||||
|
|
||||||
|
# If no chunks were streamed but we have a guide, print it as a panel
|
||||||
|
if first_chunk and result and result.get("guide"):
|
||||||
|
self.console.print(Panel(Markdown(result["guide"]), title=f"[bold {persona_color}]{persona_title}[/bold {persona_color}]", border_style=persona_color))
|
||||||
|
|
||||||
|
commands = result.get("commands", [])
|
||||||
|
if not commands:
|
||||||
|
self.console.print("")
|
||||||
|
return "continue", None, None
|
||||||
|
|
||||||
|
risk = result.get("risk_level", "low")
|
||||||
|
risk_style = {"low": "success", "high": "warning", "destructive": "error"}.get(risk, "success")
|
||||||
|
style_color = self._get_theme_color(risk_style, fallback="green")
|
||||||
|
|
||||||
|
cmd_text = "\n".join(f" {i+1}. {c}" for i, c in enumerate(commands))
|
||||||
|
# Explicitly use 'bold style_color' for both TITLE and BORDER to ensure maximum consistency
|
||||||
|
self.console.print(Panel(cmd_text, title=f"[bold {style_color}]Suggested Commands [{risk.upper()}][/bold {style_color}]", border_style=f"bold {style_color}"))
|
||||||
|
|
||||||
|
if merged_node_info.get('trust', False) and risk != "destructive":
|
||||||
|
self.console.print(f"[dim]⚙️ Auto-executing (Trust Mode)[/dim]")
|
||||||
|
return "send_all", commands, None
|
||||||
|
|
||||||
|
confirm_session = PromptSession(input=self.pt_input, output=self.pt_output)
|
||||||
|
c_bindings = KeyBindings()
|
||||||
|
@c_bindings.add('escape', eager=True)
|
||||||
|
@c_bindings.add('c-c')
|
||||||
|
def _(ev): ev.app.exit(result='n')
|
||||||
|
|
||||||
|
import html
|
||||||
|
try:
|
||||||
|
p_text = html.escape(f"Send? (y/n/e/range) [n]: ")
|
||||||
|
# Use the EXACT same style_color and force bold="true" for Prompt-Toolkit
|
||||||
|
action = await confirm_session.prompt_async(HTML(f'<style fg="{style_color}" bold="true">{p_text}</style>'), key_bindings=c_bindings)
|
||||||
|
except (KeyboardInterrupt, EOFError):
|
||||||
|
self.console.print("")
|
||||||
|
return "continue", None, None
|
||||||
|
|
||||||
|
def parse_indices(text, max_len):
|
||||||
|
"""Helper to parse '1-3, 5, 7' into [0, 1, 2, 4, 6]."""
|
||||||
|
indices = []
|
||||||
|
# Replace commas with spaces and split
|
||||||
|
parts = text.replace(',', ' ').split()
|
||||||
|
for part in parts:
|
||||||
|
if '-' in part:
|
||||||
|
try:
|
||||||
|
start, end = map(int, part.split('-'))
|
||||||
|
# Ensure inclusive and 0-indexed
|
||||||
|
indices.extend(range(start-1, end))
|
||||||
|
except: continue
|
||||||
|
elif part.isdigit():
|
||||||
|
indices.append(int(part)-1)
|
||||||
|
# Filter valid indices and remove duplicates
|
||||||
|
return [i for i in sorted(set(indices)) if 0 <= i < max_len]
|
||||||
|
|
||||||
|
action_l = (action or "n").lower().strip()
|
||||||
|
if action_l in ('y', 'yes', 'all'):
|
||||||
|
return "send_all", commands, None
|
||||||
|
|
||||||
|
# Check for numeric selection (e.g., "1, 2-4")
|
||||||
|
if re.match(r'^[0-9,\-\s]+$', action_l):
|
||||||
|
selected_idxs = parse_indices(action_l, len(commands))
|
||||||
|
if selected_idxs:
|
||||||
|
return "send_all", [commands[i] for i in selected_idxs], None
|
||||||
|
|
||||||
|
elif action_l.startswith('e'):
|
||||||
|
# Check if it's a selective edit like 'e1-2'
|
||||||
|
selection_str = action_l[1:].strip()
|
||||||
|
if selection_str:
|
||||||
|
idxs = parse_indices(selection_str, len(commands))
|
||||||
|
cmds_to_edit = [commands[i] for i in idxs] if idxs else commands
|
||||||
|
else:
|
||||||
|
cmds_to_edit = commands
|
||||||
|
|
||||||
|
target = "\n".join(cmds_to_edit)
|
||||||
|
e_bindings = KeyBindings()
|
||||||
|
@e_bindings.add('c-j')
|
||||||
|
def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
|
||||||
|
@e_bindings.add('escape', 'enter')
|
||||||
|
def _(ev): ev.app.exit(result=ev.app.current_buffer.text)
|
||||||
|
@e_bindings.add('escape')
|
||||||
|
def _(ev): ev.app.exit(result='')
|
||||||
|
|
||||||
|
c_edit = self._get_theme_color("user_prompt", "cyan")
|
||||||
|
import html
|
||||||
|
e_text = html.escape("Edit (Ctrl+Enter or Esc+Enter to submit):\n")
|
||||||
|
try:
|
||||||
|
edited = await confirm_session.prompt_async(
|
||||||
|
HTML(f'<style fg="{c_edit}">{e_text}</style>'),
|
||||||
|
default=target, multiline=True, key_bindings=e_bindings
|
||||||
|
)
|
||||||
|
except (KeyboardInterrupt, EOFError):
|
||||||
|
self.console.print("")
|
||||||
|
return "continue", None, None
|
||||||
|
|
||||||
|
if edited and edited.strip():
|
||||||
|
# Split by lines to ensure core.py applies delay between each command
|
||||||
|
lines = [l.strip() for l in edited.split('\n') if l.strip()]
|
||||||
|
return "custom", None, lines
|
||||||
|
|
||||||
|
self.console.print("")
|
||||||
|
return "continue", None, None
|
||||||
|
|
||||||
|
return "cancel", None, None
|
||||||
|
|
||||||
|
finally:
|
||||||
|
state['cancelled'] = True
|
||||||
|
|
||||||
+59
-6
@@ -147,18 +147,43 @@ def _build_tree(nodes, folders, profiles, plugins, configdir):
|
|||||||
"__extra__": lambda w: get_cwd(w, "import")
|
"__extra__": lambda w: get_cwd(w, "import")
|
||||||
})
|
})
|
||||||
|
|
||||||
run_dict = {"--generate": None, "--help": None, "-g": None, "-h": None}
|
# --- Run Loop ---
|
||||||
run_dict.update({
|
# After the first positional argument (Node filter or YAML file),
|
||||||
"*": run_dict,
|
# we stop suggesting nodes and only allow flags or commands.
|
||||||
"__extra__": lambda w: get_cwd(w, "run") + list(nodes)
|
run_after_node = {"--help": None, "-h": None}
|
||||||
|
run_after_node.update({
|
||||||
|
"--test": {"*": run_after_node},
|
||||||
|
"-t": {"*": run_after_node},
|
||||||
|
"*": run_after_node # Consume commands
|
||||||
})
|
})
|
||||||
|
|
||||||
|
run_dict = {
|
||||||
|
"--generate": {"__extra__": lambda w: get_cwd(w, "--generate")},
|
||||||
|
"-g": {"__extra__": lambda w: get_cwd(w, "-g")},
|
||||||
|
"--test": {"*": None},
|
||||||
|
"-t": {"*": None},
|
||||||
|
"--help": None,
|
||||||
|
"-h": None,
|
||||||
|
"__extra__": lambda w: get_cwd(w, "run") + list(nodes),
|
||||||
|
"*": run_after_node
|
||||||
|
}
|
||||||
|
|
||||||
# State Machine Definitions
|
# State Machine Definitions
|
||||||
|
mcp_dict = {
|
||||||
|
"list": None,
|
||||||
|
"add": {"*": {"*": {"*": None}}}, # name url [os]
|
||||||
|
"remove": {"*": None},
|
||||||
|
"enable": {"*": None},
|
||||||
|
"disable": {"*": None},
|
||||||
|
"--help": None, "-h": None
|
||||||
|
}
|
||||||
|
|
||||||
ai_dict = {"__exclude_used__": True, "--help": None, "-h": None}
|
ai_dict = {"__exclude_used__": True, "--help": None, "-h": None}
|
||||||
for opt in ["--engineer-model", "--engineer-api-key", "--architect-model", "--architect-api-key"]:
|
for opt in ["--engineer-model", "--engineer-api-key", "--architect-model", "--architect-api-key"]:
|
||||||
ai_dict[opt] = {"*": ai_dict} # takes value, loops back
|
ai_dict[opt] = {"*": ai_dict} # takes value, loops back
|
||||||
for opt in ["--debug", "--trust", "--list", "--list-sessions", "--session", "--resume", "--delete", "--delete-session", "-y"]:
|
for opt in ["--debug", "--trust", "--list", "--list-sessions", "--session", "--resume", "--delete", "--delete-session", "-y"]:
|
||||||
ai_dict[opt] = ai_dict # takes no value, loops back
|
ai_dict[opt] = ai_dict # takes no value, loops back
|
||||||
|
ai_dict["--mcp"] = mcp_dict
|
||||||
ai_dict["*"] = ai_dict
|
ai_dict["*"] = ai_dict
|
||||||
|
|
||||||
mv_state = {"__extra__": _nodes, "--help": None, "-h": None}
|
mv_state = {"__extra__": _nodes, "--help": None, "-h": None}
|
||||||
@@ -169,9 +194,37 @@ def _build_tree(nodes, folders, profiles, plugins, configdir):
|
|||||||
"folders": None,
|
"folders": None,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# --- Connect (default command) ---
|
||||||
|
# Long flags are offered; short forms (-d/-t) only used for navigation.
|
||||||
|
# Two states: before node (offer nodes + remaining long flags)
|
||||||
|
# after node (offer only remaining long flags, no more nodes)
|
||||||
|
connect_flags_long = ["--debug", "--sftp"]
|
||||||
|
connect_flags_all = ["--debug", "-d", "--sftp", "-t"]
|
||||||
|
|
||||||
|
# Post-node: only offer remaining long flags
|
||||||
|
connect_after_node = {"__exclude_used__": True}
|
||||||
|
for f in connect_flags_all:
|
||||||
|
connect_after_node[f] = connect_after_node
|
||||||
|
|
||||||
|
# Pre-node: offer nodes + remaining long flags, consume node → post-node state
|
||||||
|
connect_dict = {"__exclude_used__": True}
|
||||||
|
connect_dict["__extra__"] = lambda w: (
|
||||||
|
list(nodes) + list(folders) + (list(plugins.keys()) if plugins else [])
|
||||||
|
)
|
||||||
|
connect_dict["*"] = connect_after_node
|
||||||
|
for f in connect_flags_all:
|
||||||
|
connect_dict[f] = connect_dict
|
||||||
|
|
||||||
# --- Main Tree ---
|
# --- Main Tree ---
|
||||||
return {
|
return {
|
||||||
|
# Root: offer nodes + long flags; after a node go to post-node state
|
||||||
"__extra__": lambda w: list(nodes) + list(folders) + (list(plugins.keys()) if plugins else []),
|
"__extra__": lambda w: list(nodes) + list(folders) + (list(plugins.keys()) if plugins else []),
|
||||||
|
"*": connect_after_node,
|
||||||
|
|
||||||
|
"--debug": connect_dict,
|
||||||
|
"-d": connect_dict,
|
||||||
|
"--sftp": connect_dict,
|
||||||
|
"-t": connect_dict,
|
||||||
|
|
||||||
"--add": {"profile": _profile_values},
|
"--add": {"profile": _profile_values},
|
||||||
"--del": {"profile": _profile_values, "__extra__": _nodes_folders},
|
"--del": {"profile": _profile_values, "__extra__": _nodes_folders},
|
||||||
@@ -219,8 +272,8 @@ def _build_tree(nodes, folders, profiles, plugins, configdir):
|
|||||||
"-a": None, "-r": None, "-s": None, "-e": None, "-h": None,
|
"-a": None, "-r": None, "-s": None, "-e": None, "-h": None,
|
||||||
},
|
},
|
||||||
"plugin": {
|
"plugin": {
|
||||||
"--add": lambda w: get_cwd(w, "--add"),
|
"--add": {"*": lambda w: get_cwd(w, "--add")},
|
||||||
"--update": lambda w: get_cwd(w, "--update"),
|
"--update": {"*": lambda w: get_cwd(w, "--update")},
|
||||||
"--del": lambda w: _get_plugins("--del", configdir),
|
"--del": lambda w: _get_plugins("--del", configdir),
|
||||||
"--enable": lambda w: _get_plugins("--enable", configdir),
|
"--enable": lambda w: _get_plugins("--enable", configdir),
|
||||||
"--disable": lambda w: _get_plugins("--disable", configdir),
|
"--disable": lambda w: _get_plugins("--disable", configdir),
|
||||||
|
|||||||
+16
-17
@@ -400,15 +400,7 @@ class configfile:
|
|||||||
if isinstance(uniques, str):
|
if isinstance(uniques, str):
|
||||||
uniques = [uniques]
|
uniques = [uniques]
|
||||||
for i in uniques:
|
for i in uniques:
|
||||||
if isinstance(i, dict):
|
if i.startswith("@"):
|
||||||
name = list(i.keys())[0]
|
|
||||||
mylist = i[name]
|
|
||||||
if not self.config["case"]:
|
|
||||||
name = name.lower()
|
|
||||||
mylist = [item.lower() for item in mylist]
|
|
||||||
this = self.getitem(name, mylist, extract = extract)
|
|
||||||
nodes.update(this)
|
|
||||||
elif i.startswith("@"):
|
|
||||||
if not self.config["case"]:
|
if not self.config["case"]:
|
||||||
i = i.lower()
|
i = i.lower()
|
||||||
this = self.getitem(i, extract = extract)
|
this = self.getitem(i, extract = extract)
|
||||||
@@ -487,13 +479,17 @@ class configfile:
|
|||||||
layer3 = [k + "@" + s + "@" + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get("type") == "connection"]
|
layer3 = [k + "@" + s + "@" + f for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get("type") == "connection"]
|
||||||
nodes.extend(layer3)
|
nodes.extend(layer3)
|
||||||
if filter:
|
if filter:
|
||||||
|
flat_filter = []
|
||||||
if isinstance(filter, str):
|
if isinstance(filter, str):
|
||||||
nodes = [item for item in nodes if re.search(filter, item)]
|
flat_filter = [filter]
|
||||||
elif isinstance(filter, list):
|
elif isinstance(filter, list):
|
||||||
nodes = [item for item in nodes if any(re.search(pattern, item) for pattern in filter)]
|
for item in filter:
|
||||||
|
if isinstance(item, str):
|
||||||
|
flat_filter.append(item)
|
||||||
else:
|
else:
|
||||||
printer.error("Invalid filter: must be a string or a list of strings.")
|
printer.error("Filter must be a string or a list of strings")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
nodes = [item for item in nodes if any(re.search(pattern, item) for pattern in flat_filter)]
|
||||||
return nodes
|
return nodes
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
@@ -511,15 +507,18 @@ class configfile:
|
|||||||
layer3 = {k + "@" + s + "@" + f:v for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get("type") == "connection"}
|
layer3 = {k + "@" + s + "@" + f:v for k,v in self.connections[f][s].items() if isinstance(v, dict) and v.get("type") == "connection"}
|
||||||
nodes.update(layer3)
|
nodes.update(layer3)
|
||||||
if filter:
|
if filter:
|
||||||
|
flat_filter = []
|
||||||
if isinstance(filter, str):
|
if isinstance(filter, str):
|
||||||
filter = "^(?!.*@).+$" if filter == "@" else filter
|
flat_filter = [filter]
|
||||||
nodes = {k: v for k, v in nodes.items() if re.search(filter, k)}
|
|
||||||
elif isinstance(filter, list):
|
elif isinstance(filter, list):
|
||||||
filter = ["^(?!.*@).+$" if item == "@" else item for item in filter]
|
for item in filter:
|
||||||
nodes = {k: v for k, v in nodes.items() if any(re.search(pattern, k) for pattern in filter)}
|
if isinstance(item, str):
|
||||||
|
flat_filter.append(item)
|
||||||
else:
|
else:
|
||||||
printer.error("Invalid filter: must be a string or a list of strings.")
|
printer.error("Filter must be a string or a list of strings")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
flat_filter = ["^(?!.*@).+$" if item == "@" 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:
|
if extract:
|
||||||
for node, keys in nodes.items():
|
for node, keys in nodes.items():
|
||||||
for key, value in keys.items():
|
for key, value in keys.items():
|
||||||
|
|||||||
+13
-4
@@ -89,6 +89,10 @@ class connapp:
|
|||||||
if hasattr(self.services.nodes, "list_folders") and hasattr(self.services.nodes.list_folders, "register_post_hook"):
|
if hasattr(self.services.nodes, "list_folders") and hasattr(self.services.nodes.list_folders, "register_post_hook"):
|
||||||
self.services.nodes.list_folders.register_post_hook(self.services.context.filter_node_list)
|
self.services.nodes.list_folders.register_post_hook(self.services.context.filter_node_list)
|
||||||
|
|
||||||
|
# Apply theme from config if exists before remote connection attempts
|
||||||
|
user_theme = self.config.config.get("theme", {})
|
||||||
|
self._apply_app_theme(user_theme)
|
||||||
|
|
||||||
# Populate data via services
|
# Populate data via services
|
||||||
try:
|
try:
|
||||||
self.nodes_list = self.services.nodes.list_nodes()
|
self.nodes_list = self.services.nodes.list_nodes()
|
||||||
@@ -152,10 +156,6 @@ class connapp:
|
|||||||
|
|
||||||
configfile._saveconfig.register_post_hook(auto_sync_hook)
|
configfile._saveconfig.register_post_hook(auto_sync_hook)
|
||||||
|
|
||||||
# Apply theme from config if exists
|
|
||||||
user_theme = self.config.config.get("theme", {})
|
|
||||||
self._apply_app_theme(user_theme)
|
|
||||||
|
|
||||||
def _apply_app_theme(self, styles):
|
def _apply_app_theme(self, styles):
|
||||||
"""Unified method to apply theme to printer and help formatter."""
|
"""Unified method to apply theme to printer and help formatter."""
|
||||||
active_styles = printer.apply_theme(styles)
|
active_styles = printer.apply_theme(styles)
|
||||||
@@ -284,11 +284,13 @@ class connapp:
|
|||||||
aiparser.add_argument("--session", nargs=1, help="Resume a specific AI session by ID")
|
aiparser.add_argument("--session", nargs=1, help="Resume a specific AI session by ID")
|
||||||
aiparser.add_argument("--resume", action="store_true", help="Resume the most recent AI session")
|
aiparser.add_argument("--resume", action="store_true", help="Resume the most recent AI session")
|
||||||
aiparser.add_argument("--delete", "--delete-session", dest="delete_session", nargs=1, help="Delete an AI session by ID")
|
aiparser.add_argument("--delete", "--delete-session", dest="delete_session", nargs=1, help="Delete an AI session by ID")
|
||||||
|
aiparser.add_argument("--mcp", nargs='*', metavar=('ACTION', 'NAME'), help="Manage MCP servers. Actions: list, add, remove, enable, disable. Leave empty for interactive wizard.")
|
||||||
aiparser.set_defaults(func=self._ai.dispatch)
|
aiparser.set_defaults(func=self._ai.dispatch)
|
||||||
#RUNPARSER
|
#RUNPARSER
|
||||||
runparser = subparsers.add_parser("run", help="Run scripts or commands on nodes", description="Run scripts or commands on nodes", formatter_class=RichHelpFormatter)
|
runparser = subparsers.add_parser("run", help="Run scripts or commands on nodes", description="Run scripts or commands on nodes", formatter_class=RichHelpFormatter)
|
||||||
runparser.error = self._custom_error
|
runparser.error = self._custom_error
|
||||||
runparser.add_argument("run", nargs='+', action=self._store_type, help=get_help("run"), default="run").completer = nodes_completer
|
runparser.add_argument("run", nargs='+', action=self._store_type, help=get_help("run"), default="run").completer = nodes_completer
|
||||||
|
runparser.add_argument("-t", "--test", dest="test_expected", nargs='+', help="Expected text(s) to validate in output. Converts the action from 'run' to 'test'")
|
||||||
runparser.add_argument("-g","--generate", dest="action", action="store_const", help="Generate yaml file template", const="generate", default="run")
|
runparser.add_argument("-g","--generate", dest="action", action="store_const", help="Generate yaml file template", const="generate", default="run")
|
||||||
runparser.set_defaults(func=self._run.dispatch)
|
runparser.set_defaults(func=self._run.dispatch)
|
||||||
#APIPARSER
|
#APIPARSER
|
||||||
@@ -469,6 +471,13 @@ class connapp:
|
|||||||
# Handle global Ctrl+C gracefully
|
# Handle global Ctrl+C gracefully
|
||||||
printer.warning("Operation cancelled by user.")
|
printer.warning("Operation cancelled by user.")
|
||||||
sys.exit(130)
|
sys.exit(130)
|
||||||
|
finally:
|
||||||
|
# Safely cleanup AI sessions (litellm)
|
||||||
|
try:
|
||||||
|
from .ai import cleanup
|
||||||
|
cleanup()
|
||||||
|
except ImportError:
|
||||||
|
pass
|
||||||
|
|
||||||
class _store_type(argparse.Action):
|
class _store_type(argparse.Action):
|
||||||
#Custom store type for cli app.
|
#Custom store type for cli app.
|
||||||
|
|||||||
+516
-52
@@ -14,8 +14,33 @@ from pathlib import Path
|
|||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from .hooks import ClassHook, MethodHook
|
from .hooks import ClassHook, MethodHook
|
||||||
import io
|
import io
|
||||||
|
import asyncio
|
||||||
|
import fcntl
|
||||||
from . import printer
|
from . import printer
|
||||||
|
from .tunnels import LocalStream
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def copilot_terminal_mode():
|
||||||
|
import sys, tty, termios
|
||||||
|
fd = sys.stdin.fileno()
|
||||||
|
try:
|
||||||
|
old_settings = termios.tcgetattr(fd)
|
||||||
|
|
||||||
|
# Primero pasamos a raw mode absoluto para matar ISIG, ICANON, ECHO, etc.
|
||||||
|
tty.setraw(fd)
|
||||||
|
|
||||||
|
# Luego rehabilitamos OPOST para que rich.Live se dibuje correctamente
|
||||||
|
new_settings = termios.tcgetattr(fd)
|
||||||
|
new_settings[1] = new_settings[1] | termios.OPOST
|
||||||
|
termios.tcsetattr(fd, termios.TCSANOW, new_settings)
|
||||||
|
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
termios.tcsetattr(fd, termios.TCSANOW, old_settings)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
#functions and classes
|
#functions and classes
|
||||||
@ClassHook
|
@ClassHook
|
||||||
@@ -72,6 +97,7 @@ class node:
|
|||||||
|
|
||||||
- jumphost (str): Reference another node to be used as a jumphost
|
- jumphost (str): Reference another node to be used as a jumphost
|
||||||
'''
|
'''
|
||||||
|
self.config = config
|
||||||
if config == '':
|
if config == '':
|
||||||
self.idletime = 0
|
self.idletime = 0
|
||||||
self.key = None
|
self.key = None
|
||||||
@@ -143,9 +169,50 @@ class node:
|
|||||||
else:
|
else:
|
||||||
jumphost_cmd = jumphost_cmd + " {}".format("@".join([self.jumphost["user"],self.jumphost["host"]]))
|
jumphost_cmd = jumphost_cmd + " {}".format("@".join([self.jumphost["user"],self.jumphost["host"]]))
|
||||||
self.jumphost = f"-o ProxyCommand=\"{jumphost_cmd}\""
|
self.jumphost = f"-o ProxyCommand=\"{jumphost_cmd}\""
|
||||||
|
elif self.jumphost["protocol"] == "ssm":
|
||||||
|
ssm_target = self.jumphost["host"]
|
||||||
|
ssm_cmd = f"aws ssm start-session --target {ssm_target} --document-name AWS-StartSSHSession --parameters 'portNumber=22'"
|
||||||
|
if isinstance(self.jumphost.get("tags"), dict):
|
||||||
|
if "profile" in self.jumphost["tags"]:
|
||||||
|
ssm_cmd += f" --profile {self.jumphost['tags']['profile']}"
|
||||||
|
if "region" in self.jumphost["tags"]:
|
||||||
|
ssm_cmd += f" --region {self.jumphost['tags']['region']}"
|
||||||
|
if self.jumphost["options"] != '':
|
||||||
|
ssm_cmd += f" {self.jumphost['options']}"
|
||||||
|
|
||||||
|
bastion_user_part = f"{self.jumphost['user']}@{ssm_target}" if self.jumphost['user'] else ssm_target
|
||||||
|
|
||||||
|
ssh_opts = ""
|
||||||
|
if isinstance(self.jumphost.get("tags"), dict) and "ssh_options" in self.jumphost["tags"]:
|
||||||
|
ssh_opts = f" {self.jumphost['tags']['ssh_options']}"
|
||||||
|
|
||||||
|
inner_ssh = f"ssh{ssh_opts} -o ProxyCommand='{ssm_cmd}' -W %h:%p {bastion_user_part}"
|
||||||
|
self.jumphost = f"-o ProxyCommand=\"{inner_ssh}\""
|
||||||
|
elif self.jumphost["protocol"] in ["kubectl", "docker"]:
|
||||||
|
nc_cmd = "nc"
|
||||||
|
if isinstance(self.jumphost.get("tags"), dict) and "nc_command" in self.jumphost["tags"]:
|
||||||
|
nc_cmd = self.jumphost["tags"]["nc_command"]
|
||||||
|
|
||||||
|
if self.jumphost["protocol"] == "kubectl":
|
||||||
|
proxy_cmd = f"kubectl exec "
|
||||||
|
if self.jumphost["options"] != '':
|
||||||
|
proxy_cmd += f"{self.jumphost['options']} "
|
||||||
|
proxy_cmd += f"{self.jumphost['host']} -i -- {nc_cmd} %h %p"
|
||||||
|
else:
|
||||||
|
proxy_cmd = f"docker "
|
||||||
|
if self.jumphost["options"] != '':
|
||||||
|
proxy_cmd += f"{self.jumphost['options']} "
|
||||||
|
proxy_cmd += f"exec -i {self.jumphost['host']} {nc_cmd} %h %p"
|
||||||
|
|
||||||
|
self.jumphost = f"-o ProxyCommand=\"{proxy_cmd}\""
|
||||||
else:
|
else:
|
||||||
self.jumphost = ""
|
self.jumphost = ""
|
||||||
|
|
||||||
|
self.output = ""
|
||||||
|
self.status = 1
|
||||||
|
self.result = {}
|
||||||
|
self.cmd_byte_positions = [(0, None)]
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
def _passtx(self, passwords, *, keyfile=None):
|
def _passtx(self, passwords, *, keyfile=None):
|
||||||
# decrypts passwords, used by other methdos.
|
# decrypts passwords, used by other methdos.
|
||||||
@@ -189,30 +256,29 @@ class node:
|
|||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
def _logclean(self, logfile, var = False):
|
def _logclean(self, logfile, var = False):
|
||||||
#Remove special ascii characters and other stuff from logfile.
|
"""Remove special ascii characters and process terminal cursor movements to clean logs."""
|
||||||
|
from .utils import log_cleaner
|
||||||
|
|
||||||
if var == False:
|
if var == False:
|
||||||
t = open(logfile, "r").read()
|
try:
|
||||||
else:
|
with open(logfile, "r") as f:
|
||||||
t = logfile
|
t = f.read()
|
||||||
while t.find("\b") != -1:
|
except:
|
||||||
t = re.sub('[^\b]\b', '', t)
|
|
||||||
t = t.replace("\n","",1)
|
|
||||||
t = t.replace("\a","")
|
|
||||||
t = t.replace('\n\n', '\n')
|
|
||||||
t = re.sub(r'.\[K', '', t)
|
|
||||||
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/ ]*[@-~])')
|
|
||||||
t = ansi_escape.sub('', t)
|
|
||||||
t = t.lstrip(" \n\r")
|
|
||||||
t = t.replace("\r","")
|
|
||||||
t = t.replace("\x0E","")
|
|
||||||
t = t.replace("\x0F","")
|
|
||||||
if var == False:
|
|
||||||
d = open(logfile, "w")
|
|
||||||
d.write(t)
|
|
||||||
d.close()
|
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
return t
|
t = logfile
|
||||||
|
|
||||||
|
result = log_cleaner(t)
|
||||||
|
|
||||||
|
if var == False:
|
||||||
|
try:
|
||||||
|
with open(logfile, "w") as f:
|
||||||
|
f.write(result)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
return result
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
def _savelog(self):
|
def _savelog(self):
|
||||||
@@ -248,48 +314,318 @@ class node:
|
|||||||
sleep(1)
|
sleep(1)
|
||||||
|
|
||||||
|
|
||||||
@MethodHook
|
def _setup_interact_environment(self, debug=False, logger=None, async_mode=False):
|
||||||
def interact(self, debug = False, logger = None):
|
|
||||||
'''
|
|
||||||
Allow user to interact with the node directly, mostly used by connection manager.
|
|
||||||
|
|
||||||
### Optional Parameters:
|
|
||||||
|
|
||||||
- debug (bool): If True, display all the connecting information
|
|
||||||
before interact. Default False.
|
|
||||||
- logger (callable): Optional callback for status reporting.
|
|
||||||
'''
|
|
||||||
connect = self._connect(debug = debug, logger = logger)
|
|
||||||
if connect == True:
|
|
||||||
size = re.search('columns=([0-9]+).*lines=([0-9]+)',str(os.get_terminal_size()))
|
size = re.search('columns=([0-9]+).*lines=([0-9]+)',str(os.get_terminal_size()))
|
||||||
self.child.setwinsize(int(size.group(2)),int(size.group(1)))
|
self.child.setwinsize(int(size.group(2)),int(size.group(1)))
|
||||||
if logger:
|
if logger:
|
||||||
port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else ""
|
port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else ""
|
||||||
logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}")
|
logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}")
|
||||||
|
|
||||||
if 'logfile' in dir(self):
|
# Always initialize self.mylog to capture terminal context for the AI Copilot
|
||||||
# Initialize self.mylog
|
if not hasattr(self, 'mylog'):
|
||||||
if not 'mylog' in dir(self):
|
|
||||||
self.mylog = io.BytesIO()
|
self.mylog = io.BytesIO()
|
||||||
|
|
||||||
|
if not async_mode:
|
||||||
self.child.logfile_read = self.mylog
|
self.child.logfile_read = self.mylog
|
||||||
|
|
||||||
# Start the _savelog thread
|
# Only start disk-logging tasks if logfile is configured
|
||||||
|
if 'logfile' in dir(self):
|
||||||
|
if not async_mode:
|
||||||
|
# Start the _savelog thread (sync mode)
|
||||||
log_thread = threading.Thread(target=self._savelog)
|
log_thread = threading.Thread(target=self._savelog)
|
||||||
log_thread.daemon = True
|
log_thread.daemon = True
|
||||||
log_thread.start()
|
log_thread.start()
|
||||||
if 'missingtext' in dir(self):
|
if 'missingtext' in dir(self):
|
||||||
print(self.child.after.decode(), end='')
|
print(self.child.after.decode(), end='')
|
||||||
if self.idletime > 0:
|
if self.idletime > 0 and not async_mode:
|
||||||
x = threading.Thread(target=self._keepalive)
|
x = threading.Thread(target=self._keepalive)
|
||||||
x.daemon = True
|
x.daemon = True
|
||||||
x.start()
|
x.start()
|
||||||
if debug:
|
if debug:
|
||||||
|
if 'mylog' in dir(self):
|
||||||
|
if not async_mode:
|
||||||
print(self.mylog.getvalue().decode())
|
print(self.mylog.getvalue().decode())
|
||||||
self.child.interact(input_filter=self._filter)
|
|
||||||
if 'logfile' in dir(self):
|
def _teardown_interact_environment(self):
|
||||||
|
if 'logfile' in dir(self) and hasattr(self, 'mylog'):
|
||||||
with open(self.logfile, "w") as f:
|
with open(self.logfile, "w") as f:
|
||||||
f.write(self._logclean(self.mylog.getvalue().decode(), True))
|
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''
|
||||||
|
if getattr(self, 'missingtext', False):
|
||||||
|
# If we are missing the password, we MUST show the password prompt
|
||||||
|
ghost_buffer = (self.child.after or b'') + (self.child.buffer or b'')
|
||||||
|
else:
|
||||||
|
# We auto-logged in. Hide the messy password negotiation and just keep any pending live stream.
|
||||||
|
ghost_buffer = self.child.buffer or b''
|
||||||
|
|
||||||
|
# Fix user'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, 'missingtext', False):
|
||||||
|
ghost_buffer = ghost_buffer.lstrip(b'\r\n ')
|
||||||
|
|
||||||
|
if ghost_buffer:
|
||||||
|
# Add a single clean newline so it doesn't merge with the Connected message
|
||||||
|
await local_stream.write(b'\r\n' + ghost_buffer)
|
||||||
|
if hasattr(self, 'mylog'):
|
||||||
|
self.mylog.write(b'\n' + ghost_buffer)
|
||||||
|
|
||||||
|
self.child.buffer = b''
|
||||||
|
self.child.before = b''
|
||||||
|
|
||||||
|
# 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()
|
||||||
|
|
||||||
|
# Reset and track command byte positions for copilot context navigation
|
||||||
|
# Each entry is (byte_position, command_text_or_None)
|
||||||
|
self.cmd_byte_positions = [(self.mylog.tell() if hasattr(self, 'mylog') else 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'')
|
||||||
|
except BlockingIOError:
|
||||||
|
pass
|
||||||
|
except OSError:
|
||||||
|
child_reader_queue.put_nowait(b'')
|
||||||
|
|
||||||
|
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'\x00' 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='replace')
|
||||||
|
return str(val) if val is not None else "unknown"
|
||||||
|
|
||||||
|
node_info = {
|
||||||
|
"name": to_str(getattr(self, 'unique', 'unknown')),
|
||||||
|
"host": to_str(getattr(self, 'host', 'unknown'))
|
||||||
|
}
|
||||||
|
if isinstance(getattr(self, 'tags', None), dict):
|
||||||
|
node_info["os"] = to_str(self.tags.get("os", "unknown"))
|
||||||
|
node_info["prompt"] = to_str(self.tags.get("prompt", r'>$|#$|\$$|>.$|#.$|\$.$'))
|
||||||
|
|
||||||
|
# Invoke copilot (async callback handles UI)
|
||||||
|
await copilot_handler(self.mylog.getvalue(), node_info, local_stream, child_fd, self.cmd_byte_positions)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Remove any stray \x00 bytes and forward normally
|
||||||
|
clean_data = data.replace(b'\x00', b'')
|
||||||
|
if clean_data:
|
||||||
|
# Track command boundaries when user hits Enter
|
||||||
|
if hasattr(self, 'mylog') and (b'\r' in clean_data or b'\n' in clean_data):
|
||||||
|
self.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, 'missingtext', 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'') # Re-put EOF later or handle it
|
||||||
|
break
|
||||||
|
chunks.append(extra)
|
||||||
|
except asyncio.QueueEmpty:
|
||||||
|
break
|
||||||
|
|
||||||
|
has_eof = chunks[-1] == b''
|
||||||
|
if has_eof:
|
||||||
|
chunks.pop()
|
||||||
|
|
||||||
|
if chunks:
|
||||||
|
combined_data = b''.join(chunks)
|
||||||
|
if skip_newlines:
|
||||||
|
stripped = combined_data.lstrip(b'\r\n')
|
||||||
|
if stripped:
|
||||||
|
skip_newlines = False
|
||||||
|
combined_data = stripped
|
||||||
|
else:
|
||||||
|
if has_eof: break
|
||||||
|
continue
|
||||||
|
|
||||||
|
await local_stream.write(combined_data)
|
||||||
|
if hasattr(self, 'mylog'):
|
||||||
|
self.mylog.write(combined_data)
|
||||||
|
|
||||||
|
if has_eof:
|
||||||
|
break
|
||||||
|
|
||||||
|
async def keepalive_task():
|
||||||
|
while True:
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
if time() - self.lastinput >= self.idletime:
|
||||||
|
try:
|
||||||
|
self.child.sendcontrol("e")
|
||||||
|
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='replace')
|
||||||
|
cleaned_log = await asyncio.to_thread(self._logclean, raw_log, True)
|
||||||
|
with open(self.logfile, "w") 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 > 0:
|
||||||
|
tasks.append(asyncio.create_task(keepalive_task()))
|
||||||
|
if hasattr(self, 'logfile') and hasattr(self, 'mylog'):
|
||||||
|
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, 'logfile') and hasattr(self, 'mylog'):
|
||||||
|
try:
|
||||||
|
raw_log = self.mylog.getvalue().decode(errors='replace')
|
||||||
|
cleaned_log = await asyncio.to_thread(self._logclean, raw_log, True)
|
||||||
|
with open(self.logfile, "w") 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 & ~os.O_NONBLOCK)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
local_stream.teardown()
|
||||||
|
|
||||||
|
@MethodHook
|
||||||
|
async def inject_commands(self, commands, child_fd, on_inject=None):
|
||||||
|
"""
|
||||||
|
Inject a list of commands into the node's PTY.
|
||||||
|
Handles screen_length_command, history tracking and delays.
|
||||||
|
"""
|
||||||
|
if not commands:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 0. Clear line
|
||||||
|
os.write(child_fd, b'\x15')
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
|
||||||
|
# 1. Prepare list (prepend screen_length if exists)
|
||||||
|
slc = self.tags.get("screen_length_command") if hasattr(self, 'tags') and isinstance(self.tags, dict) else None
|
||||||
|
|
||||||
|
to_send = list(commands)
|
||||||
|
if slc and slc not in to_send: # avoid duplicates if already there
|
||||||
|
to_send.insert(0, slc)
|
||||||
|
|
||||||
|
# 2. Inject one by one
|
||||||
|
for cmd in to_send:
|
||||||
|
# Register in node's official history (SKIP if it's the administrative screen length command)
|
||||||
|
if cmd != slc and hasattr(self, 'cmd_byte_positions') and self.cmd_byte_positions is not None:
|
||||||
|
log_pos = self.mylog.tell() if hasattr(self, 'mylog') else 0
|
||||||
|
self.cmd_byte_positions.append((log_pos, cmd))
|
||||||
|
|
||||||
|
# Write physically to PTY
|
||||||
|
os.write(child_fd, (cmd + "\n").encode())
|
||||||
|
|
||||||
|
# Notify (e.g., for gRPC or logs) - SKIP for administrative SLC
|
||||||
|
if on_inject and cmd != slc:
|
||||||
|
if asyncio.iscoroutinefunction(on_inject):
|
||||||
|
await on_inject(cmd)
|
||||||
|
else:
|
||||||
|
on_inject(cmd)
|
||||||
|
|
||||||
|
# Delay to avoid overwhelming the router
|
||||||
|
await asyncio.sleep(0.8)
|
||||||
|
|
||||||
|
@MethodHook
|
||||||
|
def interact(self, debug=False, logger=None):
|
||||||
|
'''
|
||||||
|
Asynchronous interactive session using Smart Tunnel architecture.
|
||||||
|
Allows multiplexing I/O and handling SIGWINCH events locally without blocking.
|
||||||
|
'''
|
||||||
|
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:
|
else:
|
||||||
if logger:
|
if logger:
|
||||||
logger("error", str(connect))
|
logger("error", str(connect))
|
||||||
@@ -297,6 +633,81 @@ class node:
|
|||||||
printer.error(f"Connection failed: {str(connect)}")
|
printer.error(f"Connection failed: {str(connect)}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
def _build_local_copilot_handler(self):
|
||||||
|
"""Build copilot handler for local CLI sessions using rich for rendering."""
|
||||||
|
config = getattr(self, 'config', None) if hasattr(self, 'config') else None
|
||||||
|
return self._copilot_handler(config)
|
||||||
|
|
||||||
|
def _copilot_handler(self, config):
|
||||||
|
"""Unified copilot handler for local session."""
|
||||||
|
from .cli.terminal_ui import CopilotInterface
|
||||||
|
from .services.ai_service import AIService
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
|
||||||
|
async def handler(buffer, node_info, stream, child_fd, cmd_byte_positions=None):
|
||||||
|
try:
|
||||||
|
interface = CopilotInterface(
|
||||||
|
config,
|
||||||
|
history=getattr(stream, 'copilot_history', None),
|
||||||
|
session_state=getattr(stream, 'copilot_state', 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, 'stop_reading'):
|
||||||
|
stream.stop_reading()
|
||||||
|
elif hasattr(stream, '_loop') and hasattr(stream, 'stdin_fd'):
|
||||||
|
# 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=self.cmd_byte_positions,
|
||||||
|
node_info=node_info,
|
||||||
|
on_ai_call=on_ai_call
|
||||||
|
)
|
||||||
|
if action == "continue":
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
finally:
|
||||||
|
print("\033[2m Returning to session...\033[0m", flush=True)
|
||||||
|
# Reiniciar el lector de la terminal para volver al modo interactivo SSH/Telnet
|
||||||
|
if hasattr(stream, 'start_reading'):
|
||||||
|
stream.start_reading()
|
||||||
|
elif hasattr(stream, '_loop') and hasattr(stream, 'stdin_fd'):
|
||||||
|
stream._loop.add_reader(stream.stdin_fd, stream._read_ready)
|
||||||
|
|
||||||
|
if action in ("send_all", "custom"):
|
||||||
|
cmds_to_send = commands if action == "send_all" else custom_cmd
|
||||||
|
await self.inject_commands(cmds_to_send, child_fd)
|
||||||
|
else:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
except Exception as e:
|
||||||
|
import traceback
|
||||||
|
print(f"\n[ERROR in Copilot Handler] {e}", flush=True)
|
||||||
|
traceback.print_exc()
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
|
||||||
|
return handler
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
def run(self, commands, vars = None,*, folder = '', prompt = r'>$|#$|\$$|>.$|#.$|\$.$', stdout = False, timeout = 10, logger = None):
|
def run(self, commands, vars = None,*, folder = '', prompt = r'>$|#$|\$$|>.$|#.$|\$.$', stdout = False, timeout = 10, logger = None):
|
||||||
@@ -358,7 +769,6 @@ class node:
|
|||||||
if "prompt" in self.tags:
|
if "prompt" in self.tags:
|
||||||
prompt = self.tags["prompt"]
|
prompt = self.tags["prompt"]
|
||||||
expects = [prompt, pexpect.EOF, pexpect.TIMEOUT]
|
expects = [prompt, pexpect.EOF, pexpect.TIMEOUT]
|
||||||
|
|
||||||
output = ''
|
output = ''
|
||||||
status = ''
|
status = ''
|
||||||
if not isinstance(commands, list):
|
if not isinstance(commands, list):
|
||||||
@@ -369,7 +779,12 @@ class node:
|
|||||||
self.child.logfile_read = self.mylog
|
self.child.logfile_read = self.mylog
|
||||||
for c in commands:
|
for c in commands:
|
||||||
if vars is not None:
|
if vars is not None:
|
||||||
|
try:
|
||||||
c = c.format(**vars)
|
c = c.format(**vars)
|
||||||
|
except KeyError as e:
|
||||||
|
self.output = f"Error: Variable {e} not defined in task or inventory"
|
||||||
|
self.status = 1
|
||||||
|
return self.output
|
||||||
result = self.child.expect(expects, timeout = timeout)
|
result = self.child.expect(expects, timeout = timeout)
|
||||||
self.child.sendline(c)
|
self.child.sendline(c)
|
||||||
if result == 2:
|
if result == 2:
|
||||||
@@ -403,7 +818,7 @@ class node:
|
|||||||
return connect
|
return connect
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
def test(self, commands, expected, vars = None,*, prompt = r'>$|#$|\$$|>.$|#.$|\$.$', timeout = 10, logger = None):
|
def test(self, commands, expected, vars = None,*, folder = '', prompt = r'>$|#$|\$$|>.$|#.$|\$.$', timeout = 10, logger = None):
|
||||||
'''
|
'''
|
||||||
Run a command or list of commands on the node, then check if expected value appears on the output after the last command.
|
Run a command or list of commands on the node, then check if expected value appears on the output after the last command.
|
||||||
|
|
||||||
@@ -429,6 +844,9 @@ class node:
|
|||||||
|
|
||||||
### Optional Named Parameters:
|
### 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
|
- prompt (str): Prompt to be expected after a command is finished
|
||||||
running. Usually linux uses ">" or EOF while
|
running. Usually linux uses ">" or EOF while
|
||||||
routers use ">" or "#". The default value should
|
routers use ">" or "#". The default value should
|
||||||
@@ -443,6 +861,7 @@ class node:
|
|||||||
false if prompt is found before.
|
false if prompt is found before.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
|
now = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
||||||
connect = self._connect(timeout = timeout, logger = logger)
|
connect = self._connect(timeout = timeout, logger = logger)
|
||||||
if connect == True:
|
if connect == True:
|
||||||
if logger:
|
if logger:
|
||||||
@@ -471,7 +890,12 @@ class node:
|
|||||||
self.child.logfile_read = self.mylog
|
self.child.logfile_read = self.mylog
|
||||||
for c in commands:
|
for c in commands:
|
||||||
if vars is not None:
|
if vars is not None:
|
||||||
|
try:
|
||||||
c = c.format(**vars)
|
c = c.format(**vars)
|
||||||
|
except KeyError as e:
|
||||||
|
self.output = f"Error: Variable {e} not defined in task or inventory"
|
||||||
|
self.status = 1
|
||||||
|
return self.output
|
||||||
result = self.child.expect(expects, timeout = timeout)
|
result = self.child.expect(expects, timeout = timeout)
|
||||||
self.child.sendline(c)
|
self.child.sendline(c)
|
||||||
if result == 2:
|
if result == 2:
|
||||||
@@ -480,6 +904,12 @@ class node:
|
|||||||
result = self.child.expect(expects, timeout = timeout)
|
result = self.child.expect(expects, timeout = timeout)
|
||||||
self.child.close()
|
self.child.close()
|
||||||
output = self._logclean(self.mylog.getvalue().decode(), True)
|
output = self._logclean(self.mylog.getvalue().decode(), True)
|
||||||
|
if logger:
|
||||||
|
logger("output", output)
|
||||||
|
if folder != '':
|
||||||
|
with open(folder + "/" + self.unique + "_" + now + ".txt", "w") as f:
|
||||||
|
f.write(output)
|
||||||
|
f.close()
|
||||||
self.output = output
|
self.output = output
|
||||||
if result in [0, 1]:
|
if result in [0, 1]:
|
||||||
# lastcommand = commands[-1]
|
# lastcommand = commands[-1]
|
||||||
@@ -514,15 +944,18 @@ class node:
|
|||||||
@MethodHook
|
@MethodHook
|
||||||
def _generate_ssh_sftp_cmd(self):
|
def _generate_ssh_sftp_cmd(self):
|
||||||
cmd = self.protocol
|
cmd = self.protocol
|
||||||
if self.idletime > 0:
|
|
||||||
cmd += " -o ServerAliveInterval=" + str(self.idletime)
|
|
||||||
if self.port:
|
if self.port:
|
||||||
if self.protocol == "ssh":
|
if self.protocol == "ssh":
|
||||||
cmd += " -p " + self.port
|
cmd += " -p " + self.port
|
||||||
elif self.protocol == "sftp":
|
elif self.protocol == "sftp":
|
||||||
cmd += " -P " + self.port
|
cmd += " -P " + self.port
|
||||||
if self.options:
|
if self.options:
|
||||||
cmd += " " + self.options
|
opts = self.options
|
||||||
|
if self.protocol == "sftp":
|
||||||
|
# Strip SSH-only flags that sftp doesn't support
|
||||||
|
opts = re.sub(r'(?<!\S)-[XxtTAaNf]\b', '', opts).strip()
|
||||||
|
if opts:
|
||||||
|
cmd += " " + opts
|
||||||
if self.jumphost:
|
if self.jumphost:
|
||||||
cmd += " " + self.jumphost
|
cmd += " " + self.jumphost
|
||||||
user_host = f"{self.user}@{self.host}" if self.user else self.host
|
user_host = f"{self.user}@{self.host}" if self.user else self.host
|
||||||
@@ -565,6 +998,19 @@ class node:
|
|||||||
cmd += f" {self.options}"
|
cmd += f" {self.options}"
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
|
@MethodHook
|
||||||
|
def _generate_ssm_cmd(self):
|
||||||
|
region = self.tags.get("region", "") if isinstance(self.tags, dict) else ""
|
||||||
|
profile = self.tags.get("profile", "") if isinstance(self.tags, dict) else ""
|
||||||
|
cmd = f"aws ssm start-session --target {self.host}"
|
||||||
|
if region:
|
||||||
|
cmd += f" --region {region}"
|
||||||
|
if profile:
|
||||||
|
cmd += f" --profile {profile}"
|
||||||
|
if self.options:
|
||||||
|
cmd += f" {self.options}"
|
||||||
|
return cmd
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
def _get_cmd(self):
|
def _get_cmd(self):
|
||||||
if self.protocol in ["ssh", "sftp"]:
|
if self.protocol in ["ssh", "sftp"]:
|
||||||
@@ -598,7 +1044,7 @@ class node:
|
|||||||
"telnet": ['[u|U]sername:', 'refused', 'supported', 'invalid|unrecognized option', 'ssh-keygen.*\"', 'timeout|timed.out', 'unavailable', 'closed', password_prompt, prompt, 'suspend', pexpect.EOF, pexpect.TIMEOUT, "No route to host", "resolve hostname", "no matching", "[b|B]ad (owner|permissions)"],
|
"telnet": ['[u|U]sername:', 'refused', 'supported', 'invalid|unrecognized option', 'ssh-keygen.*\"', 'timeout|timed.out', 'unavailable', 'closed', password_prompt, prompt, 'suspend', pexpect.EOF, pexpect.TIMEOUT, "No route to host", "resolve hostname", "no matching", "[b|B]ad (owner|permissions)"],
|
||||||
"kubectl": ['[u|U]sername:', '[r|R]efused', '[E|e]rror', 'DEPRECATED', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF, "expired|invalid"],
|
"kubectl": ['[u|U]sername:', '[r|R]efused', '[E|e]rror', 'DEPRECATED', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF, "expired|invalid"],
|
||||||
"docker": ['[u|U]sername:', 'Cannot', '[E|e]rror', 'failed', 'not a docker command', 'unknown', 'unable to resolve', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF],
|
"docker": ['[u|U]sername:', 'Cannot', '[E|e]rror', 'failed', 'not a docker command', 'unknown', 'unable to resolve', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF],
|
||||||
"ssm": ['[u|U]sername:', 'Cannot', '[E|e]rror', 'failed', 'SessionManagerPlugin', 'unknown', 'unable to resolve', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF]
|
"ssm": ['[u|U]sername:', 'Cannot', '[E|e]rror', 'failed', 'SessionManagerPlugin', '[u|U]nknown', 'unable to resolve', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF]
|
||||||
}
|
}
|
||||||
|
|
||||||
error_indices = {
|
error_indices = {
|
||||||
@@ -637,6 +1083,7 @@ class node:
|
|||||||
if logger:
|
if logger:
|
||||||
logger("debug", f"Command:\n{cmd}")
|
logger("debug", f"Command:\n{cmd}")
|
||||||
self.mylog = io.BytesIO()
|
self.mylog = io.BytesIO()
|
||||||
|
self.mylog.write(f"[i] [DEBUG] Command:\r\n {cmd}\r\n".encode())
|
||||||
child.logfile_read = self.mylog
|
child.logfile_read = self.mylog
|
||||||
|
|
||||||
|
|
||||||
@@ -841,8 +1288,15 @@ class nodes:
|
|||||||
nodesargs[n.unique]["vars"] = {}
|
nodesargs[n.unique]["vars"] = {}
|
||||||
if "__global__" in vars.keys():
|
if "__global__" in vars.keys():
|
||||||
nodesargs[n.unique]["vars"].update(vars["__global__"])
|
nodesargs[n.unique]["vars"].update(vars["__global__"])
|
||||||
if n.unique in vars.keys():
|
for var_key, var_val in vars.items():
|
||||||
nodesargs[n.unique]["vars"].update(vars[n.unique])
|
if var_key == "__global__":
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
if re.search(var_key, n.unique, re.IGNORECASE):
|
||||||
|
nodesargs[n.unique]["vars"].update(var_val)
|
||||||
|
except re.error:
|
||||||
|
if var_key == n.unique:
|
||||||
|
nodesargs[n.unique]["vars"].update(var_val)
|
||||||
|
|
||||||
# Pass the logger to the node
|
# Pass the logger to the node
|
||||||
nodesargs[n.unique]["logger"] = logger
|
nodesargs[n.unique]["logger"] = logger
|
||||||
@@ -867,7 +1321,7 @@ class nodes:
|
|||||||
return output
|
return output
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
def test(self, commands, expected, vars = None,*, prompt = None, parallel = 10, timeout = None, on_complete = None, logger = None):
|
def test(self, commands, expected, vars = None,*, folder = None, prompt = None, parallel = 10, timeout = None, on_complete = None, logger = None):
|
||||||
'''
|
'''
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -922,6 +1376,9 @@ class nodes:
|
|||||||
nodesargs = {}
|
nodesargs = {}
|
||||||
args["commands"] = commands
|
args["commands"] = commands
|
||||||
args["expected"] = expected
|
args["expected"] = expected
|
||||||
|
if folder != None:
|
||||||
|
args["folder"] = folder
|
||||||
|
Path(folder).mkdir(parents=True, exist_ok=True)
|
||||||
if prompt != None:
|
if prompt != None:
|
||||||
args["prompt"] = prompt
|
args["prompt"] = prompt
|
||||||
if timeout != None:
|
if timeout != None:
|
||||||
@@ -943,8 +1400,15 @@ class nodes:
|
|||||||
nodesargs[n.unique]["vars"] = {}
|
nodesargs[n.unique]["vars"] = {}
|
||||||
if "__global__" in vars.keys():
|
if "__global__" in vars.keys():
|
||||||
nodesargs[n.unique]["vars"].update(vars["__global__"])
|
nodesargs[n.unique]["vars"].update(vars["__global__"])
|
||||||
if n.unique in vars.keys():
|
for var_key, var_val in vars.items():
|
||||||
nodesargs[n.unique]["vars"].update(vars[n.unique])
|
if var_key == "__global__":
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
if re.search(var_key, n.unique, re.IGNORECASE):
|
||||||
|
nodesargs[n.unique]["vars"].update(var_val)
|
||||||
|
except re.error:
|
||||||
|
if var_key == n.unique:
|
||||||
|
nodesargs[n.unique]["vars"].update(var_val)
|
||||||
nodesargs[n.unique]["logger"] = logger
|
nodesargs[n.unique]["logger"] = logger
|
||||||
|
|
||||||
if on_complete:
|
if on_complete:
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
+284
-56
@@ -55,16 +55,24 @@ def handle_errors(func):
|
|||||||
return wrapper
|
return wrapper
|
||||||
|
|
||||||
class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
|
class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
|
||||||
def __init__(self, config):
|
def __init__(self, config, debug=False):
|
||||||
self.service = NodeService(config)
|
self.service = NodeService(config)
|
||||||
|
self.server_debug = debug
|
||||||
|
if debug:
|
||||||
|
from rich.console import Console
|
||||||
|
from ..printer import connpy_theme, get_original_stdout
|
||||||
|
self.server_console = Console(theme=connpy_theme, file=get_original_stdout())
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def interact_node(self, request_iterator, context):
|
def interact_node(self, request_iterator, context):
|
||||||
import sys
|
import sys
|
||||||
import select
|
|
||||||
import os
|
import os
|
||||||
|
import asyncio
|
||||||
from connpy.core import node
|
from connpy.core import node
|
||||||
from ..services.profile_service import ProfileService
|
from ..services.profile_service import ProfileService
|
||||||
|
from connpy.tunnels import RemoteStream
|
||||||
|
import queue
|
||||||
|
import threading
|
||||||
|
|
||||||
# Fetch first setup packet
|
# Fetch first setup packet
|
||||||
try:
|
try:
|
||||||
@@ -75,7 +83,9 @@ class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
|
|||||||
unique_id = first_req.id
|
unique_id = first_req.id
|
||||||
sftp = first_req.sftp
|
sftp = first_req.sftp
|
||||||
debug = first_req.debug
|
debug = first_req.debug
|
||||||
printer.console.print(f"[debug][DEBUG][/debug] gRPC interact_node request for: [bold cyan]{unique_id}[/bold cyan]")
|
|
||||||
|
if self.server_debug:
|
||||||
|
self.server_console.print(f"[debug][DEBUG][/debug] gRPC interact_node request for: [bold cyan]{unique_id}[/bold cyan]")
|
||||||
|
|
||||||
if first_req.connection_params_json:
|
if first_req.connection_params_json:
|
||||||
import json
|
import json
|
||||||
@@ -134,7 +144,39 @@ class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
|
|||||||
if sftp:
|
if sftp:
|
||||||
n.protocol = "sftp"
|
n.protocol = "sftp"
|
||||||
|
|
||||||
connect = n._connect(debug=debug)
|
# Build a logger that captures debug messages as ANSI-colored bytes for the client
|
||||||
|
debug_chunks = []
|
||||||
|
if debug:
|
||||||
|
from io import StringIO
|
||||||
|
from rich.console import Console as RichConsole
|
||||||
|
from ..printer import connpy_theme
|
||||||
|
from .. import printer as _printer
|
||||||
|
|
||||||
|
def remote_logger(msg_type, message):
|
||||||
|
buf = StringIO()
|
||||||
|
c = RichConsole(file=buf, force_terminal=True, width=120, theme=connpy_theme)
|
||||||
|
if msg_type == "debug":
|
||||||
|
c.print(_printer._format_multiline("i", f"[DEBUG] {message}", style="info"))
|
||||||
|
elif msg_type == "success":
|
||||||
|
c.print(_printer._format_multiline("✓", message, style="success"))
|
||||||
|
elif msg_type == "error":
|
||||||
|
c.print(_printer._format_multiline("✗", message, style="error"))
|
||||||
|
else:
|
||||||
|
c.print(str(message))
|
||||||
|
rendered = buf.getvalue()
|
||||||
|
if rendered:
|
||||||
|
# Raw TTY needs \r\n instead of \n
|
||||||
|
rendered = rendered.replace('\n', '\r\n')
|
||||||
|
debug_chunks.append(rendered.encode())
|
||||||
|
else:
|
||||||
|
remote_logger = None
|
||||||
|
|
||||||
|
connect = n._connect(debug=debug, logger=remote_logger)
|
||||||
|
|
||||||
|
# Send debug output to client before checking result (always show the command)
|
||||||
|
for chunk in debug_chunks:
|
||||||
|
yield connpy_pb2.InteractResponse(stdout_data=chunk)
|
||||||
|
|
||||||
if connect != True:
|
if connect != True:
|
||||||
yield connpy_pb2.InteractResponse(success=False, error_message=str(connect))
|
yield connpy_pb2.InteractResponse(success=False, error_message=str(connect))
|
||||||
return
|
return
|
||||||
@@ -142,30 +184,6 @@ class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
|
|||||||
# Signal successful connection to the client
|
# Signal successful connection to the client
|
||||||
yield connpy_pb2.InteractResponse(success=True)
|
yield connpy_pb2.InteractResponse(success=True)
|
||||||
|
|
||||||
import threading
|
|
||||||
import queue
|
|
||||||
|
|
||||||
stdin_queue = queue.Queue()
|
|
||||||
running = True
|
|
||||||
|
|
||||||
def read_requests():
|
|
||||||
try:
|
|
||||||
for req in request_iterator:
|
|
||||||
if not running:
|
|
||||||
break
|
|
||||||
if req.cols > 0 and req.rows > 0:
|
|
||||||
try:
|
|
||||||
n.child.setwinsize(req.rows, req.cols)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if req.stdin_data:
|
|
||||||
stdin_queue.put(req.stdin_data)
|
|
||||||
except grpc.RpcError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
t = threading.Thread(target=read_requests, daemon=True)
|
|
||||||
t.start()
|
|
||||||
|
|
||||||
# Set initial window size if provided
|
# Set initial window size if provided
|
||||||
if first_req.cols > 0 and first_req.rows > 0:
|
if first_req.cols > 0 and first_req.rows > 0:
|
||||||
try:
|
try:
|
||||||
@@ -173,32 +191,210 @@ class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
try:
|
response_queue = queue.Queue()
|
||||||
while n.child.isalive() and running:
|
remote_stream = RemoteStream(request_iterator, response_queue)
|
||||||
r, _, _ = select.select([n.child.child_fd], [], [], 0.05)
|
|
||||||
if r:
|
|
||||||
try:
|
|
||||||
data = os.read(n.child.child_fd, 4096)
|
|
||||||
if not data:
|
|
||||||
break
|
|
||||||
yield connpy_pb2.InteractResponse(stdout_data=data)
|
|
||||||
except OSError:
|
|
||||||
break
|
|
||||||
|
|
||||||
while not stdin_queue.empty():
|
def run_async_loop():
|
||||||
data = stdin_queue.get_nowait()
|
|
||||||
try:
|
try:
|
||||||
os.write(n.child.child_fd, data)
|
n._setup_interact_environment(debug=debug, logger=None, async_mode=True)
|
||||||
except OSError:
|
def resize_callback(rows, cols):
|
||||||
running = False
|
|
||||||
break
|
|
||||||
finally:
|
|
||||||
running = False
|
|
||||||
try:
|
try:
|
||||||
n.child.terminate(force=True)
|
n.child.setwinsize(rows, cols)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
async def remote_copilot_handler(buffer, node_info, stream, child_fd, cmd_byte_positions=None):
|
||||||
|
import json
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
from ..services.ai_service import AIService
|
||||||
|
|
||||||
|
service = AIService(self.service.config)
|
||||||
|
|
||||||
|
if node_info is None:
|
||||||
|
node_info = {}
|
||||||
|
|
||||||
|
# Calculate real command blocks from history using the central service
|
||||||
|
raw_bytes = n.mylog.getvalue() if hasattr(n, 'mylog') else buffer
|
||||||
|
if not isinstance(raw_bytes, bytes):
|
||||||
|
raw_bytes = str(raw_bytes).encode()
|
||||||
|
|
||||||
|
from connpy.utils import log_cleaner
|
||||||
|
last_line = log_cleaner(raw_bytes.decode(errors='replace')).split('\n')[-1].strip()
|
||||||
|
blocks = service.build_context_blocks(raw_bytes, n.cmd_byte_positions, node_info, last_line=last_line)
|
||||||
|
node_info["context_blocks"] = blocks
|
||||||
|
|
||||||
|
node_info_json = json.dumps(node_info)
|
||||||
|
|
||||||
|
# Convert buffer to string if it's bytes for the preview
|
||||||
|
preview_str = buffer[-200:].decode(errors='replace') if isinstance(buffer, bytes) else str(buffer)[-200:]
|
||||||
|
|
||||||
|
# Generate a unique session ID for this copilot interaction to prevent race conditions
|
||||||
|
import uuid
|
||||||
|
copilot_session_id = str(uuid.uuid4())
|
||||||
|
node_info["session_id"] = copilot_session_id
|
||||||
|
node_info_json = json.dumps(node_info)
|
||||||
|
|
||||||
|
# 1. Send prompt to client
|
||||||
|
response_queue.put(connpy_pb2.InteractResponse(
|
||||||
|
copilot_prompt=True,
|
||||||
|
copilot_buffer_preview=preview_str,
|
||||||
|
copilot_node_info_json=node_info_json
|
||||||
|
))
|
||||||
|
|
||||||
|
while True:
|
||||||
|
# 0. Drain the queue of any stale messages before starting a new interaction
|
||||||
|
while not remote_stream.copilot_queue.empty():
|
||||||
|
try:
|
||||||
|
remote_stream.copilot_queue.get_nowait()
|
||||||
|
except:
|
||||||
|
break
|
||||||
|
|
||||||
|
# 2. Await the question from client via the copilot_queue
|
||||||
|
import threading
|
||||||
|
def preload_ai_deps():
|
||||||
|
try:
|
||||||
|
import litellm
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
threading.Thread(target=preload_ai_deps, daemon=True).start()
|
||||||
|
|
||||||
|
try:
|
||||||
|
req_data = await asyncio.wait_for(remote_stream.copilot_queue.get(), timeout=120)
|
||||||
|
if not req_data: return
|
||||||
|
|
||||||
|
# Validate session ID if provided by client (skip validation if not provided for CLI compatibility)
|
||||||
|
req_session_id = req_data.get("session_id")
|
||||||
|
if req_session_id and req_session_id != copilot_session_id:
|
||||||
|
continue # Ignore stale request from a previous session
|
||||||
|
|
||||||
|
if "question" not in req_data or not req_data["question"] or req_data["question"] == "CANCEL" or req_data.get("action") in ("cancel", "web_cancel"):
|
||||||
|
if req_data.get("action") == "web_cancel":
|
||||||
|
os.write(child_fd, b'\x05')
|
||||||
|
else:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
question = req_data["question"]
|
||||||
|
|
||||||
|
merged_node_info_str = req_data.get("node_info_json", "")
|
||||||
|
if merged_node_info_str:
|
||||||
|
try:
|
||||||
|
merged_node_info = json.loads(merged_node_info_str)
|
||||||
|
node_info.update(merged_node_info)
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
context_buffer = req_data.get("context_buffer", "")
|
||||||
|
if context_buffer.startswith('{"context_start_pos"'):
|
||||||
|
try:
|
||||||
|
parsed = json.loads(context_buffer)
|
||||||
|
start_pos = parsed["context_start_pos"]
|
||||||
|
selected_raw = raw_bytes[start_pos:]
|
||||||
|
context_buffer = n._logclean(selected_raw.decode(errors='replace'), var=True)
|
||||||
|
except Exception:
|
||||||
|
context_buffer = buffer
|
||||||
|
elif not context_buffer:
|
||||||
|
context_buffer = buffer
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
|
||||||
|
# 3. Call AI Service with streaming
|
||||||
|
def chunk_callback(chunk_text):
|
||||||
|
if chunk_text:
|
||||||
|
response_queue.put(connpy_pb2.InteractResponse(
|
||||||
|
copilot_stream_chunk=chunk_text
|
||||||
|
))
|
||||||
|
|
||||||
|
# Create a clean version of node_info for the AI to save tokens and match local CLI behavior
|
||||||
|
ai_node_info = {k: v for k, v in node_info.items() if k not in ("context_blocks", "full_buffer")}
|
||||||
|
|
||||||
|
ai_task = asyncio.create_task(service.aask_copilot(context_buffer, question, ai_node_info, chunk_callback=chunk_callback))
|
||||||
|
wait_action_task = asyncio.create_task(remote_stream.copilot_queue.get())
|
||||||
|
|
||||||
|
done, pending = await asyncio.wait(
|
||||||
|
[ai_task, wait_action_task],
|
||||||
|
return_when=asyncio.FIRST_COMPLETED
|
||||||
|
)
|
||||||
|
|
||||||
|
if wait_action_task in done:
|
||||||
|
req_data = wait_action_task.result()
|
||||||
|
ai_task.cancel()
|
||||||
|
if req_data.get("action") in ("cancel", "web_cancel") or req_data.get("question") == "CANCEL":
|
||||||
|
if req_data.get("action") == "web_cancel":
|
||||||
|
os.write(child_fd, b'\x05')
|
||||||
|
else:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
continue # Loop back instead of returning to keep session alive
|
||||||
|
else:
|
||||||
|
wait_action_task.cancel()
|
||||||
|
result = ai_task.result()
|
||||||
|
if not result:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
|
||||||
|
# 4. Send response back to client
|
||||||
|
response_queue.put(connpy_pb2.InteractResponse(
|
||||||
|
copilot_response_json=json.dumps(result)
|
||||||
|
))
|
||||||
|
|
||||||
|
# 5. Wait for user action
|
||||||
|
try:
|
||||||
|
action_data = await asyncio.wait_for(remote_stream.copilot_queue.get(), timeout=60)
|
||||||
|
if not action_data: return
|
||||||
|
action = action_data.get("action", "cancel")
|
||||||
|
|
||||||
|
if action == "continue":
|
||||||
|
continue # Loop back for next question
|
||||||
|
|
||||||
|
if action in ("cancel", "web_cancel"):
|
||||||
|
if action == "web_cancel":
|
||||||
|
os.write(child_fd, b'\x05')
|
||||||
|
else:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
|
||||||
|
def on_inject(cmd):
|
||||||
|
response_queue.put(connpy_pb2.InteractResponse(copilot_injected_command=cmd))
|
||||||
|
|
||||||
|
if action == "send_all":
|
||||||
|
commands = result.get("commands", [])
|
||||||
|
await n.inject_commands(commands, child_fd, on_inject=on_inject)
|
||||||
|
return
|
||||||
|
elif action.startswith("custom:"):
|
||||||
|
custom_cmds_raw = action[7:]
|
||||||
|
custom_cmds = [cmd.strip() for cmd in custom_cmds_raw.split('\n') if cmd.strip()]
|
||||||
|
await n.inject_commands(custom_cmds, child_fd, on_inject=on_inject)
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
|
||||||
|
asyncio.run(n._async_interact_loop(remote_stream, resize_callback, copilot_handler=remote_copilot_handler))
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
n._teardown_interact_environment()
|
||||||
|
response_queue.put(None) # Signal EOF
|
||||||
|
|
||||||
|
t_loop = threading.Thread(target=run_async_loop, daemon=True)
|
||||||
|
t_loop.start()
|
||||||
|
def response_generator():
|
||||||
|
while True:
|
||||||
|
data = response_queue.get()
|
||||||
|
if data is None:
|
||||||
|
if self.server_debug:
|
||||||
|
self.server_console.print(f"[debug][DEBUG][/debug] gRPC interact_node session closed for: [bold cyan]{unique_id}[/bold cyan]")
|
||||||
|
break
|
||||||
|
if isinstance(data, connpy_pb2.InteractResponse):
|
||||||
|
yield data
|
||||||
|
else:
|
||||||
|
yield connpy_pb2.InteractResponse(stdout_data=data)
|
||||||
|
yield from response_generator()
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def list_nodes(self, request, context):
|
def list_nodes(self, request, context):
|
||||||
f = request.filter_str if request.filter_str else None
|
f = request.filter_str if request.filter_str else None
|
||||||
@@ -407,14 +603,15 @@ class ExecutionServicer(connpy_pb2_grpc.ExecutionServiceServicer):
|
|||||||
|
|
||||||
def _worker():
|
def _worker():
|
||||||
try:
|
try:
|
||||||
self.service.run_commands(
|
self.service.run_commands( nodes_filter=nodes_filter,
|
||||||
nodes_filter=nodes_filter,
|
|
||||||
commands=list(request.commands),
|
commands=list(request.commands),
|
||||||
folder=request.folder if request.folder else None,
|
folder=request.folder if request.folder else None,
|
||||||
prompt=request.prompt if request.prompt else None,
|
prompt=request.prompt if request.prompt else None,
|
||||||
parallel=request.parallel,
|
parallel=request.parallel,
|
||||||
|
timeout=request.timeout if request.timeout > 0 else 10,
|
||||||
variables=from_struct(request.vars) if request.HasField("vars") else None,
|
variables=from_struct(request.vars) if request.HasField("vars") else None,
|
||||||
on_node_complete=_on_complete
|
on_node_complete=_on_complete,
|
||||||
|
name=request.name if request.name else None
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Optionally pass error to stream, but handle_errors decorator covers top-level.
|
# Optionally pass error to stream, but handle_errors decorator covers top-level.
|
||||||
@@ -447,20 +644,22 @@ class ExecutionServicer(connpy_pb2_grpc.ExecutionServiceServicer):
|
|||||||
|
|
||||||
q = queue.Queue()
|
q = queue.Queue()
|
||||||
|
|
||||||
def _on_complete(unique, output, status, result):
|
def _on_complete(unique, node_output, node_status, node_result):
|
||||||
q.put({"unique_id": unique, "output": output, "status": status, "result": result})
|
q.put({"unique_id": unique, "output": node_output, "status": node_status, "result": node_result})
|
||||||
|
|
||||||
def _worker():
|
def _worker():
|
||||||
try:
|
try:
|
||||||
self.service.test_commands(
|
self.service.test_commands(
|
||||||
nodes_filter=nodes_filter,
|
nodes_filter=nodes_filter,
|
||||||
commands=list(request.commands),
|
commands=list(request.commands),
|
||||||
expected=request.expected,
|
expected=list(request.expected),
|
||||||
folder=request.folder if request.folder else None,
|
folder=request.folder if request.folder else None,
|
||||||
prompt=request.prompt if request.prompt else None,
|
prompt=request.prompt if request.prompt else None,
|
||||||
parallel=request.parallel,
|
parallel=request.parallel,
|
||||||
|
timeout=request.timeout if request.timeout > 0 else 10,
|
||||||
variables=from_struct(request.vars) if request.HasField("vars") else None,
|
variables=from_struct(request.vars) if request.HasField("vars") else None,
|
||||||
on_node_complete=_on_complete
|
on_node_complete=_on_complete,
|
||||||
|
name=request.name if request.name else None
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
q.put(e)
|
q.put(e)
|
||||||
@@ -691,6 +890,8 @@ class AIServicer(connpy_pb2_grpc.AIServiceServicer):
|
|||||||
daemon=True
|
daemon=True
|
||||||
)
|
)
|
||||||
ai_thread.start()
|
ai_thread.start()
|
||||||
|
except grpc.RpcError:
|
||||||
|
pass
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Request Listener Error: {e}")
|
print(f"Request Listener Error: {e}")
|
||||||
finally:
|
finally:
|
||||||
@@ -727,6 +928,22 @@ class AIServicer(connpy_pb2_grpc.AIServiceServicer):
|
|||||||
res = self.service.confirm(request.value)
|
res = self.service.confirm(request.value)
|
||||||
return connpy_pb2.BoolResponse(value=res)
|
return connpy_pb2.BoolResponse(value=res)
|
||||||
|
|
||||||
|
@handle_errors
|
||||||
|
def ask_copilot(self, request, context):
|
||||||
|
import json
|
||||||
|
node_info = json.loads(request.node_info_json) if request.node_info_json else None
|
||||||
|
result = self.service.ask_copilot(
|
||||||
|
request.terminal_buffer,
|
||||||
|
request.user_question,
|
||||||
|
node_info
|
||||||
|
)
|
||||||
|
return connpy_pb2.CopilotResponse(
|
||||||
|
commands=result.get("commands", []),
|
||||||
|
guide=result.get("guide", ""),
|
||||||
|
risk_level=result.get("risk_level", "low"),
|
||||||
|
error=result.get("error") or ""
|
||||||
|
)
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def list_sessions(self, request, context):
|
def list_sessions(self, request, context):
|
||||||
return connpy_pb2.ValueResponse(data=to_value(self.service.list_sessions()))
|
return connpy_pb2.ValueResponse(data=to_value(self.service.list_sessions()))
|
||||||
@@ -741,6 +958,17 @@ class AIServicer(connpy_pb2_grpc.AIServiceServicer):
|
|||||||
self.service.configure_provider(request.provider, request.model, request.api_key)
|
self.service.configure_provider(request.provider, request.model, request.api_key)
|
||||||
return Empty()
|
return Empty()
|
||||||
|
|
||||||
|
@handle_errors
|
||||||
|
def configure_mcp(self, request, context):
|
||||||
|
self.service.configure_mcp(
|
||||||
|
request.name,
|
||||||
|
url=request.url or None,
|
||||||
|
enabled=request.enabled,
|
||||||
|
auto_load_on_os=request.auto_load_on_os or None,
|
||||||
|
remove=request.remove
|
||||||
|
)
|
||||||
|
return Empty()
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def load_session_data(self, request, context):
|
def load_session_data(self, request, context):
|
||||||
return connpy_pb2.StructResponse(data=to_struct(self.service.load_session_data(request.value)))
|
return connpy_pb2.StructResponse(data=to_struct(self.service.load_session_data(request.value)))
|
||||||
@@ -800,7 +1028,7 @@ def serve(config, port=8048, debug=False):
|
|||||||
interceptors = [LoggingInterceptor()] if debug else []
|
interceptors = [LoggingInterceptor()] if debug else []
|
||||||
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=interceptors)
|
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=interceptors)
|
||||||
|
|
||||||
connpy_pb2_grpc.add_NodeServiceServicer_to_server(NodeServicer(config), server)
|
connpy_pb2_grpc.add_NodeServiceServicer_to_server(NodeServicer(config, debug=debug), server)
|
||||||
connpy_pb2_grpc.add_ProfileServiceServicer_to_server(ProfileServicer(config), server)
|
connpy_pb2_grpc.add_ProfileServiceServicer_to_server(ProfileServicer(config), server)
|
||||||
connpy_pb2_grpc.add_ConfigServiceServicer_to_server(ConfigServicer(config), server)
|
connpy_pb2_grpc.add_ConfigServiceServicer_to_server(ConfigServicer(config), server)
|
||||||
plugin_servicer = PluginServicer(config)
|
plugin_servicer = PluginServicer(config)
|
||||||
|
|||||||
+305
-43
@@ -9,6 +9,8 @@ from .utils import to_value, from_value, to_struct, from_struct
|
|||||||
from ..services.exceptions import ConnpyError
|
from ..services.exceptions import ConnpyError
|
||||||
from ..hooks import MethodHook
|
from ..hooks import MethodHook
|
||||||
from .. import printer
|
from .. import printer
|
||||||
|
from ..cli.terminal_ui import CopilotInterface
|
||||||
|
from ..utils import log_cleaner
|
||||||
|
|
||||||
def handle_errors(func):
|
def handle_errors(func):
|
||||||
@wraps(func)
|
@wraps(func)
|
||||||
@@ -41,15 +43,100 @@ class NodeStub:
|
|||||||
self.remote_host = remote_host
|
self.remote_host = remote_host
|
||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
|
def _handle_remote_copilot(self, res, request_queue, response_queue, client_buffer_bytes, pause_generator, resume_generator, old_tty):
|
||||||
|
import json, asyncio, termios, sys, tty, queue
|
||||||
|
from ..core import copilot_terminal_mode
|
||||||
|
from . import connpy_pb2
|
||||||
|
|
||||||
|
pause_generator()
|
||||||
|
|
||||||
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
|
|
||||||
|
node_info = json.loads(res.copilot_node_info_json) if res.copilot_node_info_json else {}
|
||||||
|
blocks = node_info.get("context_blocks", [])
|
||||||
|
|
||||||
|
interface = CopilotInterface(
|
||||||
|
self.config,
|
||||||
|
history=getattr(self, 'copilot_history', None),
|
||||||
|
session_state=getattr(self, 'copilot_state', None)
|
||||||
|
)
|
||||||
|
self.copilot_history = interface.history
|
||||||
|
self.copilot_state = interface.session_state
|
||||||
|
|
||||||
|
async def on_ai_call_remote(active_buffer, question, chunk_callback, merged_node_info):
|
||||||
|
# Send request to server
|
||||||
|
request_queue.put(connpy_pb2.InteractRequest(
|
||||||
|
copilot_question=question,
|
||||||
|
copilot_context_buffer=active_buffer,
|
||||||
|
copilot_node_info_json=json.dumps(merged_node_info)
|
||||||
|
))
|
||||||
|
# Wait for chunks from server
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
chunk_res = response_queue.get(timeout=0.1)
|
||||||
|
if chunk_res is None: return {"error": "Server disconnected"}
|
||||||
|
if chunk_res.copilot_stream_chunk:
|
||||||
|
chunk_callback(chunk_res.copilot_stream_chunk)
|
||||||
|
elif chunk_res.copilot_response_json:
|
||||||
|
return json.loads(chunk_res.copilot_response_json)
|
||||||
|
except queue.Empty:
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
|
||||||
|
# Wrap in async loop
|
||||||
|
async def run_remote_copilot():
|
||||||
|
while True:
|
||||||
|
action, commands, custom_cmd = await interface.run_session(
|
||||||
|
raw_bytes=bytes(client_buffer_bytes),
|
||||||
|
node_info=node_info,
|
||||||
|
on_ai_call=on_ai_call_remote,
|
||||||
|
blocks=blocks
|
||||||
|
)
|
||||||
|
|
||||||
|
if action == "continue":
|
||||||
|
# Send continue signal to server to loop back for another question
|
||||||
|
request_queue.put(connpy_pb2.InteractRequest(copilot_action="continue"))
|
||||||
|
continue
|
||||||
|
|
||||||
|
return action, commands, custom_cmd
|
||||||
|
|
||||||
|
with copilot_terminal_mode():
|
||||||
|
action, commands, custom_cmd = asyncio.run(run_remote_copilot())
|
||||||
|
|
||||||
|
print("\033[2m Returning to session...\033[0m", flush=True)
|
||||||
|
# Prepare final action for server
|
||||||
|
action_sent = "cancel"
|
||||||
|
if action == "send_all" and commands:
|
||||||
|
# In remote mode, send the selected commands as a custom block
|
||||||
|
# so the server executes exactly what the user picked (e.g., selection '1')
|
||||||
|
action_sent = f"custom:{chr(10).join(commands)}"
|
||||||
|
elif action == "custom" and custom_cmd:
|
||||||
|
action_sent = f"custom:{chr(10).join(custom_cmd)}"
|
||||||
|
request_queue.put(connpy_pb2.InteractRequest(copilot_action=action_sent))
|
||||||
|
resume_generator()
|
||||||
|
tty.setraw(sys.stdin.fileno())
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
|
def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
|
||||||
import sys
|
import sys
|
||||||
import select
|
import select
|
||||||
import tty
|
import tty
|
||||||
import termios
|
import termios
|
||||||
|
import queue
|
||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
|
request_queue = queue.Queue()
|
||||||
|
client_buffer_bytes = bytearray()
|
||||||
|
pause_stdin = [False]
|
||||||
|
wake_r, wake_w = os.pipe()
|
||||||
|
|
||||||
|
def pause_generator():
|
||||||
|
pause_stdin[0] = True
|
||||||
|
os.write(wake_w, b'\x00')
|
||||||
|
|
||||||
|
def resume_generator():
|
||||||
|
pause_stdin[0] = False
|
||||||
|
|
||||||
def request_generator():
|
def request_generator():
|
||||||
cols, rows = 80, 24
|
cols, rows = 80, 24
|
||||||
try:
|
try:
|
||||||
@@ -63,8 +150,25 @@ class NodeStub:
|
|||||||
)
|
)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
r, _, _ = select.select([sys.stdin.fileno()], [], [])
|
try:
|
||||||
if r:
|
while True:
|
||||||
|
req = request_queue.get_nowait()
|
||||||
|
if req is None:
|
||||||
|
return
|
||||||
|
yield req
|
||||||
|
except queue.Empty:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if pause_stdin[0]:
|
||||||
|
import time
|
||||||
|
time.sleep(0.05)
|
||||||
|
continue
|
||||||
|
|
||||||
|
r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
|
||||||
|
if wake_r in r:
|
||||||
|
os.read(wake_r, 1)
|
||||||
|
continue
|
||||||
|
if sys.stdin.fileno() in r and not pause_stdin[0]:
|
||||||
try:
|
try:
|
||||||
data = os.read(sys.stdin.fileno(), 1024)
|
data = os.read(sys.stdin.fileno(), 1024)
|
||||||
if not data:
|
if not data:
|
||||||
@@ -86,30 +190,74 @@ class NodeStub:
|
|||||||
|
|
||||||
old_tty = termios.tcgetattr(sys.stdin)
|
old_tty = termios.tcgetattr(sys.stdin)
|
||||||
try:
|
try:
|
||||||
|
import time
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
response_iterator = self.stub.interact_node(request_generator())
|
response_iterator = self.stub.interact_node(request_generator())
|
||||||
|
|
||||||
# First response is connection status
|
import queue
|
||||||
|
response_queue = queue.Queue()
|
||||||
|
|
||||||
|
def response_consumer():
|
||||||
try:
|
try:
|
||||||
first_res = next(response_iterator)
|
for r in response_iterator:
|
||||||
if first_res.success:
|
response_queue.put(r)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
response_queue.put(None)
|
||||||
|
|
||||||
|
t_consumer = threading.Thread(target=response_consumer, daemon=True)
|
||||||
|
t_consumer.start()
|
||||||
|
|
||||||
|
# First phase: Wait for connection status, print early data
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
return
|
||||||
|
if res.stdout_data:
|
||||||
|
data = res.stdout_data
|
||||||
|
if debug:
|
||||||
|
data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
|
||||||
|
os.write(sys.stdout.fileno(), data)
|
||||||
|
|
||||||
|
if res.success:
|
||||||
# Connection established on server, show success message
|
# Connection established on server, show success message
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.success(conn_msg)
|
printer.success(conn_msg)
|
||||||
|
pause_stdin[0] = False
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
else:
|
break
|
||||||
|
|
||||||
|
if res.error_message:
|
||||||
# Connection failed on server
|
# Connection failed on server
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.error(f"Connection failed: {first_res.error_message}")
|
printer.error(f"Connection failed: {res.error_message}")
|
||||||
return
|
return
|
||||||
except StopIteration:
|
except queue.Empty:
|
||||||
return
|
return
|
||||||
|
|
||||||
for res in response_iterator:
|
# Second phase: Stream active session
|
||||||
|
# Clear screen filter is only applied before success (Phase 1).
|
||||||
|
# Once the user has a prompt, Ctrl+L must work normally.
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
break
|
||||||
|
if res.copilot_prompt:
|
||||||
|
self._handle_remote_copilot(
|
||||||
|
res, request_queue, response_queue,
|
||||||
|
client_buffer_bytes,
|
||||||
|
pause_generator, resume_generator, old_tty
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
if res.stdout_data:
|
if res.stdout_data:
|
||||||
os.write(sys.stdout.fileno(), res.stdout_data)
|
os.write(sys.stdout.fileno(), res.stdout_data)
|
||||||
|
client_buffer_bytes.extend(res.stdout_data)
|
||||||
finally:
|
finally:
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
|
os.close(wake_r)
|
||||||
|
os.close(wake_w)
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def connect_dynamic(self, connection_params, debug=False):
|
def connect_dynamic(self, connection_params, debug=False):
|
||||||
@@ -117,10 +265,22 @@ class NodeStub:
|
|||||||
import select
|
import select
|
||||||
import tty
|
import tty
|
||||||
import termios
|
import termios
|
||||||
|
import queue
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
|
|
||||||
params_json = json.dumps(connection_params)
|
params_json = json.dumps(connection_params)
|
||||||
|
request_queue = queue.Queue()
|
||||||
|
client_buffer_bytes = bytearray()
|
||||||
|
pause_stdin = [False]
|
||||||
|
wake_r, wake_w = os.pipe()
|
||||||
|
|
||||||
|
def pause_generator():
|
||||||
|
pause_stdin[0] = True
|
||||||
|
os.write(wake_w, b'\x00')
|
||||||
|
|
||||||
|
def resume_generator():
|
||||||
|
pause_stdin[0] = False
|
||||||
|
|
||||||
def request_generator():
|
def request_generator():
|
||||||
cols, rows = 80, 24
|
cols, rows = 80, 24
|
||||||
@@ -136,8 +296,25 @@ class NodeStub:
|
|||||||
)
|
)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
r, _, _ = select.select([sys.stdin.fileno()], [], [])
|
try:
|
||||||
if r:
|
while True:
|
||||||
|
req = request_queue.get_nowait()
|
||||||
|
if req is None:
|
||||||
|
return
|
||||||
|
yield req
|
||||||
|
except queue.Empty:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if pause_stdin[0]:
|
||||||
|
import time
|
||||||
|
time.sleep(0.05)
|
||||||
|
continue
|
||||||
|
|
||||||
|
r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
|
||||||
|
if wake_r in r:
|
||||||
|
os.read(wake_r, 1)
|
||||||
|
continue
|
||||||
|
if sys.stdin.fileno() in r and not pause_stdin[0]:
|
||||||
try:
|
try:
|
||||||
data = os.read(sys.stdin.fileno(), 1024)
|
data = os.read(sys.stdin.fileno(), 1024)
|
||||||
if not data:
|
if not data:
|
||||||
@@ -160,30 +337,72 @@ class NodeStub:
|
|||||||
|
|
||||||
old_tty = termios.tcgetattr(sys.stdin)
|
old_tty = termios.tcgetattr(sys.stdin)
|
||||||
try:
|
try:
|
||||||
|
import time
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
response_iterator = self.stub.interact_node(request_generator())
|
response_iterator = self.stub.interact_node(request_generator())
|
||||||
|
|
||||||
# First response is connection status
|
import queue
|
||||||
|
response_queue = queue.Queue()
|
||||||
|
|
||||||
|
def response_consumer():
|
||||||
try:
|
try:
|
||||||
first_res = next(response_iterator)
|
for r in response_iterator:
|
||||||
if first_res.success:
|
response_queue.put(r)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
response_queue.put(None)
|
||||||
|
|
||||||
|
t_consumer = threading.Thread(target=response_consumer, daemon=True)
|
||||||
|
t_consumer.start()
|
||||||
|
|
||||||
|
# First phase: Wait for connection status, print early data
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
return
|
||||||
|
if res.stdout_data:
|
||||||
|
data = res.stdout_data
|
||||||
|
if debug:
|
||||||
|
data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
|
||||||
|
os.write(sys.stdout.fileno(), data)
|
||||||
|
|
||||||
|
if res.success:
|
||||||
# Connection established on server, show success message
|
# Connection established on server, show success message
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.success(conn_msg)
|
printer.success(conn_msg)
|
||||||
|
pause_stdin[0] = False
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
else:
|
break
|
||||||
|
|
||||||
|
if res.error_message:
|
||||||
# Connection failed on server
|
# Connection failed on server
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.error(f"Connection failed: {first_res.error_message}")
|
printer.error(f"Connection failed: {res.error_message}")
|
||||||
return
|
return
|
||||||
except StopIteration:
|
except queue.Empty:
|
||||||
return
|
return
|
||||||
|
|
||||||
for res in response_iterator:
|
# Second phase: Stream active session
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
break
|
||||||
|
if res.copilot_prompt:
|
||||||
|
self._handle_remote_copilot(
|
||||||
|
res, request_queue, response_queue,
|
||||||
|
client_buffer_bytes,
|
||||||
|
pause_generator, resume_generator, old_tty
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
if res.stdout_data:
|
if res.stdout_data:
|
||||||
os.write(sys.stdout.fileno(), res.stdout_data)
|
os.write(sys.stdout.fileno(), res.stdout_data)
|
||||||
|
client_buffer_bytes.extend(res.stdout_data)
|
||||||
finally:
|
finally:
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
|
os.close(wake_r)
|
||||||
|
os.close(wake_w)
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
@handle_errors
|
@handle_errors
|
||||||
@@ -420,9 +639,9 @@ class ExecutionStub:
|
|||||||
folder=folder or "",
|
folder=folder or "",
|
||||||
prompt=prompt or "",
|
prompt=prompt or "",
|
||||||
parallel=parallel,
|
parallel=parallel,
|
||||||
|
timeout=timeout,
|
||||||
|
name=kwargs.get("name", "")
|
||||||
)
|
)
|
||||||
# Note: 'timeout', 'on_node_complete', and 'logger' are currently not
|
|
||||||
# sent over gRPC in the current proto definition.
|
|
||||||
if variables is not None:
|
if variables is not None:
|
||||||
req.vars.CopyFrom(to_struct(variables))
|
req.vars.CopyFrom(to_struct(variables))
|
||||||
|
|
||||||
@@ -432,7 +651,10 @@ class ExecutionStub:
|
|||||||
for response in self.stub.run_commands(req):
|
for response in self.stub.run_commands(req):
|
||||||
if on_complete:
|
if on_complete:
|
||||||
on_complete(response.unique_id, response.output, response.status)
|
on_complete(response.unique_id, response.output, response.status)
|
||||||
final_results[response.unique_id] = response.output
|
final_results[response.unique_id] = {
|
||||||
|
"output": response.output,
|
||||||
|
"status": response.status
|
||||||
|
}
|
||||||
|
|
||||||
return final_results
|
return final_results
|
||||||
|
|
||||||
@@ -442,10 +664,12 @@ class ExecutionStub:
|
|||||||
req = connpy_pb2.TestRequest(
|
req = connpy_pb2.TestRequest(
|
||||||
nodes=nodes_list,
|
nodes=nodes_list,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
expected=expected,
|
expected=expected if isinstance(expected, list) else [expected],
|
||||||
folder=kwargs.get("folder", ""),
|
folder=kwargs.get("folder", ""),
|
||||||
prompt=prompt or "",
|
prompt=prompt or "",
|
||||||
parallel=parallel,
|
parallel=parallel,
|
||||||
|
timeout=timeout,
|
||||||
|
name=kwargs.get("name", "")
|
||||||
)
|
)
|
||||||
if variables is not None:
|
if variables is not None:
|
||||||
req.vars.CopyFrom(to_struct(variables))
|
req.vars.CopyFrom(to_struct(variables))
|
||||||
@@ -503,7 +727,6 @@ class AIStub:
|
|||||||
import queue
|
import queue
|
||||||
from rich.prompt import Prompt
|
from rich.prompt import Prompt
|
||||||
from rich.text import Text
|
from rich.text import Text
|
||||||
from rich.live import Live
|
|
||||||
from rich.panel import Panel
|
from rich.panel import Panel
|
||||||
from rich.markdown import Markdown
|
from rich.markdown import Markdown
|
||||||
|
|
||||||
@@ -534,7 +757,7 @@ class AIStub:
|
|||||||
responses = self.stub.ask(request_generator())
|
responses = self.stub.ask(request_generator())
|
||||||
|
|
||||||
full_content = ""
|
full_content = ""
|
||||||
live_display = None
|
header_printed = False
|
||||||
final_result = {"response": "", "chat_history": []}
|
final_result = {"response": "", "chat_history": []}
|
||||||
|
|
||||||
# Background thread to pull responses from gRPC into a local queue
|
# Background thread to pull responses from gRPC into a local queue
|
||||||
@@ -581,7 +804,6 @@ class AIStub:
|
|||||||
if response.status_update:
|
if response.status_update:
|
||||||
if response.requires_confirmation:
|
if response.requires_confirmation:
|
||||||
if status: status.stop()
|
if status: status.stop()
|
||||||
if live_display: live_display.stop()
|
|
||||||
|
|
||||||
# Show prompt and wait for answer
|
# Show prompt and wait for answer
|
||||||
prompt_text = Text.from_ansi(response.status_update)
|
prompt_text = Text.from_ansi(response.status_update)
|
||||||
@@ -590,7 +812,6 @@ class AIStub:
|
|||||||
if status:
|
if status:
|
||||||
status.update("[ai_status]Agent: Resuming...")
|
status.update("[ai_status]Agent: Resuming...")
|
||||||
status.start()
|
status.start()
|
||||||
if live_display: live_display.start()
|
|
||||||
|
|
||||||
req_queue.put(connpy_pb2.AskRequest(confirmation_answer=ans))
|
req_queue.put(connpy_pb2.AskRequest(confirmation_answer=ans))
|
||||||
continue
|
continue
|
||||||
@@ -601,41 +822,71 @@ class AIStub:
|
|||||||
|
|
||||||
if response.debug_message:
|
if response.debug_message:
|
||||||
if debug:
|
if debug:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
printer.console.print(Text.from_ansi(response.debug_message))
|
printer.console.print(Text.from_ansi(response.debug_message))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if response.important_message:
|
if response.important_message:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
printer.console.print(Text.from_ansi(response.important_message))
|
printer.console.print(Text.from_ansi(response.important_message))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if not response.is_final:
|
if not response.is_final:
|
||||||
full_content += response.text_chunk
|
if response.text_chunk:
|
||||||
|
if not header_printed:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
|
||||||
if not live_display and not debug:
|
from rich.console import Console as RichConsole
|
||||||
if status: status.stop()
|
from rich.rule import Rule
|
||||||
live_display = Live(
|
from ..printer import connpy_theme, get_original_stdout, IncrementalMarkdownParser
|
||||||
Panel(Markdown(full_content), title="AI Assistant", expand=False),
|
stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
|
||||||
console=printer.console,
|
|
||||||
refresh_per_second=8,
|
# Print header on first chunk
|
||||||
transient=False
|
stable_console.print(Rule("[bold engineer]Network Engineer[/bold engineer]", style="engineer"))
|
||||||
)
|
header_printed = True
|
||||||
live_display.start()
|
|
||||||
elif live_display:
|
# Initialize parser
|
||||||
live_display.update(Panel(Markdown(full_content), title="AI Assistant", expand=False))
|
md_parser = IncrementalMarkdownParser(console=stable_console)
|
||||||
|
|
||||||
|
full_content += response.text_chunk
|
||||||
|
md_parser.feed(response.text_chunk)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if response.is_final:
|
if response.is_final:
|
||||||
|
if header_printed:
|
||||||
|
from rich.rule import Rule
|
||||||
|
md_parser.flush()
|
||||||
|
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
|
||||||
final_result = from_struct(response.full_result)
|
final_result = from_struct(response.full_result)
|
||||||
responder = final_result.get("responder", "engineer")
|
responder = final_result.get("responder", "engineer")
|
||||||
alias = "architect" if responder == "architect" else "engineer"
|
alias = "architect" if responder == "architect" else "engineer"
|
||||||
role_label = "Network Architect" if responder == "architect" else "Network Engineer"
|
role_label = "Network Architect" if responder == "architect" else "Network Engineer"
|
||||||
title = f"[bold {alias}]{role_label}[/bold {alias}]"
|
title = f"[bold {alias}]{role_label}[/bold {alias}]"
|
||||||
|
|
||||||
if live_display:
|
if header_printed:
|
||||||
live_display.update(Panel(Markdown(full_content), title=title, border_style=alias, expand=False))
|
from rich.console import Console as RichConsole
|
||||||
live_display.stop()
|
from ..printer import connpy_theme, get_original_stdout
|
||||||
elif full_content:
|
stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
|
||||||
printer.console.print(Panel(Markdown(full_content), title=title, border_style=alias, expand=False))
|
stable_console.print(Rule(style=alias))
|
||||||
|
elif not full_content and final_result.get("response"):
|
||||||
|
# If nothing streamed but we have response (e.g. error or direct guide)
|
||||||
|
printer.console.print(Panel(Markdown(final_result["response"]), title=title, border_style=alias, expand=False))
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Check if it was a gRPC error that we should let handle_errors catch
|
# Check if it was a gRPC error that we should let handle_errors catch
|
||||||
@@ -667,6 +918,17 @@ class AIStub:
|
|||||||
req = connpy_pb2.ProviderRequest(provider=provider, model=model or "", api_key=api_key or "")
|
req = connpy_pb2.ProviderRequest(provider=provider, model=model or "", api_key=api_key or "")
|
||||||
self.stub.configure_provider(req)
|
self.stub.configure_provider(req)
|
||||||
|
|
||||||
|
@handle_errors
|
||||||
|
def configure_mcp(self, name, url=None, enabled=True, auto_load_on_os=None, remove=False):
|
||||||
|
req = connpy_pb2.MCPRequest(
|
||||||
|
name=name,
|
||||||
|
url=url or "",
|
||||||
|
enabled=enabled,
|
||||||
|
auto_load_on_os=auto_load_on_os or "",
|
||||||
|
remove=remove
|
||||||
|
)
|
||||||
|
self.stub.configure_mcp(req)
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def load_session_data(self, session_id):
|
def load_session_data(self, session_id):
|
||||||
return from_struct(self.stub.load_session_data(connpy_pb2.StringRequest(value=session_id)).data)
|
return from_struct(self.stub.load_session_data(connpy_pb2.StringRequest(value=session_id)).data)
|
||||||
|
|||||||
+4
-2
@@ -20,7 +20,8 @@ class MethodHook:
|
|||||||
try:
|
try:
|
||||||
args, kwargs = hook(*args, **kwargs)
|
args, kwargs = hook(*args, **kwargs)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
printer.error(f"{self.func.__name__} Pre-hook {hook.__name__} raised an exception: {e}")
|
hook_name = getattr(hook, "__name__", str(hook))
|
||||||
|
printer.error(f"{self.func.__name__} Pre-hook {hook_name} raised an exception: {e}")
|
||||||
|
|
||||||
result = self.func(*args, **kwargs)
|
result = self.func(*args, **kwargs)
|
||||||
|
|
||||||
@@ -32,7 +33,8 @@ class MethodHook:
|
|||||||
try:
|
try:
|
||||||
result = hook(*args, **kwargs, result=result) # Pass result to hooks
|
result = hook(*args, **kwargs, result=result) # Pass result to hooks
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
printer.error(f"{self.func.__name__} Post-hook {hook.__name__} raised an exception: {e}")
|
hook_name = getattr(hook, "__name__", str(hook))
|
||||||
|
printer.error(f"{self.func.__name__} Post-hook {hook_name} raised an exception: {e}")
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import threading
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
import logging
|
||||||
|
|
||||||
|
try:
|
||||||
|
from mcp import ClientSession
|
||||||
|
from mcp.client.sse import sse_client
|
||||||
|
MCP_AVAILABLE = True
|
||||||
|
except ImportError:
|
||||||
|
MCP_AVAILABLE = False
|
||||||
|
|
||||||
|
# Silence noisy MCP and HTTP internal logging
|
||||||
|
logging.getLogger("mcp").setLevel(logging.CRITICAL)
|
||||||
|
logging.getLogger("httpx").setLevel(logging.CRITICAL)
|
||||||
|
logging.getLogger("httpcore").setLevel(logging.CRITICAL)
|
||||||
|
|
||||||
|
class MCPClientManager:
|
||||||
|
"""Manages MCP SSE client connections for connpy."""
|
||||||
|
|
||||||
|
_instance = None
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
def __new__(cls, *args, **kwargs):
|
||||||
|
with cls._lock:
|
||||||
|
if cls._instance is None:
|
||||||
|
cls._instance = super(MCPClientManager, cls).__new__(cls)
|
||||||
|
cls._instance._initialized = False
|
||||||
|
return cls._instance
|
||||||
|
|
||||||
|
def __init__(self, config=None):
|
||||||
|
if self._initialized:
|
||||||
|
return
|
||||||
|
self.config = config
|
||||||
|
self.sessions: Dict[str, Dict[str, Any]] = {} # name -> {session, stack}
|
||||||
|
self.tool_cache: Dict[str, List[Dict[str, Any]]] = {}
|
||||||
|
self._connecting: Dict[str, asyncio.Future] = {}
|
||||||
|
self._initialized = True
|
||||||
|
|
||||||
|
async def get_tools_for_llm(self, os_filter: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Fetches tools from enabled MCP servers that match the OS filter.
|
||||||
|
"""
|
||||||
|
if not MCP_AVAILABLE:
|
||||||
|
return []
|
||||||
|
|
||||||
|
all_llm_tools = []
|
||||||
|
try:
|
||||||
|
mcp_config = self.config.config.get("ai", {}).get("mcp_servers", {})
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def _fetch(name, cfg):
|
||||||
|
if not cfg.get("enabled", True): return []
|
||||||
|
|
||||||
|
# Filter by OS if specified in config (primarily used for copilot strict matching)
|
||||||
|
auto_os = cfg.get("auto_load_on_os")
|
||||||
|
if os_filter is not None and auto_os and os_filter.lower() != auto_os.lower():
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
session = await self._ensure_connected(name, cfg)
|
||||||
|
if session:
|
||||||
|
if name in self.tool_cache: return self.tool_cache[name]
|
||||||
|
llm_tools = await self._fetch_tools_as_openai(name, session)
|
||||||
|
self.tool_cache[name] = llm_tools
|
||||||
|
return llm_tools
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return []
|
||||||
|
|
||||||
|
tasks = [ _fetch(name, cfg) for name, cfg in mcp_config.items() ]
|
||||||
|
|
||||||
|
if tasks:
|
||||||
|
results = await asyncio.gather(*tasks)
|
||||||
|
for tools in results:
|
||||||
|
all_llm_tools.extend(tools)
|
||||||
|
|
||||||
|
return all_llm_tools
|
||||||
|
|
||||||
|
async def _ensure_connected(self, name: str, cfg: Dict[str, Any]) -> Optional[Any]:
|
||||||
|
if not MCP_AVAILABLE: return None
|
||||||
|
|
||||||
|
if name in self.sessions and self.sessions[name].get("session"):
|
||||||
|
return self.sessions[name]["session"]
|
||||||
|
|
||||||
|
url = cfg.get("url")
|
||||||
|
if not url:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if name in self._connecting:
|
||||||
|
try:
|
||||||
|
return await asyncio.wait_for(asyncio.shield(self._connecting[name]), timeout=10.0)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
fut = loop.create_future()
|
||||||
|
self._connecting[name] = fut
|
||||||
|
|
||||||
|
try:
|
||||||
|
from contextlib import AsyncExitStack
|
||||||
|
stack = AsyncExitStack()
|
||||||
|
|
||||||
|
async def _do_connect():
|
||||||
|
read, write = await stack.enter_async_context(sse_client(url))
|
||||||
|
session = await stack.enter_async_context(ClientSession(read, write))
|
||||||
|
await session.initialize()
|
||||||
|
return session
|
||||||
|
|
||||||
|
session = await asyncio.wait_for(_do_connect(), timeout=15.0)
|
||||||
|
self.sessions[name] = {"session": session, "stack": stack}
|
||||||
|
fut.set_result(session)
|
||||||
|
return session
|
||||||
|
except Exception:
|
||||||
|
fut.set_result(None)
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
if name in self._connecting:
|
||||||
|
del self._connecting[name]
|
||||||
|
|
||||||
|
async def _fetch_tools_as_openai(self, server_name: str, session: Any) -> List[Dict[str, Any]]:
|
||||||
|
try:
|
||||||
|
result = await asyncio.wait_for(session.list_tools(), timeout=5.0)
|
||||||
|
openai_tools = []
|
||||||
|
for tool in result.tools:
|
||||||
|
# Use mcp_ prefix to ensure valid function name for LiteLLM/Gemini
|
||||||
|
prefixed_name = f"mcp_{server_name}__{tool.name}"
|
||||||
|
openai_tools.append({
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": prefixed_name,
|
||||||
|
"description": f"[{server_name}] {tool.description}",
|
||||||
|
"parameters": tool.inputSchema
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return openai_tools
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def call_tool(self, full_tool_name: str, arguments: Dict[str, Any]) -> Any:
|
||||||
|
"""Calls an MCP tool and returns text result."""
|
||||||
|
if not MCP_AVAILABLE:
|
||||||
|
return "Error: MCP SDK is not installed."
|
||||||
|
|
||||||
|
if "__" not in full_tool_name:
|
||||||
|
return f"Error: Tool {full_tool_name} is not a valid MCP tool."
|
||||||
|
|
||||||
|
clean_name = full_tool_name[4:] if full_tool_name.startswith("mcp_") else full_tool_name
|
||||||
|
server_name, tool_name = clean_name.split("__", 1)
|
||||||
|
|
||||||
|
if server_name not in self.sessions:
|
||||||
|
return f"Error: MCP server {server_name} is not connected."
|
||||||
|
|
||||||
|
session = self.sessions[server_name]["session"]
|
||||||
|
try:
|
||||||
|
result = await asyncio.wait_for(session.call_tool(tool_name, arguments), timeout=60.0)
|
||||||
|
text_outputs = [content.text for content in result.content if hasattr(content, "text")]
|
||||||
|
return "\n".join(text_outputs) if text_outputs else str(result)
|
||||||
|
except Exception as e:
|
||||||
|
return f"Error calling tool {tool_name} on {server_name}: {str(e)}"
|
||||||
|
|
||||||
|
async def shutdown(self):
|
||||||
|
"""Close all SSE connections."""
|
||||||
|
for name, data in self.sessions.items():
|
||||||
|
stack = data.get("stack")
|
||||||
|
if stack:
|
||||||
|
await stack.aclose()
|
||||||
|
self.sessions = {}
|
||||||
+218
-37
@@ -15,7 +15,17 @@ class ThreadLocalStream:
|
|||||||
def write(self, data):
|
def write(self, data):
|
||||||
stream = self._get_stream()
|
stream = self._get_stream()
|
||||||
if stream:
|
if stream:
|
||||||
|
import time
|
||||||
|
retries = 0
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
stream.write(data)
|
stream.write(data)
|
||||||
|
break
|
||||||
|
except BlockingIOError:
|
||||||
|
if retries > 50:
|
||||||
|
raise
|
||||||
|
time.sleep(0.01)
|
||||||
|
retries += 1
|
||||||
|
|
||||||
def flush(self):
|
def flush(self):
|
||||||
stream = self._get_stream()
|
stream = self._get_stream()
|
||||||
@@ -46,8 +56,9 @@ def _get_local():
|
|||||||
_local.console = None
|
_local.console = None
|
||||||
if not hasattr(_local, 'err_console'):
|
if not hasattr(_local, 'err_console'):
|
||||||
_local.err_console = None
|
_local.err_console = None
|
||||||
if not hasattr(_local, 'theme'):
|
if not hasattr(_local, 'theme') or _local.theme is None:
|
||||||
_local.theme = None
|
from rich.theme import Theme
|
||||||
|
_local.theme = Theme(_global_active_styles)
|
||||||
return _local
|
return _local
|
||||||
|
|
||||||
def set_thread_stream(stream):
|
def set_thread_stream(stream):
|
||||||
@@ -69,23 +80,45 @@ def get_original_stderr():
|
|||||||
|
|
||||||
# Centralized design system
|
# Centralized design system
|
||||||
STYLES = {
|
STYLES = {
|
||||||
"info": "cyan",
|
"info": "#00ffff", # Cyan
|
||||||
"warning": "yellow",
|
"warning": "#ffff00", # Yellow
|
||||||
"error": "red",
|
"error": "#ff0000", # Red
|
||||||
"success": "green",
|
"success": "#00ff00", # Green
|
||||||
"debug": "dim",
|
"debug": "#888888",
|
||||||
"header": "bold cyan",
|
"header": "bold #00ffff",
|
||||||
"key": "bold cyan",
|
"key": "bold #00ffff",
|
||||||
"border": "cyan",
|
"border": "#00ffff",
|
||||||
"pass": "bold green",
|
"pass": "bold #00ff00",
|
||||||
"fail": "bold red",
|
"fail": "bold #ff0000",
|
||||||
"engineer": "blue",
|
"engineer": "#5fafff", # Sky Blue (lighter than pure blue)
|
||||||
"architect": "medium_purple",
|
"architect": "#9370db", # Medium Purple
|
||||||
"ai_status": "bold green",
|
"ai_status": "bold #00ff00",
|
||||||
"user_prompt": "bold cyan",
|
"user_prompt": "bold #00afd7", # Deep Sky Blue / Soft Cyan
|
||||||
"unavailable": "orange3",
|
"unavailable": "#d78700",
|
||||||
|
"contrast": "#bbbbbb",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
LIGHT_THEME = {
|
||||||
|
"info": "#00008b", # Navy Blue
|
||||||
|
"warning": "#d78700", # Orange
|
||||||
|
"error": "#cd0000", # Dark Red
|
||||||
|
"success": "#006400", # Dark Green
|
||||||
|
"debug": "#777777",
|
||||||
|
"header": "bold #00008b",
|
||||||
|
"key": "bold #00008b",
|
||||||
|
"border": "#00008b",
|
||||||
|
"pass": "bold #006400",
|
||||||
|
"fail": "bold #cd0000",
|
||||||
|
"engineer": "#00008b",
|
||||||
|
"architect": "#8b008b", # Dark Magenta
|
||||||
|
"ai_status": "bold #006400",
|
||||||
|
"user_prompt": "bold #00008b",
|
||||||
|
"unavailable": "#666666",
|
||||||
|
"contrast": "#777777",
|
||||||
|
}
|
||||||
|
|
||||||
|
_global_active_styles = STYLES.copy()
|
||||||
|
|
||||||
def _get_console():
|
def _get_console():
|
||||||
local = _get_local()
|
local = _get_local()
|
||||||
|
|
||||||
@@ -171,7 +204,7 @@ def connpy_theme():
|
|||||||
local = _get_local()
|
local = _get_local()
|
||||||
if local.theme is None:
|
if local.theme is None:
|
||||||
from rich.theme import Theme
|
from rich.theme import Theme
|
||||||
local.theme = Theme(STYLES)
|
local.theme = Theme(_global_active_styles)
|
||||||
return local.theme
|
return local.theme
|
||||||
|
|
||||||
def apply_theme(user_styles=None):
|
def apply_theme(user_styles=None):
|
||||||
@@ -179,6 +212,7 @@ def apply_theme(user_styles=None):
|
|||||||
Updates the global console themes with user-defined styles.
|
Updates the global console themes with user-defined styles.
|
||||||
If a style is missing in user_styles, it falls back to the default in STYLES.
|
If a style is missing in user_styles, it falls back to the default in STYLES.
|
||||||
"""
|
"""
|
||||||
|
global _global_active_styles
|
||||||
local = _get_local()
|
local = _get_local()
|
||||||
from rich.theme import Theme
|
from rich.theme import Theme
|
||||||
|
|
||||||
@@ -190,6 +224,7 @@ def apply_theme(user_styles=None):
|
|||||||
if key in active_styles:
|
if key in active_styles:
|
||||||
active_styles[key] = value
|
active_styles[key] = value
|
||||||
|
|
||||||
|
_global_active_styles = active_styles
|
||||||
local.theme = Theme(active_styles)
|
local.theme = Theme(active_styles)
|
||||||
if local.console:
|
if local.console:
|
||||||
local.console.push_theme(local.theme)
|
local.console.push_theme(local.theme)
|
||||||
@@ -202,10 +237,15 @@ def _format_multiline(tag, message, style=None):
|
|||||||
message = str(message)
|
message = str(message)
|
||||||
lines = message.splitlines()
|
lines = message.splitlines()
|
||||||
if not lines:
|
if not lines:
|
||||||
return f"[{style}]\\[{tag}][/{style}]" if style else f"\\[{tag}]"
|
if style:
|
||||||
|
return f"[{style}]\\[{tag}][/{style}]"
|
||||||
|
return f"\\[{tag}]"
|
||||||
|
|
||||||
# Apply style to the tag if provided
|
# Apply style to the tag if provided
|
||||||
styled_tag = f"[{style}]\\[{tag}][/{style}]" if style else f"\\[{tag}]"
|
styled_tag = f"[{style}]\\[{tag}][/{style}]" if style else f"\\[{tag}]"
|
||||||
|
if style:
|
||||||
|
# Include brackets in the styling
|
||||||
|
styled_tag = f"[{style}]\\[{tag}][/{style}]"
|
||||||
formatted = [f"{styled_tag} {lines[0]}"]
|
formatted = [f"{styled_tag} {lines[0]}"]
|
||||||
|
|
||||||
# Indent subsequent lines
|
# Indent subsequent lines
|
||||||
@@ -317,7 +357,7 @@ def test_panel(unique, output, status, result):
|
|||||||
_get_console().print(Panel(Group(Text(), code_block, test_results), title=title_line, width=cols, border_style=border))
|
_get_console().print(Panel(Group(Text(), code_block, test_results), title=title_line, width=cols, border_style=border))
|
||||||
|
|
||||||
def test_summary(results):
|
def test_summary(results):
|
||||||
"""Print an aggregate summary of multiple test results."""
|
"""Print an aggregate summary of multiple test results in a single panel."""
|
||||||
from rich.panel import Panel
|
from rich.panel import Panel
|
||||||
from rich.text import Text
|
from rich.text import Text
|
||||||
from rich.console import Group
|
from rich.console import Group
|
||||||
@@ -328,26 +368,96 @@ def test_summary(results):
|
|||||||
except OSError:
|
except OSError:
|
||||||
cols = 80
|
cols = 80
|
||||||
|
|
||||||
for node, test_result in results.items():
|
summary_content = Text()
|
||||||
status_code = 0 if test_result and all(test_result.values()) else 1
|
total_passed = 0
|
||||||
if status_code == 0:
|
total_failed = 0
|
||||||
status_str = "[pass]✓ PASS[/pass]"
|
total_partial = 0
|
||||||
border = "pass"
|
|
||||||
|
if not results:
|
||||||
|
summary_content.append(" No test results found.\n", style="error")
|
||||||
else:
|
else:
|
||||||
status_str = f"[fail]✗ FAIL[/fail]"
|
for node, test_result in results.items():
|
||||||
border = "fail"
|
summary_content.append(f"• ", style="border")
|
||||||
|
summary_content.append(f"{node.ljust(40)}", style="bold")
|
||||||
|
|
||||||
title_line = f"[bold]{node}[/bold] — {status_str}"
|
if test_result:
|
||||||
|
passed_count = sum(1 for v in test_result.values() if v)
|
||||||
|
total_count = len(test_result)
|
||||||
|
|
||||||
test_output = Text()
|
if passed_count == total_count:
|
||||||
test_output.append("TEST RESULTS:\n", style="header")
|
total_passed += 1
|
||||||
max_key_len = max(len(k) for k in test_result.keys()) if test_result else 0
|
node_style = "success"
|
||||||
for k, v in (test_result.items() if test_result else []):
|
mark = "✓ PASS"
|
||||||
mark = "✓" if v else "✗"
|
elif passed_count > 0:
|
||||||
style = "success" if v else "error"
|
total_partial += 1
|
||||||
test_output.append(f" {k.ljust(max_key_len)} {mark}\n", style=style)
|
node_style = "warning"
|
||||||
|
mark = f"⚠ PARTIAL ({passed_count}/{total_count})"
|
||||||
|
else:
|
||||||
|
total_failed += 1
|
||||||
|
node_style = "error"
|
||||||
|
mark = "✗ FAIL"
|
||||||
|
|
||||||
_get_console().print(Panel(Group(Text(), test_output), title=title_line, width=cols, border_style=border))
|
summary_content.append(f" {mark}\n", style=node_style)
|
||||||
|
for k, v in test_result.items():
|
||||||
|
res_mark = "✓" if v else "✗"
|
||||||
|
res_style = "success" if v else "error"
|
||||||
|
summary_content.append(f" {k.ljust(38)} {res_mark}\n", style=res_style)
|
||||||
|
else:
|
||||||
|
total_failed += 1
|
||||||
|
summary_content.append(" ✗ FAIL\n", style="error")
|
||||||
|
summary_content.append(" No results (execution failed)\n", style="error")
|
||||||
|
|
||||||
|
status_parts = []
|
||||||
|
if total_passed: status_parts.append(f"[pass]{total_passed} PASSED[/pass]")
|
||||||
|
if total_partial: status_parts.append(f"[warning]{total_partial} PARTIAL[/warning]")
|
||||||
|
if total_failed: status_parts.append(f"[fail]{total_failed} FAILED[/fail]")
|
||||||
|
|
||||||
|
status_str = " | ".join(status_parts) if status_parts else "[error]NO RESULTS[/error]"
|
||||||
|
title_line = f"AGGREGATE TEST SUMMARY — {status_str}"
|
||||||
|
|
||||||
|
_get_console().print(Panel(Group(Text(), summary_content), title=title_line, width=cols, border_style="border"))
|
||||||
|
|
||||||
|
def run_summary(results):
|
||||||
|
"""Print an aggregate summary of multiple execution results in a single panel."""
|
||||||
|
from rich.panel import Panel
|
||||||
|
from rich.text import Text
|
||||||
|
from rich.console import Group
|
||||||
|
import os
|
||||||
|
|
||||||
|
try:
|
||||||
|
cols, _ = os.get_terminal_size()
|
||||||
|
except OSError:
|
||||||
|
cols = 80
|
||||||
|
|
||||||
|
summary_content = Text()
|
||||||
|
total_ok = 0
|
||||||
|
total_err = 0
|
||||||
|
|
||||||
|
if not results:
|
||||||
|
summary_content.append(" No execution results found.\n", style="error")
|
||||||
|
else:
|
||||||
|
for node, data in results.items():
|
||||||
|
summary_content.append(f"• ", style="border")
|
||||||
|
summary_content.append(f"{node.ljust(40)}", style="bold")
|
||||||
|
|
||||||
|
# Check if we have a status dict or just output (for backward compatibility)
|
||||||
|
status = data.get("status", 0) if isinstance(data, dict) else 0
|
||||||
|
|
||||||
|
if status == 0:
|
||||||
|
total_ok += 1
|
||||||
|
summary_content.append(f" ✓ DONE\n", style="success")
|
||||||
|
else:
|
||||||
|
total_err += 1
|
||||||
|
summary_content.append(f" ✗ FAIL({status})\n", style="error")
|
||||||
|
|
||||||
|
status_parts = []
|
||||||
|
if total_ok: status_parts.append(f"[success]{total_ok} DONE[/success]")
|
||||||
|
if total_err: status_parts.append(f"[error]{total_err} FAILED[/error]")
|
||||||
|
|
||||||
|
status_str = " | ".join(status_parts) if status_parts else "[error]NO RESULTS[/error]"
|
||||||
|
title_line = f"AGGREGATE EXECUTION SUMMARY — {status_str}"
|
||||||
|
|
||||||
|
_get_console().print(Panel(Group(Text(), summary_content), title=title_line, width=cols, border_style="border"))
|
||||||
|
|
||||||
def header(text):
|
def header(text):
|
||||||
"""Print a section header."""
|
"""Print a section header."""
|
||||||
@@ -392,7 +502,78 @@ class _ThemeProxy:
|
|||||||
local = _get_local()
|
local = _get_local()
|
||||||
if local.theme is None:
|
if local.theme is None:
|
||||||
from rich.theme import Theme
|
from rich.theme import Theme
|
||||||
local.theme = Theme(STYLES)
|
local.theme = Theme(_global_active_styles)
|
||||||
return getattr(local.theme, name)
|
return getattr(local.theme, name)
|
||||||
|
|
||||||
connpy_theme = _ThemeProxy()
|
connpy_theme = _ThemeProxy()
|
||||||
|
|
||||||
|
class BlockMarkdownRenderer:
|
||||||
|
"""
|
||||||
|
Block-buffered streaming markdown renderer.
|
||||||
|
Accumulates text until block boundaries are detected,
|
||||||
|
then renders complete blocks using Rich's Markdown.
|
||||||
|
"""
|
||||||
|
def __init__(self, console=None):
|
||||||
|
from rich.console import Console as RichConsole
|
||||||
|
from .printer import connpy_theme, get_original_stdout
|
||||||
|
self._console = console or RichConsole(
|
||||||
|
theme=connpy_theme, file=get_original_stdout()
|
||||||
|
)
|
||||||
|
self._line_buf = "" # chars waiting for \n
|
||||||
|
self._block_lines = [] # complete lines for current block
|
||||||
|
self._in_code_block = False
|
||||||
|
|
||||||
|
def feed(self, text):
|
||||||
|
self._line_buf += text
|
||||||
|
while '\n' in self._line_buf:
|
||||||
|
idx = self._line_buf.index('\n')
|
||||||
|
line = self._line_buf[:idx + 1]
|
||||||
|
self._line_buf = self._line_buf[idx + 1:]
|
||||||
|
self._process_line(line)
|
||||||
|
|
||||||
|
def flush(self):
|
||||||
|
if self._line_buf:
|
||||||
|
self._block_lines.append(self._line_buf)
|
||||||
|
self._line_buf = ""
|
||||||
|
self._flush_block()
|
||||||
|
|
||||||
|
def _process_line(self, line):
|
||||||
|
stripped = line.strip()
|
||||||
|
|
||||||
|
if stripped.startswith('```'):
|
||||||
|
if not self._in_code_block:
|
||||||
|
# Flush accumulated text before code block
|
||||||
|
self._flush_block()
|
||||||
|
self._in_code_block = True
|
||||||
|
self._block_lines.append(line)
|
||||||
|
else:
|
||||||
|
# Include closing fence and flush code block
|
||||||
|
self._block_lines.append(line)
|
||||||
|
self._in_code_block = False
|
||||||
|
self._flush_block()
|
||||||
|
return
|
||||||
|
|
||||||
|
if self._in_code_block:
|
||||||
|
self._block_lines.append(line)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Blank line = paragraph break
|
||||||
|
if stripped == '':
|
||||||
|
self._block_lines.append(line)
|
||||||
|
self._flush_block()
|
||||||
|
return
|
||||||
|
|
||||||
|
self._block_lines.append(line)
|
||||||
|
|
||||||
|
def _flush_block(self):
|
||||||
|
if not self._block_lines:
|
||||||
|
return
|
||||||
|
block_text = ''.join(self._block_lines).strip()
|
||||||
|
self._block_lines = []
|
||||||
|
if not block_text:
|
||||||
|
return
|
||||||
|
from rich.markdown import Markdown
|
||||||
|
self._console.print(Markdown(block_text))
|
||||||
|
|
||||||
|
# Alias for backward compatibility
|
||||||
|
IncrementalMarkdownParser = BlockMarkdownRenderer
|
||||||
|
|||||||
@@ -65,9 +65,11 @@ service ImportExportService {
|
|||||||
service AIService {
|
service AIService {
|
||||||
rpc ask (stream AskRequest) returns (stream AIResponse) {}
|
rpc ask (stream AskRequest) returns (stream AIResponse) {}
|
||||||
rpc confirm (StringRequest) returns (BoolResponse) {}
|
rpc confirm (StringRequest) returns (BoolResponse) {}
|
||||||
|
rpc ask_copilot (CopilotRequest) returns (CopilotResponse) {}
|
||||||
rpc list_sessions (google.protobuf.Empty) returns (ValueResponse) {}
|
rpc list_sessions (google.protobuf.Empty) returns (ValueResponse) {}
|
||||||
rpc delete_session (StringRequest) returns (google.protobuf.Empty) {}
|
rpc delete_session (StringRequest) returns (google.protobuf.Empty) {}
|
||||||
rpc configure_provider (ProviderRequest) returns (google.protobuf.Empty) {}
|
rpc configure_provider (ProviderRequest) returns (google.protobuf.Empty) {}
|
||||||
|
rpc configure_mcp (MCPRequest) returns (google.protobuf.Empty) {}
|
||||||
rpc load_session_data (StringRequest) returns (StructResponse) {}
|
rpc load_session_data (StringRequest) returns (StructResponse) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,12 +91,24 @@ message InteractRequest {
|
|||||||
int32 cols = 5;
|
int32 cols = 5;
|
||||||
int32 rows = 6;
|
int32 rows = 6;
|
||||||
string connection_params_json = 7;
|
string connection_params_json = 7;
|
||||||
|
// Copilot fields
|
||||||
|
string copilot_question = 8;
|
||||||
|
string copilot_action = 9;
|
||||||
|
string copilot_context_buffer = 10;
|
||||||
|
string copilot_node_info_json = 13;
|
||||||
}
|
}
|
||||||
|
|
||||||
message InteractResponse {
|
message InteractResponse {
|
||||||
bytes stdout_data = 1;
|
bytes stdout_data = 1;
|
||||||
bool success = 2;
|
bool success = 2;
|
||||||
string error_message = 3;
|
string error_message = 3;
|
||||||
|
// Copilot fields
|
||||||
|
bool copilot_prompt = 4;
|
||||||
|
string copilot_buffer_preview = 5;
|
||||||
|
string copilot_response_json = 6;
|
||||||
|
string copilot_node_info_json = 7;
|
||||||
|
string copilot_stream_chunk = 8;
|
||||||
|
string copilot_injected_command = 9;
|
||||||
}
|
}
|
||||||
|
|
||||||
message FilterRequest {
|
message FilterRequest {
|
||||||
@@ -176,16 +190,20 @@ message RunRequest {
|
|||||||
string prompt = 4;
|
string prompt = 4;
|
||||||
int32 parallel = 5;
|
int32 parallel = 5;
|
||||||
google.protobuf.Struct vars = 6;
|
google.protobuf.Struct vars = 6;
|
||||||
|
int32 timeout = 7;
|
||||||
|
string name = 8;
|
||||||
}
|
}
|
||||||
|
|
||||||
message TestRequest {
|
message TestRequest {
|
||||||
repeated string nodes = 1;
|
repeated string nodes = 1;
|
||||||
repeated string commands = 2;
|
repeated string commands = 2;
|
||||||
string expected = 3;
|
repeated string expected = 3;
|
||||||
string folder = 4;
|
string folder = 4;
|
||||||
string prompt = 5;
|
string prompt = 5;
|
||||||
int32 parallel = 6;
|
int32 parallel = 6;
|
||||||
google.protobuf.Struct vars = 7;
|
google.protobuf.Struct vars = 7;
|
||||||
|
int32 timeout = 8;
|
||||||
|
string name = 9;
|
||||||
}
|
}
|
||||||
|
|
||||||
message ScriptRequest {
|
message ScriptRequest {
|
||||||
@@ -253,3 +271,24 @@ message FullReplaceRequest {
|
|||||||
google.protobuf.Struct connections = 1;
|
google.protobuf.Struct connections = 1;
|
||||||
google.protobuf.Struct profiles = 2;
|
google.protobuf.Struct profiles = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message CopilotRequest {
|
||||||
|
string terminal_buffer = 1;
|
||||||
|
string user_question = 2;
|
||||||
|
string node_info_json = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message CopilotResponse {
|
||||||
|
repeated string commands = 1;
|
||||||
|
string guide = 2;
|
||||||
|
string risk_level = 3;
|
||||||
|
string error = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
message MCPRequest {
|
||||||
|
string name = 1;
|
||||||
|
string url = 2;
|
||||||
|
bool enabled = 3;
|
||||||
|
string auto_load_on_os = 4;
|
||||||
|
bool remove = 5;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,143 @@
|
|||||||
|
import re
|
||||||
from .base import BaseService
|
from .base import BaseService
|
||||||
from .exceptions import InvalidConfigurationError
|
from .exceptions import InvalidConfigurationError
|
||||||
|
from connpy.utils import log_cleaner
|
||||||
|
|
||||||
class AIService(BaseService):
|
class AIService(BaseService):
|
||||||
"""Business logic for interacting with AI agents and LLM configurations."""
|
"""Business logic for interacting with AI agents and LLM configurations."""
|
||||||
|
|
||||||
|
def build_context_blocks(self, raw_bytes: bytes, cmd_byte_positions: list, node_info: dict, last_line: str = "") -> list:
|
||||||
|
"""Identifies command blocks in the terminal history."""
|
||||||
|
blocks = []
|
||||||
|
if not raw_bytes:
|
||||||
|
return blocks
|
||||||
|
|
||||||
|
default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$'
|
||||||
|
device_prompt = node_info.get("prompt", default_prompt) if isinstance(node_info, dict) else default_prompt
|
||||||
|
prompt_re_str = re.sub(r'(?<!\\)\$', '', device_prompt)
|
||||||
|
try:
|
||||||
|
prompt_re = re.compile(prompt_re_str)
|
||||||
|
except Exception:
|
||||||
|
prompt_re = re.compile(re.sub(r'(?<!\\)\$', '', default_prompt))
|
||||||
|
|
||||||
|
parsed_positions = []
|
||||||
|
if cmd_byte_positions and len(cmd_byte_positions) >= 1:
|
||||||
|
for i in range(1, len(cmd_byte_positions)):
|
||||||
|
pos, known_cmd = cmd_byte_positions[i]
|
||||||
|
prev_pos = cmd_byte_positions[i-1][0]
|
||||||
|
|
||||||
|
if known_cmd:
|
||||||
|
prev_chunk = raw_bytes[prev_pos:pos]
|
||||||
|
prev_cleaned = log_cleaner(prev_chunk.decode(errors='replace'))
|
||||||
|
prev_lines = [l for l in prev_cleaned.split('\n') if l.strip()]
|
||||||
|
prompt_text = prev_lines[-1].strip() if prev_lines else ""
|
||||||
|
preview = f"{prompt_text}{known_cmd}" if prompt_text else known_cmd
|
||||||
|
parsed_positions.append({"pos": pos, "type": "VALID_CMD", "preview": preview[:80]})
|
||||||
|
else:
|
||||||
|
chunk = raw_bytes[prev_pos:pos]
|
||||||
|
cleaned = log_cleaner(chunk.decode(errors='replace'))
|
||||||
|
lines = [l for l in cleaned.split('\n') if l.strip()]
|
||||||
|
preview = lines[-1].strip() if lines else ""
|
||||||
|
|
||||||
|
if preview:
|
||||||
|
match = prompt_re.search(preview)
|
||||||
|
if match:
|
||||||
|
cmd_text = preview[match.end():].strip()
|
||||||
|
if cmd_text:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "VALID_CMD", "preview": preview[:80]})
|
||||||
|
else:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "EMPTY_PROMPT", "preview": ""})
|
||||||
|
else:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "SCROLLING", "preview": ""})
|
||||||
|
else:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "SCROLLING", "preview": ""})
|
||||||
|
|
||||||
|
last_newline = raw_bytes.rfind(b'\n')
|
||||||
|
current_prompt_pos = last_newline + 1 if last_newline != -1 else 0
|
||||||
|
current_end = len(raw_bytes)
|
||||||
|
|
||||||
|
for i, item in enumerate(parsed_positions):
|
||||||
|
if item["type"] == "VALID_CMD":
|
||||||
|
start_pos = item["pos"]
|
||||||
|
preview = item["preview"]
|
||||||
|
|
||||||
|
# Find the end position: next VALID_CMD or EMPTY_PROMPT
|
||||||
|
end_pos = current_prompt_pos
|
||||||
|
for j in range(i + 1, len(parsed_positions)):
|
||||||
|
next_item = parsed_positions[j]
|
||||||
|
if next_item["type"] in ("VALID_CMD", "EMPTY_PROMPT"):
|
||||||
|
end_pos = next_item["pos"]
|
||||||
|
break
|
||||||
|
|
||||||
|
blocks.append((start_pos, end_pos, preview))
|
||||||
|
|
||||||
|
# Always ensure there is a final block representing the current prompt
|
||||||
|
if not blocks:
|
||||||
|
blocks.append((current_prompt_pos, current_end, last_line[:80] if last_line else "CURRENT CONTEXT"))
|
||||||
|
elif blocks[-1][0] < current_prompt_pos:
|
||||||
|
blocks.append((current_prompt_pos, current_end, last_line[:80] if last_line else "CURRENT CONTEXT"))
|
||||||
|
|
||||||
|
return blocks
|
||||||
|
|
||||||
|
def process_copilot_input(self, input_text: str, session_state: dict) -> dict:
|
||||||
|
"""Parses slash commands and manages session state. Returns directive dict."""
|
||||||
|
text = input_text.strip()
|
||||||
|
if not text.startswith('/'):
|
||||||
|
return {"action": "execute", "clean_prompt": text, "overrides": {}}
|
||||||
|
|
||||||
|
parts = text.split(maxsplit=1)
|
||||||
|
cmd = parts[0].lower()
|
||||||
|
args = parts[1] if len(parts) > 1 else ""
|
||||||
|
|
||||||
|
# 1. State Commands (Persistent)
|
||||||
|
if cmd == "/os":
|
||||||
|
if args:
|
||||||
|
session_state['os'] = args
|
||||||
|
return {"action": "state_update", "message": f"OS context changed to {args}"}
|
||||||
|
elif cmd == "/prompt":
|
||||||
|
if args:
|
||||||
|
session_state['prompt'] = args
|
||||||
|
return {"action": "state_update", "message": f"Prompt regex changed to {args}"}
|
||||||
|
elif cmd == "/memorize":
|
||||||
|
if args:
|
||||||
|
session_state['memories'].append(args)
|
||||||
|
return {"action": "state_update", "message": f"Memory added: {args}"}
|
||||||
|
elif cmd == "/clear":
|
||||||
|
session_state['memories'] = []
|
||||||
|
return {"action": "state_update", "message": "Memory cleared"}
|
||||||
|
|
||||||
|
# 2. Hybrid Commands
|
||||||
|
elif cmd == "/architect":
|
||||||
|
if not args:
|
||||||
|
session_state['persona'] = 'architect'
|
||||||
|
return {"action": "state_update", "message": "Persona set to Architect"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"persona": "architect"}}
|
||||||
|
|
||||||
|
elif cmd == "/engineer":
|
||||||
|
if not args:
|
||||||
|
session_state['persona'] = 'engineer'
|
||||||
|
return {"action": "state_update", "message": "Persona set to Engineer"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"persona": "engineer"}}
|
||||||
|
|
||||||
|
elif cmd == "/trust":
|
||||||
|
if not args:
|
||||||
|
session_state['trust_mode'] = True
|
||||||
|
return {"action": "state_update", "message": "Auto-execute (trust) enabled for session"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"trust": True}}
|
||||||
|
|
||||||
|
elif cmd == "/untrust":
|
||||||
|
if not args:
|
||||||
|
session_state['trust_mode'] = False
|
||||||
|
return {"action": "state_update", "message": "Auto-execute (trust) disabled for session"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"trust": False}}
|
||||||
|
|
||||||
|
# Unknown command, execute normally
|
||||||
|
return {"action": "execute", "clean_prompt": text, "overrides": {}}
|
||||||
|
|
||||||
def ask(self, input_text, dryrun=False, chat_history=None, status=None, debug=False, session_id=None, console=None, chunk_callback=None, confirm_handler=None, trust=False, **overrides):
|
def ask(self, input_text, dryrun=False, chat_history=None, status=None, debug=False, session_id=None, console=None, chunk_callback=None, confirm_handler=None, trust=False, **overrides):
|
||||||
"""Send a prompt to the AI agent."""
|
"""Send a prompt to the AI agent."""
|
||||||
from connpy.ai import ai
|
from connpy.ai import ai
|
||||||
@@ -17,6 +151,21 @@ class AIService(BaseService):
|
|||||||
agent = ai(self.config, console=console)
|
agent = ai(self.config, console=console)
|
||||||
return agent.confirm(input_text)
|
return agent.confirm(input_text)
|
||||||
|
|
||||||
|
def ask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
|
||||||
|
"""Ask the AI copilot for terminal assistance."""
|
||||||
|
from connpy.ai import ai, run_ai_async
|
||||||
|
agent = ai(self.config)
|
||||||
|
future = run_ai_async(agent.aask_copilot(terminal_buffer, user_question, node_info, chunk_callback=chunk_callback))
|
||||||
|
return future.result()
|
||||||
|
|
||||||
|
async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
|
||||||
|
"""Ask the AI copilot for terminal assistance asynchronously."""
|
||||||
|
from connpy.ai import ai, run_ai_async
|
||||||
|
import asyncio
|
||||||
|
agent = ai(self.config)
|
||||||
|
future = run_ai_async(agent.aask_copilot(terminal_buffer, user_question, node_info, chunk_callback=chunk_callback))
|
||||||
|
return await asyncio.wrap_future(future)
|
||||||
|
|
||||||
|
|
||||||
def list_sessions(self):
|
def list_sessions(self):
|
||||||
"""Return a list of all saved AI sessions."""
|
"""Return a list of all saved AI sessions."""
|
||||||
@@ -45,6 +194,40 @@ class AIService(BaseService):
|
|||||||
self.config.config["ai"] = settings
|
self.config.config["ai"] = settings
|
||||||
self.config._saveconfig(self.config.file)
|
self.config._saveconfig(self.config.file)
|
||||||
|
|
||||||
|
def configure_mcp(self, name, url=None, enabled=None, auto_load_on_os=None, remove=False):
|
||||||
|
"""Update MCP server settings in the configuration with smart merging."""
|
||||||
|
ai_settings = self.config.config.get("ai", {})
|
||||||
|
mcp_servers = ai_settings.get("mcp_servers", {})
|
||||||
|
|
||||||
|
if remove:
|
||||||
|
if name in mcp_servers:
|
||||||
|
del mcp_servers[name]
|
||||||
|
else:
|
||||||
|
# Get existing or new
|
||||||
|
server_cfg = mcp_servers.get(name, {})
|
||||||
|
|
||||||
|
# Partial updates
|
||||||
|
if url is not None:
|
||||||
|
server_cfg["url"] = url
|
||||||
|
|
||||||
|
if enabled is not None:
|
||||||
|
server_cfg["enabled"] = bool(enabled)
|
||||||
|
elif "enabled" not in server_cfg:
|
||||||
|
server_cfg["enabled"] = True # Default for new entries
|
||||||
|
|
||||||
|
if auto_load_on_os is not None:
|
||||||
|
if auto_load_on_os == "": # Explicit clear
|
||||||
|
if "auto_load_on_os" in server_cfg:
|
||||||
|
del server_cfg["auto_load_on_os"]
|
||||||
|
else:
|
||||||
|
server_cfg["auto_load_on_os"] = auto_load_on_os
|
||||||
|
|
||||||
|
mcp_servers[name] = server_cfg
|
||||||
|
|
||||||
|
ai_settings["mcp_servers"] = mcp_servers
|
||||||
|
self.config.config["ai"] = ai_settings
|
||||||
|
self.config._saveconfig(self.config.file)
|
||||||
|
|
||||||
def load_session_data(self, session_id):
|
def load_session_data(self, session_id):
|
||||||
"""Load a session's raw data by ID."""
|
"""Load a session's raw data by ID."""
|
||||||
from connpy.ai import ai
|
from connpy.ai import ai
|
||||||
|
|||||||
@@ -70,6 +70,10 @@ class ConfigService(BaseService):
|
|||||||
if not isinstance(user_styles, dict):
|
if not isinstance(user_styles, dict):
|
||||||
raise InvalidConfigurationError("Theme file must be a YAML dictionary.")
|
raise InvalidConfigurationError("Theme file must be a YAML dictionary.")
|
||||||
|
|
||||||
|
# Support both direct styles and nested under 'theme' key
|
||||||
|
if "theme" in user_styles and isinstance(user_styles["theme"], dict):
|
||||||
|
user_styles = user_styles["theme"]
|
||||||
|
|
||||||
# Filter for valid styles only (prevent junk in config)
|
# Filter for valid styles only (prevent junk in config)
|
||||||
valid_styles = {k: v for k, v in user_styles.items() if k in STYLES}
|
valid_styles = {k: v for k, v in user_styles.items() if k in STYLES}
|
||||||
|
|
||||||
|
|||||||
@@ -14,11 +14,12 @@ class ExecutionService(BaseService):
|
|||||||
commands: List[str],
|
commands: List[str],
|
||||||
variables: Optional[Dict[str, Any]] = None,
|
variables: Optional[Dict[str, Any]] = None,
|
||||||
parallel: int = 10,
|
parallel: int = 10,
|
||||||
timeout: int = 10,
|
timeout: int = 20,
|
||||||
folder: Optional[str] = None,
|
folder: Optional[str] = None,
|
||||||
prompt: Optional[str] = None,
|
prompt: Optional[str] = None,
|
||||||
on_node_complete: Optional[Callable] = None,
|
on_node_complete: Optional[Callable] = None,
|
||||||
logger: Optional[Callable] = None
|
logger: Optional[Callable] = None,
|
||||||
|
name: Optional[str] = None
|
||||||
) -> Dict[str, str]:
|
) -> Dict[str, str]:
|
||||||
|
|
||||||
"""Execute commands on a set of nodes."""
|
"""Execute commands on a set of nodes."""
|
||||||
@@ -42,7 +43,15 @@ class ExecutionService(BaseService):
|
|||||||
logger=logger
|
logger=logger
|
||||||
)
|
)
|
||||||
|
|
||||||
return results
|
# Combine output and status for the caller
|
||||||
|
full_results = {}
|
||||||
|
for unique in results:
|
||||||
|
full_results[unique] = {
|
||||||
|
"output": results[unique],
|
||||||
|
"status": executor.status.get(unique, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
return full_results
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ConnpyError(f"Execution failed: {e}")
|
raise ConnpyError(f"Execution failed: {e}")
|
||||||
|
|
||||||
@@ -53,10 +62,12 @@ class ExecutionService(BaseService):
|
|||||||
expected: List[str],
|
expected: List[str],
|
||||||
variables: Optional[Dict[str, Any]] = None,
|
variables: Optional[Dict[str, Any]] = None,
|
||||||
parallel: int = 10,
|
parallel: int = 10,
|
||||||
timeout: int = 10,
|
timeout: int = 20,
|
||||||
|
folder: Optional[str] = None,
|
||||||
prompt: Optional[str] = None,
|
prompt: Optional[str] = None,
|
||||||
on_node_complete: Optional[Callable] = None,
|
on_node_complete: Optional[Callable] = None,
|
||||||
logger: Optional[Callable] = None
|
logger: Optional[Callable] = None,
|
||||||
|
name: Optional[str] = None
|
||||||
) -> Dict[str, Dict[str, bool]]:
|
) -> Dict[str, Dict[str, bool]]:
|
||||||
|
|
||||||
"""Run commands and verify expected output on a set of nodes."""
|
"""Run commands and verify expected output on a set of nodes."""
|
||||||
@@ -75,6 +86,7 @@ class ExecutionService(BaseService):
|
|||||||
vars=variables,
|
vars=variables,
|
||||||
parallel=parallel,
|
parallel=parallel,
|
||||||
timeout=timeout,
|
timeout=timeout,
|
||||||
|
folder=folder,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
on_complete=on_node_complete,
|
on_complete=on_node_complete,
|
||||||
logger=logger
|
logger=logger
|
||||||
@@ -96,37 +108,52 @@ class ExecutionService(BaseService):
|
|||||||
|
|
||||||
return self.run_commands(nodes_filter, commands, parallel=parallel)
|
return self.run_commands(nodes_filter, commands, parallel=parallel)
|
||||||
|
|
||||||
def run_yaml_playbook(self, playbook_path: str, parallel: int = 10) -> Dict[str, Any]:
|
def run_yaml_playbook(self, playbook_data: str, parallel: int = 10) -> Dict[str, Any]:
|
||||||
"""Run a structured Connpy YAML automation playbook."""
|
"""Run a structured Connpy YAML automation playbook (from path or content)."""
|
||||||
if not os.path.exists(playbook_path):
|
playbook = None
|
||||||
raise ConnpyError(f"Playbook file not found: {playbook_path}")
|
if playbook_data.startswith("---YAML---\n"):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(playbook_path, "r") as f:
|
content = playbook_data[len("---YAML---\n"):]
|
||||||
|
playbook = yaml.load(content, Loader=yaml.FullLoader)
|
||||||
|
except Exception as e:
|
||||||
|
raise ConnpyError(f"Failed to parse YAML content: {e}")
|
||||||
|
else:
|
||||||
|
if not os.path.exists(playbook_data):
|
||||||
|
raise ConnpyError(f"Playbook file not found: {playbook_data}")
|
||||||
|
try:
|
||||||
|
with open(playbook_data, "r") as f:
|
||||||
playbook = yaml.load(f, Loader=yaml.FullLoader)
|
playbook = yaml.load(f, Loader=yaml.FullLoader)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ConnpyError(f"Failed to load playbook {playbook_path}: {e}")
|
raise ConnpyError(f"Failed to load playbook {playbook_data}: {e}")
|
||||||
|
|
||||||
# Basic validation
|
# Basic validation
|
||||||
if not isinstance(playbook, dict) or "nodes" not in playbook or "commands" not in playbook:
|
if not isinstance(playbook, dict) or "nodes" not in playbook or "commands" not in playbook:
|
||||||
raise ConnpyError("Invalid playbook format: missing 'nodes' or 'commands' keys.")
|
raise ConnpyError("Invalid playbook format: missing 'nodes' or 'commands' keys.")
|
||||||
|
|
||||||
action = playbook.get("action", "run")
|
action = playbook.get("action", "run")
|
||||||
|
options = playbook.get("options", {})
|
||||||
|
|
||||||
|
# Extract all fields similar to RunHandler.cli_run
|
||||||
|
exec_args = {
|
||||||
|
"nodes_filter": playbook["nodes"],
|
||||||
|
"commands": playbook["commands"],
|
||||||
|
"variables": playbook.get("variables"),
|
||||||
|
"parallel": options.get("parallel", parallel),
|
||||||
|
"timeout": playbook.get("timeout", options.get("timeout", 20)),
|
||||||
|
"prompt": options.get("prompt"),
|
||||||
|
"name": playbook.get("name", "Task")
|
||||||
|
}
|
||||||
|
|
||||||
|
# Map 'output' field to folder path if it's not stdout/null
|
||||||
|
output_cfg = playbook.get("output")
|
||||||
|
if output_cfg not in [None, "stdout"]:
|
||||||
|
exec_args["folder"] = output_cfg
|
||||||
|
|
||||||
if action == "run":
|
if action == "run":
|
||||||
return self.run_commands(
|
return self.run_commands(**exec_args)
|
||||||
nodes_filter=playbook["nodes"],
|
|
||||||
commands=playbook["commands"],
|
|
||||||
parallel=parallel,
|
|
||||||
timeout=playbook.get("timeout", 10)
|
|
||||||
)
|
|
||||||
elif action == "test":
|
elif action == "test":
|
||||||
return self.test_commands(
|
exec_args["expected"] = playbook.get("expected", [])
|
||||||
nodes_filter=playbook["nodes"],
|
return self.test_commands(**exec_args)
|
||||||
commands=playbook["commands"],
|
|
||||||
expected=playbook.get("expected", []),
|
|
||||||
parallel=parallel,
|
|
||||||
timeout=playbook.get("timeout", 10)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
raise ConnpyError(f"Unsupported playbook action: {action}")
|
raise ConnpyError(f"Unsupported playbook action: {action}")
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from .base import BaseService
|
from .base import BaseService
|
||||||
import yaml
|
import yaml
|
||||||
import os
|
import os
|
||||||
|
from copy import deepcopy
|
||||||
from .exceptions import InvalidConfigurationError, NodeNotFoundError, ReservedNameError
|
from .exceptions import InvalidConfigurationError, NodeNotFoundError, ReservedNameError
|
||||||
from ..configfile import NoAliasDumper
|
from ..configfile import NoAliasDumper
|
||||||
|
|
||||||
@@ -23,13 +24,45 @@ class ImportExportService(BaseService):
|
|||||||
def export_to_dict(self, folders=None):
|
def export_to_dict(self, folders=None):
|
||||||
"""Export nodes/folders to a dictionary."""
|
"""Export nodes/folders to a dictionary."""
|
||||||
if not folders:
|
if not folders:
|
||||||
return self.config._getallnodesfull(extract=False)
|
return deepcopy(self.config.connections)
|
||||||
else:
|
else:
|
||||||
# Validate folders exist
|
# Validate folders exist
|
||||||
for f in folders:
|
for f in folders:
|
||||||
if f != "@" and f not in self.config._getallfolders():
|
if f != "@" and f not in self.config._getallfolders():
|
||||||
raise NodeNotFoundError(f"Folder '{f}' not found.")
|
raise NodeNotFoundError(f"Folder '{f}' not found.")
|
||||||
return self.config._getallnodesfull(folders, extract=False)
|
|
||||||
|
flat = self.config._getallnodesfull(folders, extract=False)
|
||||||
|
nested = {}
|
||||||
|
for k, v in flat.items():
|
||||||
|
uniques = self.config._explode_unique(k)
|
||||||
|
if not uniques:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if "folder" in uniques and "subfolder" in uniques:
|
||||||
|
f_name = uniques["folder"]
|
||||||
|
s_name = uniques["subfolder"]
|
||||||
|
i_name = uniques["id"]
|
||||||
|
|
||||||
|
if f_name not in nested:
|
||||||
|
nested[f_name] = {"type": "folder"}
|
||||||
|
if s_name not in nested[f_name]:
|
||||||
|
nested[f_name][s_name] = {"type": "subfolder"}
|
||||||
|
|
||||||
|
nested[f_name][s_name][i_name] = v
|
||||||
|
|
||||||
|
elif "folder" in uniques:
|
||||||
|
f_name = uniques["folder"]
|
||||||
|
i_name = uniques["id"]
|
||||||
|
|
||||||
|
if f_name not in nested:
|
||||||
|
nested[f_name] = {"type": "folder"}
|
||||||
|
|
||||||
|
nested[f_name][i_name] = v
|
||||||
|
else:
|
||||||
|
i_name = uniques["id"]
|
||||||
|
nested[i_name] = v
|
||||||
|
|
||||||
|
return nested
|
||||||
|
|
||||||
def import_from_file(self, file_path):
|
def import_from_file(self, file_path):
|
||||||
"""Import nodes/folders from a YAML file."""
|
"""Import nodes/folders from a YAML file."""
|
||||||
@@ -48,26 +81,35 @@ class ImportExportService(BaseService):
|
|||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
raise InvalidConfigurationError("Invalid import data format: expected a dictionary of nodes.")
|
raise InvalidConfigurationError("Invalid import data format: expected a dictionary of nodes.")
|
||||||
|
|
||||||
# Process imports
|
def _traverse_import(node_data, current_folder='', current_subfolder=''):
|
||||||
for k, v in data.items():
|
for k, v in node_data.items():
|
||||||
uniques = self.config._explode_unique(k)
|
if k == "type":
|
||||||
|
continue
|
||||||
|
if isinstance(v, dict):
|
||||||
|
node_type = v.get("type", "connection")
|
||||||
|
if node_type == "folder":
|
||||||
|
self.config._folder_add(folder=k)
|
||||||
|
_traverse_import(v, current_folder=k, current_subfolder='')
|
||||||
|
elif node_type == "subfolder":
|
||||||
|
self.config._folder_add(folder=current_folder, subfolder=k)
|
||||||
|
_traverse_import(v, current_folder=current_folder, current_subfolder=k)
|
||||||
|
elif node_type == "connection":
|
||||||
|
unique_id = k
|
||||||
|
if current_subfolder:
|
||||||
|
unique_id = f"{k}@{current_subfolder}@{current_folder}"
|
||||||
|
elif current_folder:
|
||||||
|
unique_id = f"{k}@{current_folder}"
|
||||||
|
self._validate_node_name(unique_id)
|
||||||
|
|
||||||
# Ensure folders exist
|
kwargs = deepcopy(v)
|
||||||
if "folder" in uniques:
|
kwargs['id'] = k
|
||||||
folder_name = f"@{uniques['folder']}"
|
kwargs['folder'] = current_folder
|
||||||
if folder_name not in self.config._getallfolders():
|
kwargs['subfolder'] = current_subfolder
|
||||||
folder_uniques = self.config._explode_unique(folder_name)
|
|
||||||
self.config._folder_add(**folder_uniques)
|
|
||||||
|
|
||||||
if "subfolder" in uniques:
|
self.config._connections_add(**kwargs)
|
||||||
sub_name = f"@{uniques['subfolder']}@{uniques['folder']}"
|
else:
|
||||||
if sub_name not in self.config._getallfolders():
|
# Invalid format skip
|
||||||
sub_uniques = self.config._explode_unique(sub_name)
|
pass
|
||||||
self.config._folder_add(**sub_uniques)
|
|
||||||
|
|
||||||
# Add node/connection
|
|
||||||
v.update(uniques)
|
|
||||||
self._validate_node_name(k)
|
|
||||||
self.config._connections_add(**v)
|
|
||||||
|
|
||||||
|
_traverse_import(data)
|
||||||
self.config._saveconfig(self.config.file)
|
self.config._saveconfig(self.config.file)
|
||||||
|
|||||||
@@ -67,6 +67,12 @@ class NodeService(BaseService):
|
|||||||
case_sensitive = self.config.config.get("case", False)
|
case_sensitive = self.config.config.get("case", False)
|
||||||
|
|
||||||
if filter_str:
|
if filter_str:
|
||||||
|
if filter_str.startswith("@"):
|
||||||
|
if not case_sensitive:
|
||||||
|
folders = [f for f in folders if f.lower() == filter_str.lower()]
|
||||||
|
else:
|
||||||
|
folders = [f for f in folders if f == filter_str]
|
||||||
|
else:
|
||||||
flags = re.IGNORECASE if not case_sensitive else 0
|
flags = re.IGNORECASE if not case_sensitive else 0
|
||||||
folders = [f for f in folders if re.search(filter_str, f, flags)]
|
folders = [f for f in folders if re.search(filter_str, f, flags)]
|
||||||
return folders
|
return folders
|
||||||
@@ -89,8 +95,15 @@ class NodeService(BaseService):
|
|||||||
"""Generate and update the internal nodes cache."""
|
"""Generate and update the internal nodes cache."""
|
||||||
self.config._generate_nodes_cache(nodes=nodes, folders=folders, profiles=profiles)
|
self.config._generate_nodes_cache(nodes=nodes, folders=folders, profiles=profiles)
|
||||||
|
|
||||||
def validate_parent_folder(self, unique_id):
|
def validate_parent_folder(self, unique_id, is_folder=False):
|
||||||
"""Check if parent folder exists for a given node unique ID."""
|
"""Check if parent folder exists for a given node unique ID."""
|
||||||
|
if is_folder:
|
||||||
|
uniques = self.config._explode_unique(unique_id)
|
||||||
|
if uniques and "subfolder" in uniques and "folder" in uniques:
|
||||||
|
parent_folder = f"@{uniques['folder']}"
|
||||||
|
if parent_folder not in self.config._getallfolders():
|
||||||
|
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||||
|
else:
|
||||||
node_folder = unique_id.partition("@")[2]
|
node_folder = unique_id.partition("@")[2]
|
||||||
if node_folder:
|
if node_folder:
|
||||||
parent_folder = f"@{node_folder}"
|
parent_folder = f"@{node_folder}"
|
||||||
@@ -115,7 +128,7 @@ class NodeService(BaseService):
|
|||||||
|
|
||||||
# Check if parent folder exists when creating a subfolder
|
# Check if parent folder exists when creating a subfolder
|
||||||
if "subfolder" in uniques:
|
if "subfolder" in uniques:
|
||||||
self.validate_parent_folder(unique_id)
|
self.validate_parent_folder(unique_id, is_folder=True)
|
||||||
|
|
||||||
self.config._folder_add(**uniques)
|
self.config._folder_add(**uniques)
|
||||||
self.config._saveconfig(self.config.file)
|
self.config._saveconfig(self.config.file)
|
||||||
|
|||||||
@@ -233,14 +233,26 @@ class PluginService(BaseService):
|
|||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
|
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
buf = io.StringIO()
|
import queue
|
||||||
|
import threading
|
||||||
|
|
||||||
|
q = queue.Queue()
|
||||||
|
|
||||||
|
class QueueIO(io.StringIO):
|
||||||
|
def write(self, s):
|
||||||
|
q.put(s)
|
||||||
|
return len(s)
|
||||||
|
def flush(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
buf = QueueIO()
|
||||||
old_console = printer._get_console()
|
old_console = printer._get_console()
|
||||||
old_err_console = printer._get_err_console()
|
old_err_console = printer._get_err_console()
|
||||||
|
|
||||||
|
def run_plugin():
|
||||||
printer.set_thread_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
printer.set_thread_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
||||||
printer.set_thread_err_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
printer.set_thread_err_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
||||||
printer.set_thread_stream(buf)
|
printer.set_thread_stream(buf)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if hasattr(module, "Entrypoint"):
|
if hasattr(module, "Entrypoint"):
|
||||||
module.Entrypoint(args, parser, app)
|
module.Entrypoint(args, parser, app)
|
||||||
@@ -252,6 +264,13 @@ class PluginService(BaseService):
|
|||||||
printer.set_thread_console(old_console)
|
printer.set_thread_console(old_console)
|
||||||
printer.set_thread_err_console(old_err_console)
|
printer.set_thread_err_console(old_err_console)
|
||||||
printer.set_thread_stream(None)
|
printer.set_thread_stream(None)
|
||||||
|
q.put(None)
|
||||||
|
|
||||||
for line in buf.getvalue().splitlines(keepends=True):
|
t = threading.Thread(target=run_plugin, daemon=True)
|
||||||
yield line
|
t.start()
|
||||||
|
|
||||||
|
while True:
|
||||||
|
item = q.get()
|
||||||
|
if item is None:
|
||||||
|
break
|
||||||
|
yield item
|
||||||
|
|||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import pytest
|
||||||
|
from unittest.mock import MagicMock, patch, AsyncMock
|
||||||
|
import json
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from connpy.ai import ai
|
||||||
|
from connpy.core import node
|
||||||
|
|
||||||
|
class DummyConfig:
|
||||||
|
def __init__(self):
|
||||||
|
self.config = {"ai": {"engineer_api_key": "test_key", "engineer_model": "test_model"}}
|
||||||
|
self.defaultdir = "/tmp"
|
||||||
|
|
||||||
|
class MockAsyncIterator:
|
||||||
|
def __init__(self, items):
|
||||||
|
self.items = items
|
||||||
|
def __aiter__(self):
|
||||||
|
return self
|
||||||
|
async def __anext__(self):
|
||||||
|
if not self.items:
|
||||||
|
raise StopAsyncIteration
|
||||||
|
return self.items.pop(0)
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mock_acompletion():
|
||||||
|
# Patch acompletion inside connpy.ai.aask_copilot
|
||||||
|
with patch('litellm.acompletion') as mock:
|
||||||
|
yield mock
|
||||||
|
|
||||||
|
def test_aask_copilot_tool_call(mock_acompletion):
|
||||||
|
agent = ai(DummyConfig())
|
||||||
|
|
||||||
|
# Setup mock response for streaming
|
||||||
|
class MockDelta:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.content = content
|
||||||
|
|
||||||
|
class MockChoice:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.delta = MockDelta(content)
|
||||||
|
|
||||||
|
class MockChunk:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.choices = [MockChoice(content)]
|
||||||
|
|
||||||
|
# acompletion is awaited and returns an async iterator
|
||||||
|
async def mock_ac(*args, **kwargs):
|
||||||
|
return MockAsyncIterator([
|
||||||
|
MockChunk("<guide>Check the interfaces and running config.</guide>"),
|
||||||
|
MockChunk("<commands>\nshow ip int br\nshow run\n</commands>"),
|
||||||
|
MockChunk("<risk>low</risk>")
|
||||||
|
])
|
||||||
|
|
||||||
|
mock_acompletion.side_effect = mock_ac
|
||||||
|
|
||||||
|
async def run_test():
|
||||||
|
return await agent.aask_copilot("Router#", "What do I do?")
|
||||||
|
|
||||||
|
result = asyncio.run(run_test())
|
||||||
|
|
||||||
|
if result["error"]:
|
||||||
|
print(f"ERROR OCCURRED: {result['error']}")
|
||||||
|
|
||||||
|
assert result["error"] is None
|
||||||
|
assert result["guide"] == "Check the interfaces and running config."
|
||||||
|
assert result["risk_level"] == "low"
|
||||||
|
assert result["commands"] == ["show ip int br", "show run"]
|
||||||
|
|
||||||
|
def test_aask_copilot_fallback(mock_acompletion):
|
||||||
|
agent = ai(DummyConfig())
|
||||||
|
|
||||||
|
# Setup mock response for streaming
|
||||||
|
class MockDelta:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.content = content
|
||||||
|
|
||||||
|
class MockChoice:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.delta = MockDelta(content)
|
||||||
|
|
||||||
|
class MockChunk:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.choices = [MockChoice(content)]
|
||||||
|
|
||||||
|
async def mock_ac(*args, **kwargs):
|
||||||
|
return MockAsyncIterator([
|
||||||
|
MockChunk("Here is some text response instead of tool call.")
|
||||||
|
])
|
||||||
|
|
||||||
|
mock_acompletion.side_effect = mock_ac
|
||||||
|
|
||||||
|
async def run_test():
|
||||||
|
return await agent.aask_copilot("Router#", "What do I do?")
|
||||||
|
|
||||||
|
result = asyncio.run(run_test())
|
||||||
|
|
||||||
|
if result["error"]:
|
||||||
|
print(f"ERROR OCCURRED: {result['error']}")
|
||||||
|
|
||||||
|
assert result["error"] is None
|
||||||
|
assert result["guide"] == "Here is some text response instead of tool call."
|
||||||
|
assert result["risk_level"] == "low"
|
||||||
|
|
||||||
|
def test_logclean_ansi():
|
||||||
|
c = node("test_node", "1.2.3.4")
|
||||||
|
raw = "Router#\x1b[K\x1b[m show ip"
|
||||||
|
clean = c._logclean(raw, var=True)
|
||||||
|
assert "\x1b" not in clean
|
||||||
|
|
||||||
|
def test_ingress_task_interception():
|
||||||
|
async def run_test():
|
||||||
|
c = node("test_node", "1.2.3.4")
|
||||||
|
c.mylog = MagicMock()
|
||||||
|
c.mylog.getvalue.return_value = b"Some session log"
|
||||||
|
c.unique = "test_node"
|
||||||
|
c.host = "1.2.3.4"
|
||||||
|
c.tags = {"os": "cisco_ios"}
|
||||||
|
|
||||||
|
class MockStream:
|
||||||
|
def __init__(self):
|
||||||
|
self.data = [b"a", b"b", b"\x00", b"c", b""]
|
||||||
|
async def read(self):
|
||||||
|
if self.data:
|
||||||
|
return self.data.pop(0)
|
||||||
|
return b""
|
||||||
|
def setup(self, resize_callback):
|
||||||
|
pass
|
||||||
|
|
||||||
|
stream = MockStream()
|
||||||
|
|
||||||
|
called_copilot = False
|
||||||
|
async def mock_handler(buffer, node_info, s, child_fd):
|
||||||
|
nonlocal called_copilot
|
||||||
|
called_copilot = True
|
||||||
|
assert buffer == "Some session log"
|
||||||
|
assert node_info["os"] == "cisco_ios"
|
||||||
|
|
||||||
|
c.child = MagicMock()
|
||||||
|
c.child.child_fd = 123
|
||||||
|
c.child.after = b""
|
||||||
|
c.child.buffer = b""
|
||||||
|
|
||||||
|
async def mock_ingress():
|
||||||
|
while True:
|
||||||
|
data = await stream.read()
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
|
||||||
|
if mock_handler and b'\x00' in data:
|
||||||
|
buffer = c.mylog.getvalue().decode()
|
||||||
|
node_info = {"name": getattr(c, 'unique', 'unknown'), "host": getattr(c, 'host', 'unknown')}
|
||||||
|
if isinstance(getattr(c, 'tags', None), dict):
|
||||||
|
node_info["os"] = c.tags.get("os", "unknown")
|
||||||
|
await mock_handler(buffer, node_info, stream, c.child.child_fd)
|
||||||
|
continue
|
||||||
|
|
||||||
|
await mock_ingress()
|
||||||
|
assert called_copilot
|
||||||
|
|
||||||
|
asyncio.run(run_test())
|
||||||
@@ -85,8 +85,8 @@ class TestStubsMessageFormatting:
|
|||||||
|
|
||||||
mock_resp = MagicMock()
|
mock_resp = MagicMock()
|
||||||
mock_resp.success = True
|
mock_resp.success = True
|
||||||
|
mock_resp.stdout_data = b''
|
||||||
stub.stub.interact_node.return_value = iter([mock_resp])
|
stub.stub.interact_node.return_value = iter([mock_resp])
|
||||||
|
|
||||||
with patch("connpy.printer.success") as mock_success:
|
with patch("connpy.printer.success") as mock_success:
|
||||||
with patch("sys.stdin.fileno", return_value=0):
|
with patch("sys.stdin.fileno", return_value=0):
|
||||||
mock_select.return_value = ([], [], [])
|
mock_select.return_value = ([], [], [])
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import termios
|
||||||
|
import tty
|
||||||
|
import signal
|
||||||
|
import struct
|
||||||
|
import fcntl
|
||||||
|
|
||||||
|
class LocalStream:
|
||||||
|
"""
|
||||||
|
Asynchronous stream wrapper for local stdin/stdout.
|
||||||
|
Handles terminal raw mode, async I/O, and SIGWINCH signals.
|
||||||
|
"""
|
||||||
|
def __init__(self):
|
||||||
|
self.stdin_fd = sys.stdin.fileno()
|
||||||
|
self.stdout_fd = sys.stdout.fileno()
|
||||||
|
self.original_tty_settings = None
|
||||||
|
self.resize_callback = None
|
||||||
|
self._reader_queue = asyncio.Queue()
|
||||||
|
self._loop = None
|
||||||
|
|
||||||
|
def setup(self, resize_callback=None):
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
self.resize_callback = resize_callback
|
||||||
|
|
||||||
|
# Save original terminal settings
|
||||||
|
try:
|
||||||
|
self.original_tty_settings = termios.tcgetattr(self.stdin_fd)
|
||||||
|
tty.setraw(self.stdin_fd)
|
||||||
|
except termios.error:
|
||||||
|
# Not a TTY, maybe piped or redirected
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Set stdin non-blocking
|
||||||
|
flags = fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL)
|
||||||
|
fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
|
||||||
|
|
||||||
|
# Setup read callback
|
||||||
|
self._loop.add_reader(self.stdin_fd, self._read_ready)
|
||||||
|
|
||||||
|
# Register SIGWINCH
|
||||||
|
if resize_callback:
|
||||||
|
try:
|
||||||
|
self._loop.add_signal_handler(signal.SIGWINCH, self._handle_winch)
|
||||||
|
except (NotImplementedError, RuntimeError):
|
||||||
|
# signal handling not supported on some loops (e.g., Windows Proactor)
|
||||||
|
pass
|
||||||
|
|
||||||
|
def stop_reading(self):
|
||||||
|
"""Temporarily stop reading from stdin."""
|
||||||
|
if self._loop and self.stdin_fd is not None:
|
||||||
|
try:
|
||||||
|
self._loop.remove_reader(self.stdin_fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def start_reading(self):
|
||||||
|
"""Resume reading from stdin."""
|
||||||
|
if self._loop and self.stdin_fd is not None:
|
||||||
|
try:
|
||||||
|
# Ensure we don't add it twice
|
||||||
|
self._loop.remove_reader(self.stdin_fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._loop.add_reader(self.stdin_fd, self._read_ready)
|
||||||
|
|
||||||
|
def teardown(self):
|
||||||
|
if self._loop:
|
||||||
|
try:
|
||||||
|
self._loop.remove_reader(self.stdin_fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if self.resize_callback:
|
||||||
|
try:
|
||||||
|
self._loop.remove_signal_handler(signal.SIGWINCH)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Restore terminal settings
|
||||||
|
if self.original_tty_settings is not None:
|
||||||
|
try:
|
||||||
|
termios.tcsetattr(self.stdin_fd, termios.TCSADRAIN, self.original_tty_settings)
|
||||||
|
except termios.error:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Restore blocking mode for stdin
|
||||||
|
try:
|
||||||
|
flags = fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL)
|
||||||
|
fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _read_ready(self):
|
||||||
|
try:
|
||||||
|
# Read whatever is available
|
||||||
|
data = os.read(self.stdin_fd, 4096)
|
||||||
|
if data:
|
||||||
|
self._reader_queue.put_nowait(data)
|
||||||
|
else:
|
||||||
|
self._reader_queue.put_nowait(b'') # EOF
|
||||||
|
except BlockingIOError:
|
||||||
|
pass
|
||||||
|
except OSError:
|
||||||
|
self._reader_queue.put_nowait(b'') # EOF on error
|
||||||
|
|
||||||
|
async def read(self) -> bytes:
|
||||||
|
"""Asynchronously read bytes from stdin."""
|
||||||
|
return await self._reader_queue.get()
|
||||||
|
|
||||||
|
async def write(self, data: bytes):
|
||||||
|
"""Asynchronously write bytes to stdout."""
|
||||||
|
if not data:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.write(self.stdout_fd, data)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _handle_winch(self):
|
||||||
|
if self.resize_callback:
|
||||||
|
try:
|
||||||
|
# Use ioctl to get the current window size
|
||||||
|
s = struct.pack("HHHH", 0, 0, 0, 0)
|
||||||
|
a = fcntl.ioctl(self.stdout_fd, termios.TIOCGWINSZ, s)
|
||||||
|
rows, cols, _, _ = struct.unpack("HHHH", a)
|
||||||
|
|
||||||
|
# We schedule the callback safely inside the asyncio loop
|
||||||
|
# instead of running it raw in the signal handler
|
||||||
|
self._loop.call_soon(self.resize_callback, rows, cols)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
import threading
|
||||||
|
|
||||||
|
class RemoteStream:
|
||||||
|
"""
|
||||||
|
Asynchronous stream wrapper for gRPC remote connections.
|
||||||
|
Bridges the blocking gRPC iterators with the async _async_interact_loop.
|
||||||
|
"""
|
||||||
|
def __init__(self, request_iterator, response_queue):
|
||||||
|
self.request_iterator = request_iterator
|
||||||
|
self.response_queue = response_queue
|
||||||
|
self.running = True
|
||||||
|
self._reader_queue = asyncio.Queue()
|
||||||
|
self.copilot_queue = asyncio.Queue()
|
||||||
|
self.resize_callback = None
|
||||||
|
self._loop = None
|
||||||
|
self.t = None
|
||||||
|
|
||||||
|
def setup(self, resize_callback=None):
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
self.resize_callback = resize_callback
|
||||||
|
|
||||||
|
def read_requests():
|
||||||
|
try:
|
||||||
|
for req in self.request_iterator:
|
||||||
|
if not self.running:
|
||||||
|
break
|
||||||
|
if req.cols > 0 and req.rows > 0:
|
||||||
|
if self.resize_callback:
|
||||||
|
self._loop.call_soon_threadsafe(self.resize_callback, req.rows, req.cols)
|
||||||
|
# Copilot dispatching
|
||||||
|
copilot_msg = {}
|
||||||
|
if getattr(req, "copilot_question", ""):
|
||||||
|
copilot_msg.update({
|
||||||
|
"question": req.copilot_question,
|
||||||
|
"context_buffer": getattr(req, "copilot_context_buffer", ""),
|
||||||
|
"node_info_json": getattr(req, "copilot_node_info_json", "")
|
||||||
|
})
|
||||||
|
if getattr(req, "copilot_action", ""):
|
||||||
|
copilot_msg["action"] = req.copilot_action
|
||||||
|
|
||||||
|
if copilot_msg:
|
||||||
|
self._loop.call_soon_threadsafe(self.copilot_queue.put_nowait, copilot_msg)
|
||||||
|
if req.stdin_data:
|
||||||
|
self._loop.call_soon_threadsafe(self._reader_queue.put_nowait, req.stdin_data)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
if self._loop and not self._loop.is_closed():
|
||||||
|
try:
|
||||||
|
self._loop.call_soon_threadsafe(self._reader_queue.put_nowait, b'')
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
self.t = threading.Thread(target=read_requests, daemon=True)
|
||||||
|
self.t.start()
|
||||||
|
|
||||||
|
def teardown(self):
|
||||||
|
self.running = False
|
||||||
|
self.response_queue.put(None) # Signal EOF
|
||||||
|
|
||||||
|
async def read(self) -> bytes:
|
||||||
|
"""Asynchronously read bytes from the gRPC iterator queue."""
|
||||||
|
return await self._reader_queue.get()
|
||||||
|
|
||||||
|
async def write(self, data: bytes):
|
||||||
|
"""Asynchronously write bytes to the gRPC response queue."""
|
||||||
|
if data:
|
||||||
|
self.response_queue.put(data)
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import re
|
||||||
|
|
||||||
|
def log_cleaner(data: str) -> str:
|
||||||
|
"""
|
||||||
|
Stateless utility to remove ANSI sequences and process cursor movements.
|
||||||
|
"""
|
||||||
|
if not data:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
lines = data.split('\n')
|
||||||
|
cleaned_lines = []
|
||||||
|
|
||||||
|
# Regex to capture: ANSI sequences, control characters (\r, \b, etc), and plain text chunks
|
||||||
|
token_re = re.compile(r'(\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/ ]*[@-~])|\r|\b|\x7f|[\x00-\x1F]|[^\x1B\r\b\x7f\x00-\x1F]+)')
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
buffer = []
|
||||||
|
cursor = 0
|
||||||
|
|
||||||
|
for token in token_re.findall(line):
|
||||||
|
if token == '\r':
|
||||||
|
cursor = 0
|
||||||
|
elif token in ('\b', '\x7f'):
|
||||||
|
if cursor > 0:
|
||||||
|
cursor -= 1
|
||||||
|
elif token.startswith('\x1B[') and len(token) >= 3:
|
||||||
|
# Parse CSI: \x1B[ <params> <final_char>
|
||||||
|
final = token[-1]
|
||||||
|
param_str = token[2:-1]
|
||||||
|
n = int(param_str) if param_str.isdigit() else 1
|
||||||
|
|
||||||
|
if final == 'D': # CUB – Cursor Back
|
||||||
|
cursor = max(0, cursor - n)
|
||||||
|
elif final == 'C': # CUF – Cursor Forward
|
||||||
|
cursor = min(len(buffer), cursor + n)
|
||||||
|
elif final == 'K': # EL – Erase in Line
|
||||||
|
if n == 0 or param_str == '': # Clear to end
|
||||||
|
buffer = buffer[:cursor]
|
||||||
|
elif n == 1: # Clear to start
|
||||||
|
buffer[:cursor] = [' '] * cursor
|
||||||
|
elif n == 2: # Clear entire line
|
||||||
|
buffer = []
|
||||||
|
cursor = 0
|
||||||
|
elif final == 'G': # CHA – Cursor Horizontal Absolute (1-indexed)
|
||||||
|
cursor = max(0, n - 1)
|
||||||
|
# Pad buffer if cursor is beyond current length
|
||||||
|
if cursor > len(buffer):
|
||||||
|
buffer.extend([' '] * (cursor - len(buffer)))
|
||||||
|
elif final == 'P': # DCH – Delete Characters
|
||||||
|
del buffer[cursor:cursor + n]
|
||||||
|
elif final == '@': # ICH – Insert Characters
|
||||||
|
buffer[cursor:cursor] = [' '] * n
|
||||||
|
# All other CSI sequences are silently discarded
|
||||||
|
elif token.startswith('\x1B'):
|
||||||
|
continue
|
||||||
|
elif len(token) == 1 and ord(token) < 32:
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
for char in token:
|
||||||
|
if cursor == len(buffer):
|
||||||
|
buffer.append(char)
|
||||||
|
else:
|
||||||
|
buffer[cursor] = char
|
||||||
|
cursor += 1
|
||||||
|
cleaned_lines.append("".join(buffer))
|
||||||
|
|
||||||
|
return "\n".join(cleaned_lines).replace('\n\n', '\n').strip()
|
||||||
+13
-5
@@ -1,9 +1,17 @@
|
|||||||
version: "3.8"
|
|
||||||
services:
|
services:
|
||||||
connpy-app:
|
connpy-app:
|
||||||
build: .
|
build: .
|
||||||
image: connpy-app
|
image: connpy:latest
|
||||||
|
container_name: connpy
|
||||||
|
# Fundamental para la interactividad de la terminal
|
||||||
|
stdin_open: true
|
||||||
|
tty: true
|
||||||
|
environment:
|
||||||
|
- TERM=xterm-256color
|
||||||
|
extra_hosts:
|
||||||
|
- "host.docker.internal:host-gateway"
|
||||||
volumes:
|
volumes:
|
||||||
- ./docker/connpy/:/app
|
- ./docker/config:/config
|
||||||
- ./docker/logs/:/logs
|
- ./docker/ssh:/root/.ssh
|
||||||
- ./docker/ssh/:/root/.ssh/
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
# No definimos comando por defecto para que 'run' sea más natural
|
||||||
|
|||||||
+58
-14
@@ -1,21 +1,65 @@
|
|||||||
# Use the official python image
|
# connpy v6.0.0b8 - Modern Network Automation Environment (Local Build)
|
||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
FROM python:3.11-alpine as connpy-app
|
LABEL description="Connpy: AI-Driven Network Automation & Intelligence Platform"
|
||||||
|
|
||||||
|
# Configuración de Terminal y Python
|
||||||
|
ENV DEBIAN_FRONTEND=noninteractive \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
TERM=xterm-256color
|
||||||
|
|
||||||
# Set the entrypoint
|
|
||||||
# Set the working directory
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Install any additional dependencies
|
# 1. Herramientas base del sistema
|
||||||
RUN apk update && apk add --no-cache openssh fzf fzf-tmux ncurses bash
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
RUN pip3 install connpy
|
curl \
|
||||||
RUN connpy config --configfolder /app
|
git \
|
||||||
|
openssh-client \
|
||||||
|
fzf \
|
||||||
|
ncurses-bin \
|
||||||
|
bash \
|
||||||
|
procps \
|
||||||
|
unzip \
|
||||||
|
ca-certificates \
|
||||||
|
gnupg \
|
||||||
|
iputils-ping \
|
||||||
|
telnet \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
#AUTH
|
# 2. Instalar Docker CLI (para el plugin de docker de connpy)
|
||||||
RUN ssh-keygen -A
|
RUN install -m 0755 -d /etc/apt/keyrings && \
|
||||||
RUN mkdir /root/.ssh && \
|
curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg && \
|
||||||
chmod 700 /root/.ssh
|
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
|
||||||
|
tee /etc/apt/sources.list.d/docker.list > /dev/null && \
|
||||||
|
apt-get update && apt-get install -y docker-ce-cli && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# 3. Instalar Kubectl (para el plugin de k8s de connpy)
|
||||||
|
RUN curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/$(dpkg --print-architecture)/kubectl" && \
|
||||||
|
install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl && \
|
||||||
|
rm kubectl
|
||||||
|
|
||||||
#Set the entrypoint
|
# 4. Instalar AWS CLI y Session Manager Plugin (Universal x86_64/ARM64)
|
||||||
ENTRYPOINT ["connpy"]
|
RUN ARCH=$(uname -m) && \
|
||||||
|
if [ "$ARCH" = "x86_64" ]; then AWS_ARCH="x86_64"; else AWS_ARCH="aarch64"; fi && \
|
||||||
|
curl "https://awscli.amazonaws.com/awscli-exe-linux-$AWS_ARCH.zip" -o "awscliv2.zip" && \
|
||||||
|
unzip awscliv2.zip && ./aws/install && rm -rf awscliv2.zip aws/ && \
|
||||||
|
if [ "$ARCH" = "x86_64" ]; then \
|
||||||
|
curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_64bit/session-manager-plugin.deb" -o "ssm.deb"; \
|
||||||
|
else \
|
||||||
|
curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_arm64/session-manager-plugin.deb" -o "ssm.deb"; \
|
||||||
|
fi && \
|
||||||
|
dpkg -i ssm.deb && rm ssm.deb
|
||||||
|
|
||||||
|
# 5. Copiar código local e instalar dependencias
|
||||||
|
COPY . .
|
||||||
|
RUN pip install --no-cache-dir --upgrade pip && \
|
||||||
|
pip install --no-cache-dir .
|
||||||
|
|
||||||
|
# 6. Configuración de persistencia
|
||||||
|
# Creamos la carpeta y el puntero .folder para que connpy use /config
|
||||||
|
RUN mkdir -p /config /root/.ssh /root/.config/conn && chmod 700 /root/.ssh && \
|
||||||
|
echo -n "/config" > /root/.config/conn/.folder
|
||||||
|
|
||||||
|
# Punto de entrada directo a connpy
|
||||||
|
ENTRYPOINT ["conn"]
|
||||||
|
|||||||
+247
-10
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.ai_handler API documentation</title>
|
<title>connpy.cli.ai_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -78,6 +78,9 @@ el.replaceWith(d);
|
|||||||
printer.error(str(e))
|
printer.error(str(e))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if args.mcp is not None:
|
||||||
|
return self.configure_mcp(args)
|
||||||
|
|
||||||
# Determinar session_id para retomar
|
# Determinar session_id para retomar
|
||||||
session_id = None
|
session_id = None
|
||||||
if args.resume:
|
if args.resume:
|
||||||
@@ -134,7 +137,6 @@ el.replaceWith(d);
|
|||||||
if "usage" in result:
|
if "usage" in result:
|
||||||
u = result["usage"]
|
u = result["usage"]
|
||||||
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
||||||
console.print()
|
|
||||||
|
|
||||||
def interactive_chat(self, args, session_id):
|
def interactive_chat(self, args, session_id):
|
||||||
history = None
|
history = None
|
||||||
@@ -157,7 +159,7 @@ el.replaceWith(d);
|
|||||||
try:
|
try:
|
||||||
user_query = Prompt.ask("[user_prompt]User[/user_prompt]")
|
user_query = Prompt.ask("[user_prompt]User[/user_prompt]")
|
||||||
if not user_query.strip(): continue
|
if not user_query.strip(): continue
|
||||||
if user_query.lower() in ['exit', 'quit', 'bye']: break
|
if user_query.lower() in ['exit', 'quit', 'bye', 'cancel']: break
|
||||||
|
|
||||||
with console.status("[ai_status]Agent is thinking...") as status:
|
with console.status("[ai_status]Agent is thinking...") as status:
|
||||||
result = self.app.myai.ask(user_query, chat_history=history, status=status, debug=args.debug, trust=args.trust, **self.ai_overrides)
|
result = self.app.myai.ask(user_query, chat_history=history, status=status, debug=args.debug, trust=args.trust, **self.ai_overrides)
|
||||||
@@ -178,14 +180,247 @@ el.replaceWith(d);
|
|||||||
if "usage" in result:
|
if "usage" in result:
|
||||||
u = result["usage"]
|
u = result["usage"]
|
||||||
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
||||||
console.print()
|
|
||||||
except (KeyboardInterrupt, EOFError):
|
except (KeyboardInterrupt, EOFError):
|
||||||
console.print("\n[dim]Session closed.[/dim]")
|
console.print("\n[dim]Session closed.[/dim]")
|
||||||
break</code></pre>
|
break
|
||||||
|
|
||||||
|
def configure_mcp(self, args):
|
||||||
|
"""Handle MCP server configuration via CLI tokens or interactive wizard."""
|
||||||
|
mcp_args = args.mcp
|
||||||
|
|
||||||
|
# 1. Non-interactive CLI Mode (if arguments are provided)
|
||||||
|
if mcp_args:
|
||||||
|
action = mcp_args[0].lower()
|
||||||
|
|
||||||
|
if action == "list":
|
||||||
|
settings = self.app.services.config_svc.get_settings()
|
||||||
|
mcp_servers = settings.get("ai", {}).get("mcp_servers", {})
|
||||||
|
if not mcp_servers:
|
||||||
|
printer.info("No MCP servers configured.")
|
||||||
|
else:
|
||||||
|
columns = ["Name", "URL", "Enabled", "Auto-load OS"]
|
||||||
|
rows = []
|
||||||
|
for name, cfg in mcp_servers.items():
|
||||||
|
rows.append([
|
||||||
|
name,
|
||||||
|
cfg.get("url", ""),
|
||||||
|
"[green]Yes[/green]" if cfg.get("enabled", True) else "[red]No[/red]",
|
||||||
|
cfg.get("auto_load_on_os", "Any")
|
||||||
|
])
|
||||||
|
printer.table("Configured MCP Servers", columns, rows)
|
||||||
|
return
|
||||||
|
|
||||||
|
elif action == "add":
|
||||||
|
if len(mcp_args) < 3:
|
||||||
|
printer.error("Usage: connpy ai --mcp add <name> <url> [os_filter]")
|
||||||
|
return
|
||||||
|
name, url = mcp_args[1], mcp_args[2]
|
||||||
|
os_filter = mcp_args[3] if len(mcp_args) > 3 else None
|
||||||
|
try:
|
||||||
|
self.app.services.ai.configure_mcp(name, url=url, auto_load_on_os=os_filter)
|
||||||
|
printer.success(f"MCP server '{name}' added/updated.")
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
elif action == "remove":
|
||||||
|
if len(mcp_args) < 2:
|
||||||
|
printer.error("Usage: connpy ai --mcp remove <name>")
|
||||||
|
return
|
||||||
|
name = mcp_args[1]
|
||||||
|
try:
|
||||||
|
self.app.services.ai.configure_mcp(name, remove=True)
|
||||||
|
printer.success(f"MCP server '{name}' removed.")
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
elif action in ["enable", "disable"]:
|
||||||
|
if len(mcp_args) < 2:
|
||||||
|
printer.error(f"Usage: connpy ai --mcp {action} <name>")
|
||||||
|
return
|
||||||
|
name = mcp_args[1]
|
||||||
|
enabled = (action == "enable")
|
||||||
|
try:
|
||||||
|
self.app.services.ai.configure_mcp(name, enabled=enabled)
|
||||||
|
printer.success(f"MCP server '{name}' {'enabled' if enabled else 'disabled'}.")
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
else:
|
||||||
|
printer.error(f"Unknown MCP action: {action}")
|
||||||
|
printer.info("Available actions: list, add, remove, enable, disable")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2. Interactive Wizard Mode (if no arguments provided)
|
||||||
|
# Import forms dynamically to avoid circular dependencies if any
|
||||||
|
if not hasattr(self.app, "cli_forms"):
|
||||||
|
from .forms import Forms
|
||||||
|
self.app.cli_forms = Forms(self.app)
|
||||||
|
|
||||||
|
settings = self.app.services.config_svc.get_settings()
|
||||||
|
mcp_servers = settings.get("ai", {}).get("mcp_servers", {})
|
||||||
|
|
||||||
|
result = self.app.cli_forms.mcp_wizard(mcp_servers)
|
||||||
|
if not result:
|
||||||
|
return
|
||||||
|
|
||||||
|
action = result["action"]
|
||||||
|
try:
|
||||||
|
if action == "list":
|
||||||
|
# Recursive call to the non-interactive list logic
|
||||||
|
args.mcp = ["list"]
|
||||||
|
return self.configure_mcp(args)
|
||||||
|
|
||||||
|
elif action == "add":
|
||||||
|
self.app.services.ai.configure_mcp(
|
||||||
|
result["name"],
|
||||||
|
url=result["url"],
|
||||||
|
enabled=result["enabled"],
|
||||||
|
auto_load_on_os=result["os"]
|
||||||
|
)
|
||||||
|
printer.success(f"MCP server '{result['name']}' saved.")
|
||||||
|
|
||||||
|
elif action == "update": # Used for toggle
|
||||||
|
self.app.services.ai.configure_mcp(
|
||||||
|
result["name"],
|
||||||
|
enabled=result["enabled"]
|
||||||
|
)
|
||||||
|
printer.success(f"MCP server '{result['name']}' updated.")
|
||||||
|
|
||||||
|
elif action == "remove":
|
||||||
|
self.app.services.ai.configure_mcp(result["name"], remove=True)
|
||||||
|
printer.success(f"MCP server '{result['name']}' removed.")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"></div>
|
<div class="desc"></div>
|
||||||
<h3>Methods</h3>
|
<h3>Methods</h3>
|
||||||
<dl>
|
<dl>
|
||||||
|
<dt id="connpy.cli.ai_handler.AIHandler.configure_mcp"><code class="name flex">
|
||||||
|
<span>def <span class="ident">configure_mcp</span></span>(<span>self, args)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def configure_mcp(self, args):
|
||||||
|
"""Handle MCP server configuration via CLI tokens or interactive wizard."""
|
||||||
|
mcp_args = args.mcp
|
||||||
|
|
||||||
|
# 1. Non-interactive CLI Mode (if arguments are provided)
|
||||||
|
if mcp_args:
|
||||||
|
action = mcp_args[0].lower()
|
||||||
|
|
||||||
|
if action == "list":
|
||||||
|
settings = self.app.services.config_svc.get_settings()
|
||||||
|
mcp_servers = settings.get("ai", {}).get("mcp_servers", {})
|
||||||
|
if not mcp_servers:
|
||||||
|
printer.info("No MCP servers configured.")
|
||||||
|
else:
|
||||||
|
columns = ["Name", "URL", "Enabled", "Auto-load OS"]
|
||||||
|
rows = []
|
||||||
|
for name, cfg in mcp_servers.items():
|
||||||
|
rows.append([
|
||||||
|
name,
|
||||||
|
cfg.get("url", ""),
|
||||||
|
"[green]Yes[/green]" if cfg.get("enabled", True) else "[red]No[/red]",
|
||||||
|
cfg.get("auto_load_on_os", "Any")
|
||||||
|
])
|
||||||
|
printer.table("Configured MCP Servers", columns, rows)
|
||||||
|
return
|
||||||
|
|
||||||
|
elif action == "add":
|
||||||
|
if len(mcp_args) < 3:
|
||||||
|
printer.error("Usage: connpy ai --mcp add <name> <url> [os_filter]")
|
||||||
|
return
|
||||||
|
name, url = mcp_args[1], mcp_args[2]
|
||||||
|
os_filter = mcp_args[3] if len(mcp_args) > 3 else None
|
||||||
|
try:
|
||||||
|
self.app.services.ai.configure_mcp(name, url=url, auto_load_on_os=os_filter)
|
||||||
|
printer.success(f"MCP server '{name}' added/updated.")
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
elif action == "remove":
|
||||||
|
if len(mcp_args) < 2:
|
||||||
|
printer.error("Usage: connpy ai --mcp remove <name>")
|
||||||
|
return
|
||||||
|
name = mcp_args[1]
|
||||||
|
try:
|
||||||
|
self.app.services.ai.configure_mcp(name, remove=True)
|
||||||
|
printer.success(f"MCP server '{name}' removed.")
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
elif action in ["enable", "disable"]:
|
||||||
|
if len(mcp_args) < 2:
|
||||||
|
printer.error(f"Usage: connpy ai --mcp {action} <name>")
|
||||||
|
return
|
||||||
|
name = mcp_args[1]
|
||||||
|
enabled = (action == "enable")
|
||||||
|
try:
|
||||||
|
self.app.services.ai.configure_mcp(name, enabled=enabled)
|
||||||
|
printer.success(f"MCP server '{name}' {'enabled' if enabled else 'disabled'}.")
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
else:
|
||||||
|
printer.error(f"Unknown MCP action: {action}")
|
||||||
|
printer.info("Available actions: list, add, remove, enable, disable")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2. Interactive Wizard Mode (if no arguments provided)
|
||||||
|
# Import forms dynamically to avoid circular dependencies if any
|
||||||
|
if not hasattr(self.app, "cli_forms"):
|
||||||
|
from .forms import Forms
|
||||||
|
self.app.cli_forms = Forms(self.app)
|
||||||
|
|
||||||
|
settings = self.app.services.config_svc.get_settings()
|
||||||
|
mcp_servers = settings.get("ai", {}).get("mcp_servers", {})
|
||||||
|
|
||||||
|
result = self.app.cli_forms.mcp_wizard(mcp_servers)
|
||||||
|
if not result:
|
||||||
|
return
|
||||||
|
|
||||||
|
action = result["action"]
|
||||||
|
try:
|
||||||
|
if action == "list":
|
||||||
|
# Recursive call to the non-interactive list logic
|
||||||
|
args.mcp = ["list"]
|
||||||
|
return self.configure_mcp(args)
|
||||||
|
|
||||||
|
elif action == "add":
|
||||||
|
self.app.services.ai.configure_mcp(
|
||||||
|
result["name"],
|
||||||
|
url=result["url"],
|
||||||
|
enabled=result["enabled"],
|
||||||
|
auto_load_on_os=result["os"]
|
||||||
|
)
|
||||||
|
printer.success(f"MCP server '{result['name']}' saved.")
|
||||||
|
|
||||||
|
elif action == "update": # Used for toggle
|
||||||
|
self.app.services.ai.configure_mcp(
|
||||||
|
result["name"],
|
||||||
|
enabled=result["enabled"]
|
||||||
|
)
|
||||||
|
printer.success(f"MCP server '{result['name']}' updated.")
|
||||||
|
|
||||||
|
elif action == "remove":
|
||||||
|
self.app.services.ai.configure_mcp(result["name"], remove=True)
|
||||||
|
printer.success(f"MCP server '{result['name']}' removed.")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
printer.error(str(e))</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Handle MCP server configuration via CLI tokens or interactive wizard.</p></div>
|
||||||
|
</dd>
|
||||||
<dt id="connpy.cli.ai_handler.AIHandler.dispatch"><code class="name flex">
|
<dt id="connpy.cli.ai_handler.AIHandler.dispatch"><code class="name flex">
|
||||||
<span>def <span class="ident">dispatch</span></span>(<span>self, args)</span>
|
<span>def <span class="ident">dispatch</span></span>(<span>self, args)</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
@@ -213,6 +448,9 @@ el.replaceWith(d);
|
|||||||
printer.error(str(e))
|
printer.error(str(e))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if args.mcp is not None:
|
||||||
|
return self.configure_mcp(args)
|
||||||
|
|
||||||
# Determinar session_id para retomar
|
# Determinar session_id para retomar
|
||||||
session_id = None
|
session_id = None
|
||||||
if args.resume:
|
if args.resume:
|
||||||
@@ -285,7 +523,7 @@ el.replaceWith(d);
|
|||||||
try:
|
try:
|
||||||
user_query = Prompt.ask("[user_prompt]User[/user_prompt]")
|
user_query = Prompt.ask("[user_prompt]User[/user_prompt]")
|
||||||
if not user_query.strip(): continue
|
if not user_query.strip(): continue
|
||||||
if user_query.lower() in ['exit', 'quit', 'bye']: break
|
if user_query.lower() in ['exit', 'quit', 'bye', 'cancel']: break
|
||||||
|
|
||||||
with console.status("[ai_status]Agent is thinking...") as status:
|
with console.status("[ai_status]Agent is thinking...") as status:
|
||||||
result = self.app.myai.ask(user_query, chat_history=history, status=status, debug=args.debug, trust=args.trust, **self.ai_overrides)
|
result = self.app.myai.ask(user_query, chat_history=history, status=status, debug=args.debug, trust=args.trust, **self.ai_overrides)
|
||||||
@@ -306,7 +544,6 @@ el.replaceWith(d);
|
|||||||
if "usage" in result:
|
if "usage" in result:
|
||||||
u = result["usage"]
|
u = result["usage"]
|
||||||
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
||||||
console.print()
|
|
||||||
except (KeyboardInterrupt, EOFError):
|
except (KeyboardInterrupt, EOFError):
|
||||||
console.print("\n[dim]Session closed.[/dim]")
|
console.print("\n[dim]Session closed.[/dim]")
|
||||||
break</code></pre>
|
break</code></pre>
|
||||||
@@ -335,8 +572,7 @@ el.replaceWith(d);
|
|||||||
|
|
||||||
if "usage" in result:
|
if "usage" in result:
|
||||||
u = result["usage"]
|
u = result["usage"]
|
||||||
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")
|
console.print(f"[debug]Tokens: {u['total']} (Input: {u['input']}, Output: {u['output']})[/debug]")</code></pre>
|
||||||
console.print()</code></pre>
|
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -360,6 +596,7 @@ el.replaceWith(d);
|
|||||||
<li>
|
<li>
|
||||||
<h4><code><a title="connpy.cli.ai_handler.AIHandler" href="#connpy.cli.ai_handler.AIHandler">AIHandler</a></code></h4>
|
<h4><code><a title="connpy.cli.ai_handler.AIHandler" href="#connpy.cli.ai_handler.AIHandler">AIHandler</a></code></h4>
|
||||||
<ul class="">
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.cli.ai_handler.AIHandler.configure_mcp" href="#connpy.cli.ai_handler.AIHandler.configure_mcp">configure_mcp</a></code></li>
|
||||||
<li><code><a title="connpy.cli.ai_handler.AIHandler.dispatch" href="#connpy.cli.ai_handler.AIHandler.dispatch">dispatch</a></code></li>
|
<li><code><a title="connpy.cli.ai_handler.AIHandler.dispatch" href="#connpy.cli.ai_handler.AIHandler.dispatch">dispatch</a></code></li>
|
||||||
<li><code><a title="connpy.cli.ai_handler.AIHandler.interactive_chat" href="#connpy.cli.ai_handler.AIHandler.interactive_chat">interactive_chat</a></code></li>
|
<li><code><a title="connpy.cli.ai_handler.AIHandler.interactive_chat" href="#connpy.cli.ai_handler.AIHandler.interactive_chat">interactive_chat</a></code></li>
|
||||||
<li><code><a title="connpy.cli.ai_handler.AIHandler.single_question" href="#connpy.cli.ai_handler.AIHandler.single_question">single_question</a></code></li>
|
<li><code><a title="connpy.cli.ai_handler.AIHandler.single_question" href="#connpy.cli.ai_handler.AIHandler.single_question">single_question</a></code></li>
|
||||||
@@ -371,7 +608,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.api_handler API documentation</title>
|
<title>connpy.cli.api_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -193,7 +193,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.config_handler API documentation</title>
|
<title>connpy.cli.config_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -482,7 +482,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.context_handler API documentation</title>
|
<title>connpy.cli.context_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -249,7 +249,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+176
-3
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.forms API documentation</title>
|
<title>connpy.cli.forms API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -249,11 +249,183 @@ el.replaceWith(d);
|
|||||||
if "tags" in answer and not answer["tags"].startswith("@") and answer["tags"]:
|
if "tags" in answer and not answer["tags"].startswith("@") and answer["tags"]:
|
||||||
answer["tags"] = ast.literal_eval(answer["tags"])
|
answer["tags"] = ast.literal_eval(answer["tags"])
|
||||||
|
|
||||||
return answer</code></pre>
|
return answer
|
||||||
|
|
||||||
|
def mcp_wizard(self, mcp_servers):
|
||||||
|
"""Interactive wizard to manage MCP servers."""
|
||||||
|
from .helpers import theme
|
||||||
|
|
||||||
|
while True:
|
||||||
|
options = [
|
||||||
|
("List Configured Servers", "list"),
|
||||||
|
("Add/Update Server", "add"),
|
||||||
|
("Enable/Disable Server", "toggle"),
|
||||||
|
("Remove Server", "remove"),
|
||||||
|
("Back", "exit")
|
||||||
|
]
|
||||||
|
|
||||||
|
questions = [
|
||||||
|
inquirer.List("action", message="MCP Configuration", choices=options)
|
||||||
|
]
|
||||||
|
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if not answers or answers["action"] == "exit":
|
||||||
|
return None
|
||||||
|
|
||||||
|
action = answers["action"]
|
||||||
|
|
||||||
|
if action == "list":
|
||||||
|
if not mcp_servers:
|
||||||
|
print("\nNo MCP servers configured.\n")
|
||||||
|
else:
|
||||||
|
return {"action": "list"}
|
||||||
|
|
||||||
|
elif action == "add":
|
||||||
|
questions = [
|
||||||
|
inquirer.Text("name", message="Server Name (identifier)"),
|
||||||
|
inquirer.Text("url", message="SSE URL (e.g., http://localhost:8000/sse)"),
|
||||||
|
inquirer.Confirm("enabled", message="Enabled?", default=True),
|
||||||
|
inquirer.Text("auto_load_os", message="Auto-load on specific OS (blank for any)")
|
||||||
|
]
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if answers:
|
||||||
|
return {
|
||||||
|
"action": "add",
|
||||||
|
"name": answers["name"],
|
||||||
|
"url": answers["url"],
|
||||||
|
"enabled": answers["enabled"],
|
||||||
|
"os": answers["auto_load_os"]
|
||||||
|
}
|
||||||
|
|
||||||
|
elif action == "toggle":
|
||||||
|
if not mcp_servers:
|
||||||
|
print("\nNo servers to toggle.\n")
|
||||||
|
continue
|
||||||
|
|
||||||
|
choices = []
|
||||||
|
for name, cfg in mcp_servers.items():
|
||||||
|
status = "[Enabled]" if cfg.get("enabled", True) else "[Disabled]"
|
||||||
|
choices.append((f"{name} {status}", name))
|
||||||
|
|
||||||
|
questions = [
|
||||||
|
inquirer.List("name", message="Select server to toggle", choices=choices + [("Cancel", None)])
|
||||||
|
]
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if answers and answers["name"]:
|
||||||
|
current = mcp_servers[answers["name"]].get("enabled", True)
|
||||||
|
return {
|
||||||
|
"action": "update",
|
||||||
|
"name": answers["name"],
|
||||||
|
"enabled": not current
|
||||||
|
}
|
||||||
|
|
||||||
|
elif action == "remove":
|
||||||
|
if not mcp_servers:
|
||||||
|
print("\nNo servers to remove.\n")
|
||||||
|
continue
|
||||||
|
|
||||||
|
questions = [
|
||||||
|
inquirer.List("name", message="Select server to remove", choices=list(mcp_servers.keys()) + ["Cancel"])
|
||||||
|
]
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if answers and answers["name"] != "Cancel":
|
||||||
|
return {"action": "remove", "name": answers["name"]}
|
||||||
|
return None</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"></div>
|
<div class="desc"></div>
|
||||||
<h3>Methods</h3>
|
<h3>Methods</h3>
|
||||||
<dl>
|
<dl>
|
||||||
|
<dt id="connpy.cli.forms.Forms.mcp_wizard"><code class="name flex">
|
||||||
|
<span>def <span class="ident">mcp_wizard</span></span>(<span>self, mcp_servers)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def mcp_wizard(self, mcp_servers):
|
||||||
|
"""Interactive wizard to manage MCP servers."""
|
||||||
|
from .helpers import theme
|
||||||
|
|
||||||
|
while True:
|
||||||
|
options = [
|
||||||
|
("List Configured Servers", "list"),
|
||||||
|
("Add/Update Server", "add"),
|
||||||
|
("Enable/Disable Server", "toggle"),
|
||||||
|
("Remove Server", "remove"),
|
||||||
|
("Back", "exit")
|
||||||
|
]
|
||||||
|
|
||||||
|
questions = [
|
||||||
|
inquirer.List("action", message="MCP Configuration", choices=options)
|
||||||
|
]
|
||||||
|
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if not answers or answers["action"] == "exit":
|
||||||
|
return None
|
||||||
|
|
||||||
|
action = answers["action"]
|
||||||
|
|
||||||
|
if action == "list":
|
||||||
|
if not mcp_servers:
|
||||||
|
print("\nNo MCP servers configured.\n")
|
||||||
|
else:
|
||||||
|
return {"action": "list"}
|
||||||
|
|
||||||
|
elif action == "add":
|
||||||
|
questions = [
|
||||||
|
inquirer.Text("name", message="Server Name (identifier)"),
|
||||||
|
inquirer.Text("url", message="SSE URL (e.g., http://localhost:8000/sse)"),
|
||||||
|
inquirer.Confirm("enabled", message="Enabled?", default=True),
|
||||||
|
inquirer.Text("auto_load_os", message="Auto-load on specific OS (blank for any)")
|
||||||
|
]
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if answers:
|
||||||
|
return {
|
||||||
|
"action": "add",
|
||||||
|
"name": answers["name"],
|
||||||
|
"url": answers["url"],
|
||||||
|
"enabled": answers["enabled"],
|
||||||
|
"os": answers["auto_load_os"]
|
||||||
|
}
|
||||||
|
|
||||||
|
elif action == "toggle":
|
||||||
|
if not mcp_servers:
|
||||||
|
print("\nNo servers to toggle.\n")
|
||||||
|
continue
|
||||||
|
|
||||||
|
choices = []
|
||||||
|
for name, cfg in mcp_servers.items():
|
||||||
|
status = "[Enabled]" if cfg.get("enabled", True) else "[Disabled]"
|
||||||
|
choices.append((f"{name} {status}", name))
|
||||||
|
|
||||||
|
questions = [
|
||||||
|
inquirer.List("name", message="Select server to toggle", choices=choices + [("Cancel", None)])
|
||||||
|
]
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if answers and answers["name"]:
|
||||||
|
current = mcp_servers[answers["name"]].get("enabled", True)
|
||||||
|
return {
|
||||||
|
"action": "update",
|
||||||
|
"name": answers["name"],
|
||||||
|
"enabled": not current
|
||||||
|
}
|
||||||
|
|
||||||
|
elif action == "remove":
|
||||||
|
if not mcp_servers:
|
||||||
|
print("\nNo servers to remove.\n")
|
||||||
|
continue
|
||||||
|
|
||||||
|
questions = [
|
||||||
|
inquirer.List("name", message="Select server to remove", choices=list(mcp_servers.keys()) + ["Cancel"])
|
||||||
|
]
|
||||||
|
answers = inquirer.prompt(questions, theme=theme)
|
||||||
|
if answers and answers["name"] != "Cancel":
|
||||||
|
return {"action": "remove", "name": answers["name"]}
|
||||||
|
return None</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Interactive wizard to manage MCP servers.</p></div>
|
||||||
|
</dd>
|
||||||
<dt id="connpy.cli.forms.Forms.questions_bulk"><code class="name flex">
|
<dt id="connpy.cli.forms.Forms.questions_bulk"><code class="name flex">
|
||||||
<span>def <span class="ident">questions_bulk</span></span>(<span>self, nodes='', hosts='')</span>
|
<span>def <span class="ident">questions_bulk</span></span>(<span>self, nodes='', hosts='')</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
@@ -505,6 +677,7 @@ el.replaceWith(d);
|
|||||||
<li>
|
<li>
|
||||||
<h4><code><a title="connpy.cli.forms.Forms" href="#connpy.cli.forms.Forms">Forms</a></code></h4>
|
<h4><code><a title="connpy.cli.forms.Forms" href="#connpy.cli.forms.Forms">Forms</a></code></h4>
|
||||||
<ul class="">
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.cli.forms.Forms.mcp_wizard" href="#connpy.cli.forms.Forms.mcp_wizard">mcp_wizard</a></code></li>
|
||||||
<li><code><a title="connpy.cli.forms.Forms.questions_bulk" href="#connpy.cli.forms.Forms.questions_bulk">questions_bulk</a></code></li>
|
<li><code><a title="connpy.cli.forms.Forms.questions_bulk" href="#connpy.cli.forms.Forms.questions_bulk">questions_bulk</a></code></li>
|
||||||
<li><code><a title="connpy.cli.forms.Forms.questions_edit" href="#connpy.cli.forms.Forms.questions_edit">questions_edit</a></code></li>
|
<li><code><a title="connpy.cli.forms.Forms.questions_edit" href="#connpy.cli.forms.Forms.questions_edit">questions_edit</a></code></li>
|
||||||
<li><code><a title="connpy.cli.forms.Forms.questions_nodes" href="#connpy.cli.forms.Forms.questions_nodes">questions_nodes</a></code></li>
|
<li><code><a title="connpy.cli.forms.Forms.questions_nodes" href="#connpy.cli.forms.Forms.questions_nodes">questions_nodes</a></code></li>
|
||||||
@@ -517,7 +690,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.help_text API documentation</title>
|
<title>connpy.cli.help_text API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -117,6 +117,10 @@ Here are some important instructions and tips for configuring your new node:
|
|||||||
- `prompt`: Replaces default app prompt to identify the end of output or where the user can start inputting commands.
|
- `prompt`: Replaces default app prompt to identify the end of output or where the user can start inputting commands.
|
||||||
- `kube_command`: Replaces the default command (`/bin/bash`) for `kubectl exec`.
|
- `kube_command`: Replaces the default command (`/bin/bash`) for `kubectl exec`.
|
||||||
- `docker_command`: Replaces the default command for `docker exec`.
|
- `docker_command`: Replaces the default command for `docker exec`.
|
||||||
|
- `region`: AWS Region used for `aws ssm start-session`.
|
||||||
|
- `profile`: AWS Profile used for `aws ssm start-session`.
|
||||||
|
- `ssh_options`: Additional SSH options injected when an SSM node is used as a jumphost (e.g., `-i ~/.ssh/key.pem`).
|
||||||
|
- `nc_command`: Replaces the default `nc` command used when bridging connections through Docker or Kubernetes (e.g., `ip netns exec global-vrf nc`).
|
||||||
"""
|
"""
|
||||||
if type == "bashcompletion":
|
if type == "bashcompletion":
|
||||||
return '''
|
return '''
|
||||||
@@ -215,9 +219,7 @@ tasks:
|
|||||||
nodes: #List of nodes to work on. Mandatory
|
nodes: #List of nodes to work on. Mandatory
|
||||||
- 'router1@office' #You can add specific nodes
|
- 'router1@office' #You can add specific nodes
|
||||||
- '@aws' #entire folders or subfolders
|
- '@aws' #entire folders or subfolders
|
||||||
- '@office': #or filter inside a folder or subfolder
|
- 'router.*@office' #or use regex to filter inside a folder
|
||||||
- 'router2'
|
|
||||||
- 'router7'
|
|
||||||
|
|
||||||
commands: #List of commands to send, use {name} to pass variables
|
commands: #List of commands to send, use {name} to pass variables
|
||||||
- 'term len 0'
|
- 'term len 0'
|
||||||
@@ -243,7 +245,7 @@ tasks:
|
|||||||
vrouterN@aws:
|
vrouterN@aws:
|
||||||
id: 5
|
id: 5
|
||||||
|
|
||||||
output: /home/user/logs #Type of output, if null you only get Connection and test result. Choices are: null,stdout,/path/to/folder. Folder path only works on 'run' action.
|
output: /home/user/logs #Type of output, if null you only get Connection and test result. Choices are: null,stdout,/path/to/folder. Folder path works on both 'run' and 'test' actions.
|
||||||
|
|
||||||
options:
|
options:
|
||||||
prompt: r'>$|#$|\$$|>.$|#.$|\$.$' #Optional prompt to check on your devices, default should work on most devices.
|
prompt: r'>$|#$|\$$|>.$|#.$|\$.$' #Optional prompt to check on your devices, default should work on most devices.
|
||||||
@@ -255,9 +257,6 @@ tasks:
|
|||||||
nodes:
|
nodes:
|
||||||
- 'router1@office'
|
- 'router1@office'
|
||||||
- '@aws'
|
- '@aws'
|
||||||
- '@office':
|
|
||||||
- 'router2'
|
|
||||||
- 'router7'
|
|
||||||
commands:
|
commands:
|
||||||
- 'ping 10.100.100.{id}'
|
- 'ping 10.100.100.{id}'
|
||||||
expected: '!' #Expected text to find when running test action. Mandatory for 'test'
|
expected: '!' #Expected text to find when running test action. Mandatory for 'test'
|
||||||
@@ -304,7 +303,7 @@ tasks:
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.helpers API documentation</title>
|
<title>connpy.cli.helpers API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -207,7 +207,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.import_export_handler API documentation</title>
|
<title>connpy.cli.import_export_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -272,7 +272,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli API documentation</title>
|
<title>connpy.cli API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -92,6 +92,10 @@ el.replaceWith(d);
|
|||||||
<dd>
|
<dd>
|
||||||
<div class="desc"></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
|
<dt><code class="name"><a title="connpy.cli.terminal_ui" href="terminal_ui.html">connpy.cli.terminal_ui</a></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
<dt><code class="name"><a title="connpy.cli.validators" href="validators.html">connpy.cli.validators</a></code></dt>
|
<dt><code class="name"><a title="connpy.cli.validators" href="validators.html">connpy.cli.validators</a></code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<div class="desc"></div>
|
<div class="desc"></div>
|
||||||
@@ -130,6 +134,7 @@ el.replaceWith(d);
|
|||||||
<li><code><a title="connpy.cli.profile_handler" href="profile_handler.html">connpy.cli.profile_handler</a></code></li>
|
<li><code><a title="connpy.cli.profile_handler" href="profile_handler.html">connpy.cli.profile_handler</a></code></li>
|
||||||
<li><code><a title="connpy.cli.run_handler" href="run_handler.html">connpy.cli.run_handler</a></code></li>
|
<li><code><a title="connpy.cli.run_handler" href="run_handler.html">connpy.cli.run_handler</a></code></li>
|
||||||
<li><code><a title="connpy.cli.sync_handler" href="sync_handler.html">connpy.cli.sync_handler</a></code></li>
|
<li><code><a title="connpy.cli.sync_handler" href="sync_handler.html">connpy.cli.sync_handler</a></code></li>
|
||||||
|
<li><code><a title="connpy.cli.terminal_ui" href="terminal_ui.html">connpy.cli.terminal_ui</a></code></li>
|
||||||
<li><code><a title="connpy.cli.validators" href="validators.html">connpy.cli.validators</a></code></li>
|
<li><code><a title="connpy.cli.validators" href="validators.html">connpy.cli.validators</a></code></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
@@ -137,7 +142,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.node_handler API documentation</title>
|
<title>connpy.cli.node_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -606,7 +606,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.plugin_handler API documentation</title>
|
<title>connpy.cli.plugin_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -385,7 +385,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.profile_handler API documentation</title>
|
<title>connpy.cli.profile_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -314,7 +314,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.run_handler API documentation</title>
|
<title>connpy.cli.run_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -58,6 +58,7 @@ el.replaceWith(d);
|
|||||||
<pre><code class="python">class RunHandler:
|
<pre><code class="python">class RunHandler:
|
||||||
def __init__(self, app):
|
def __init__(self, app):
|
||||||
self.app = app
|
self.app = app
|
||||||
|
self.print_lock = threading.Lock()
|
||||||
|
|
||||||
def dispatch(self, args):
|
def dispatch(self, args):
|
||||||
if len(args.data) > 1:
|
if len(args.data) > 1:
|
||||||
@@ -71,19 +72,40 @@ el.replaceWith(d);
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
header_printed = False
|
header_printed = False
|
||||||
# Inline execution with streaming results
|
|
||||||
|
if hasattr(args, 'test_expected') and args.test_expected:
|
||||||
|
# Mode: Test
|
||||||
|
def _on_node_complete(unique, node_output, node_status, node_result):
|
||||||
|
nonlocal header_printed
|
||||||
|
with self.print_lock:
|
||||||
|
if not header_printed:
|
||||||
|
printer.console.print(Rule("OUTPUT", style="header"))
|
||||||
|
header_printed = True
|
||||||
|
printer.test_panel(unique, node_output, node_status, node_result)
|
||||||
|
|
||||||
|
results = self.app.services.execution.test_commands(
|
||||||
|
nodes_filter=nodes_filter,
|
||||||
|
commands=commands,
|
||||||
|
expected=args.test_expected,
|
||||||
|
on_node_complete=_on_node_complete
|
||||||
|
)
|
||||||
|
printer.test_summary(results)
|
||||||
|
else:
|
||||||
|
# Mode: Normal Run
|
||||||
def _on_node_complete(unique, node_output, node_status):
|
def _on_node_complete(unique, node_output, node_status):
|
||||||
nonlocal header_printed
|
nonlocal header_printed
|
||||||
|
with self.print_lock:
|
||||||
if not header_printed:
|
if not header_printed:
|
||||||
printer.console.print(Rule("OUTPUT", style="header"))
|
printer.console.print(Rule("OUTPUT", style="header"))
|
||||||
header_printed = True
|
header_printed = True
|
||||||
printer.node_panel(unique, node_output, node_status)
|
printer.node_panel(unique, node_output, node_status)
|
||||||
|
|
||||||
self.app.services.execution.run_commands(
|
results = self.app.services.execution.run_commands(
|
||||||
nodes_filter=nodes_filter,
|
nodes_filter=nodes_filter,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
on_node_complete=_on_node_complete
|
on_node_complete=_on_node_complete
|
||||||
)
|
)
|
||||||
|
printer.run_summary(results)
|
||||||
|
|
||||||
except ConnpyError as e:
|
except ConnpyError as e:
|
||||||
printer.error(str(e))
|
printer.error(str(e))
|
||||||
@@ -113,56 +135,80 @@ el.replaceWith(d);
|
|||||||
sys.exit(10)
|
sys.exit(10)
|
||||||
|
|
||||||
def cli_run(self, script):
|
def cli_run(self, script):
|
||||||
|
name = script.get("name", "Task")
|
||||||
try:
|
try:
|
||||||
action = script["action"]
|
action = script["action"]
|
||||||
nodelist = script["nodes"]
|
nodelist = script["nodes"]
|
||||||
commands = script["commands"]
|
commands = script["commands"]
|
||||||
variables = script.get("variables")
|
variables = script.get("variables")
|
||||||
output_cfg = script["output"]
|
output_cfg = script["output"]
|
||||||
name = script.get("name", "Task")
|
|
||||||
options = script.get("options", {})
|
options = script.get("options", {})
|
||||||
except KeyError as e:
|
except KeyError as e:
|
||||||
printer.error(f"'{e.args[0]}' is mandatory in script")
|
printer.error(f"[{name}] '{e.args[0]}' is mandatory in script")
|
||||||
sys.exit(11)
|
sys.exit(11)
|
||||||
|
|
||||||
stdout = (output_cfg == "stdout")
|
stdout = (output_cfg == "stdout")
|
||||||
folder = output_cfg if output_cfg not in [None, "stdout"] else None
|
folder = output_cfg if output_cfg not in [None, "stdout"] else None
|
||||||
prompt = options.get("prompt")
|
prompt = options.get("prompt")
|
||||||
printer.header(name.upper())
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
header_printed = False
|
||||||
if action == "run":
|
if action == "run":
|
||||||
# If stdout is true, we stream results as they arrive
|
# If stdout is true, we stream results as they arrive
|
||||||
on_complete = printer.node_panel if stdout else None
|
def _on_run_complete(unique, node_output, node_status):
|
||||||
|
nonlocal header_printed
|
||||||
|
if stdout:
|
||||||
|
with self.print_lock:
|
||||||
|
if not header_printed:
|
||||||
|
printer.console.print(Rule(name.upper(), style="header"))
|
||||||
|
header_printed = True
|
||||||
|
printer.node_panel(unique, node_output, node_status)
|
||||||
|
|
||||||
results = self.app.services.execution.run_commands(
|
results = self.app.services.execution.run_commands(
|
||||||
nodes_filter=nodelist,
|
nodes_filter=nodelist,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
variables=variables,
|
variables=variables,
|
||||||
parallel=options.get("parallel", 10),
|
parallel=options.get("parallel", 10),
|
||||||
timeout=options.get("timeout", 10),
|
timeout=options.get("timeout", 20),
|
||||||
folder=folder,
|
folder=folder,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
on_node_complete=on_complete
|
on_node_complete=_on_run_complete
|
||||||
)
|
)
|
||||||
# If not streaming, we could print a summary table here if needed
|
# Final Summary
|
||||||
if not stdout:
|
if not stdout and not folder:
|
||||||
for unique, output in results.items():
|
with self.print_lock:
|
||||||
|
printer.console.print(Rule(name.upper(), style="header"))
|
||||||
|
for unique, data in results.items():
|
||||||
|
output = data["output"] if isinstance(data, dict) else data
|
||||||
printer.node_panel(unique, output, 0)
|
printer.node_panel(unique, output, 0)
|
||||||
|
|
||||||
|
# ALWAYS show the aggregate execution summary at the end
|
||||||
|
printer.run_summary(results)
|
||||||
|
|
||||||
elif action == "test":
|
elif action == "test":
|
||||||
expected = script.get("expected", [])
|
expected = script.get("expected", [])
|
||||||
on_complete = printer.test_panel if stdout else None
|
# Show test_panel per node ONLY if stdout is True
|
||||||
|
def _on_test_complete(unique, node_output, node_status, node_result):
|
||||||
|
nonlocal header_printed
|
||||||
|
if stdout:
|
||||||
|
with self.print_lock:
|
||||||
|
if not header_printed:
|
||||||
|
printer.console.print(Rule(name.upper(), style="header"))
|
||||||
|
header_printed = True
|
||||||
|
printer.test_panel(unique, node_output, node_status, node_result)
|
||||||
|
|
||||||
results = self.app.services.execution.test_commands(
|
results = self.app.services.execution.test_commands(
|
||||||
nodes_filter=nodelist,
|
nodes_filter=nodelist,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
expected=expected,
|
expected=expected,
|
||||||
variables=variables,
|
variables=variables,
|
||||||
parallel=options.get("parallel", 10),
|
parallel=options.get("parallel", 10),
|
||||||
timeout=options.get("timeout", 10),
|
timeout=options.get("timeout", 20),
|
||||||
|
folder=folder,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
on_node_complete=on_complete
|
on_node_complete=_on_test_complete
|
||||||
)
|
)
|
||||||
if not stdout:
|
# ALWAYS show the aggregate summary at the end
|
||||||
printer.test_summary(results)
|
printer.test_summary(results)
|
||||||
|
|
||||||
except ConnpyError as e:
|
except ConnpyError as e:
|
||||||
@@ -180,56 +226,80 @@ el.replaceWith(d);
|
|||||||
<span>Expand source code</span>
|
<span>Expand source code</span>
|
||||||
</summary>
|
</summary>
|
||||||
<pre><code class="python">def cli_run(self, script):
|
<pre><code class="python">def cli_run(self, script):
|
||||||
|
name = script.get("name", "Task")
|
||||||
try:
|
try:
|
||||||
action = script["action"]
|
action = script["action"]
|
||||||
nodelist = script["nodes"]
|
nodelist = script["nodes"]
|
||||||
commands = script["commands"]
|
commands = script["commands"]
|
||||||
variables = script.get("variables")
|
variables = script.get("variables")
|
||||||
output_cfg = script["output"]
|
output_cfg = script["output"]
|
||||||
name = script.get("name", "Task")
|
|
||||||
options = script.get("options", {})
|
options = script.get("options", {})
|
||||||
except KeyError as e:
|
except KeyError as e:
|
||||||
printer.error(f"'{e.args[0]}' is mandatory in script")
|
printer.error(f"[{name}] '{e.args[0]}' is mandatory in script")
|
||||||
sys.exit(11)
|
sys.exit(11)
|
||||||
|
|
||||||
stdout = (output_cfg == "stdout")
|
stdout = (output_cfg == "stdout")
|
||||||
folder = output_cfg if output_cfg not in [None, "stdout"] else None
|
folder = output_cfg if output_cfg not in [None, "stdout"] else None
|
||||||
prompt = options.get("prompt")
|
prompt = options.get("prompt")
|
||||||
printer.header(name.upper())
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
header_printed = False
|
||||||
if action == "run":
|
if action == "run":
|
||||||
# If stdout is true, we stream results as they arrive
|
# If stdout is true, we stream results as they arrive
|
||||||
on_complete = printer.node_panel if stdout else None
|
def _on_run_complete(unique, node_output, node_status):
|
||||||
|
nonlocal header_printed
|
||||||
|
if stdout:
|
||||||
|
with self.print_lock:
|
||||||
|
if not header_printed:
|
||||||
|
printer.console.print(Rule(name.upper(), style="header"))
|
||||||
|
header_printed = True
|
||||||
|
printer.node_panel(unique, node_output, node_status)
|
||||||
|
|
||||||
results = self.app.services.execution.run_commands(
|
results = self.app.services.execution.run_commands(
|
||||||
nodes_filter=nodelist,
|
nodes_filter=nodelist,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
variables=variables,
|
variables=variables,
|
||||||
parallel=options.get("parallel", 10),
|
parallel=options.get("parallel", 10),
|
||||||
timeout=options.get("timeout", 10),
|
timeout=options.get("timeout", 20),
|
||||||
folder=folder,
|
folder=folder,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
on_node_complete=on_complete
|
on_node_complete=_on_run_complete
|
||||||
)
|
)
|
||||||
# If not streaming, we could print a summary table here if needed
|
# Final Summary
|
||||||
if not stdout:
|
if not stdout and not folder:
|
||||||
for unique, output in results.items():
|
with self.print_lock:
|
||||||
|
printer.console.print(Rule(name.upper(), style="header"))
|
||||||
|
for unique, data in results.items():
|
||||||
|
output = data["output"] if isinstance(data, dict) else data
|
||||||
printer.node_panel(unique, output, 0)
|
printer.node_panel(unique, output, 0)
|
||||||
|
|
||||||
|
# ALWAYS show the aggregate execution summary at the end
|
||||||
|
printer.run_summary(results)
|
||||||
|
|
||||||
elif action == "test":
|
elif action == "test":
|
||||||
expected = script.get("expected", [])
|
expected = script.get("expected", [])
|
||||||
on_complete = printer.test_panel if stdout else None
|
# Show test_panel per node ONLY if stdout is True
|
||||||
|
def _on_test_complete(unique, node_output, node_status, node_result):
|
||||||
|
nonlocal header_printed
|
||||||
|
if stdout:
|
||||||
|
with self.print_lock:
|
||||||
|
if not header_printed:
|
||||||
|
printer.console.print(Rule(name.upper(), style="header"))
|
||||||
|
header_printed = True
|
||||||
|
printer.test_panel(unique, node_output, node_status, node_result)
|
||||||
|
|
||||||
results = self.app.services.execution.test_commands(
|
results = self.app.services.execution.test_commands(
|
||||||
nodes_filter=nodelist,
|
nodes_filter=nodelist,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
expected=expected,
|
expected=expected,
|
||||||
variables=variables,
|
variables=variables,
|
||||||
parallel=options.get("parallel", 10),
|
parallel=options.get("parallel", 10),
|
||||||
timeout=options.get("timeout", 10),
|
timeout=options.get("timeout", 20),
|
||||||
|
folder=folder,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
on_node_complete=on_complete
|
on_node_complete=_on_test_complete
|
||||||
)
|
)
|
||||||
if not stdout:
|
# ALWAYS show the aggregate summary at the end
|
||||||
printer.test_summary(results)
|
printer.test_summary(results)
|
||||||
|
|
||||||
except ConnpyError as e:
|
except ConnpyError as e:
|
||||||
@@ -267,19 +337,40 @@ el.replaceWith(d);
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
header_printed = False
|
header_printed = False
|
||||||
# Inline execution with streaming results
|
|
||||||
|
if hasattr(args, 'test_expected') and args.test_expected:
|
||||||
|
# Mode: Test
|
||||||
|
def _on_node_complete(unique, node_output, node_status, node_result):
|
||||||
|
nonlocal header_printed
|
||||||
|
with self.print_lock:
|
||||||
|
if not header_printed:
|
||||||
|
printer.console.print(Rule("OUTPUT", style="header"))
|
||||||
|
header_printed = True
|
||||||
|
printer.test_panel(unique, node_output, node_status, node_result)
|
||||||
|
|
||||||
|
results = self.app.services.execution.test_commands(
|
||||||
|
nodes_filter=nodes_filter,
|
||||||
|
commands=commands,
|
||||||
|
expected=args.test_expected,
|
||||||
|
on_node_complete=_on_node_complete
|
||||||
|
)
|
||||||
|
printer.test_summary(results)
|
||||||
|
else:
|
||||||
|
# Mode: Normal Run
|
||||||
def _on_node_complete(unique, node_output, node_status):
|
def _on_node_complete(unique, node_output, node_status):
|
||||||
nonlocal header_printed
|
nonlocal header_printed
|
||||||
|
with self.print_lock:
|
||||||
if not header_printed:
|
if not header_printed:
|
||||||
printer.console.print(Rule("OUTPUT", style="header"))
|
printer.console.print(Rule("OUTPUT", style="header"))
|
||||||
header_printed = True
|
header_printed = True
|
||||||
printer.node_panel(unique, node_output, node_status)
|
printer.node_panel(unique, node_output, node_status)
|
||||||
|
|
||||||
self.app.services.execution.run_commands(
|
results = self.app.services.execution.run_commands(
|
||||||
nodes_filter=nodes_filter,
|
nodes_filter=nodes_filter,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
on_node_complete=_on_node_complete
|
on_node_complete=_on_node_complete
|
||||||
)
|
)
|
||||||
|
printer.run_summary(results)
|
||||||
|
|
||||||
except ConnpyError as e:
|
except ConnpyError as e:
|
||||||
printer.error(str(e))
|
printer.error(str(e))
|
||||||
@@ -363,7 +454,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.sync_handler API documentation</title>
|
<title>connpy.cli.sync_handler API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -427,7 +427,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.cli.validators API documentation</title>
|
<title>connpy.cli.validators API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -508,7 +508,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.grpc_layer.connpy_pb2 API documentation</title>
|
<title>connpy.grpc_layer.connpy_pb2 API documentation</title>
|
||||||
<meta name="description" content="Generated protocol buffer code.">
|
<meta name="description" content="Generated protocol buffer code.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -45,6 +45,617 @@ el.replaceWith(d);
|
|||||||
<section>
|
<section>
|
||||||
</section>
|
</section>
|
||||||
<section>
|
<section>
|
||||||
|
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.AIResponse"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">AIResponse</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.AIResponse.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.AskRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">AskRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.AskRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.BoolResponse"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">BoolResponse</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.BoolResponse.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.BulkRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">BulkRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.BulkRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.CopilotRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">CopilotRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.CopilotRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.CopilotResponse"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">CopilotResponse</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.CopilotResponse.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.DeleteRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">DeleteRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.DeleteRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ExportRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">ExportRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ExportRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.FilterRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">FilterRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.FilterRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.FullReplaceRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">FullReplaceRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.FullReplaceRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.IdRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">IdRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.IdRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.IntRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">IntRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.IntRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.InteractRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">InteractRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.InteractRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.InteractResponse"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">InteractResponse</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.InteractResponse.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ListRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">ListRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ListRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.MCPRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">MCPRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.MCPRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.MessageValue"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">MessageValue</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.MessageValue.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.MoveRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">MoveRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.MoveRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.NodeRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">NodeRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.NodeRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.NodeRunResult"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">NodeRunResult</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.NodeRunResult.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.PluginRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">PluginRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.PluginRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ProfileRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">ProfileRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ProfileRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ProviderRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">ProviderRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ProviderRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.RunRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">RunRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.RunRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ScriptRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">ScriptRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ScriptRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.StringRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">StringRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.StringRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.StringResponse"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">StringResponse</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.StringResponse.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.StructRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">StructRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.StructRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.StructResponse"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">StructResponse</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.StructResponse.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.TestRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">TestRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.TestRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.UpdateRequest"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">UpdateRequest</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.UpdateRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ValueResponse"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">ValueResponse</span></span>
|
||||||
|
<span>(</span><span>*args, **kwargs)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"><p>A ProtocolMessage</p></div>
|
||||||
|
<h3>Ancestors</h3>
|
||||||
|
<ul class="hlist">
|
||||||
|
<li>google._upb._message.Message</li>
|
||||||
|
<li>google.protobuf.message.Message</li>
|
||||||
|
</ul>
|
||||||
|
<h3>Class variables</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.grpc_layer.connpy_pb2.ValueResponse.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
</section>
|
</section>
|
||||||
</article>
|
</article>
|
||||||
<nav id="sidebar">
|
<nav id="sidebar">
|
||||||
@@ -57,11 +668,207 @@ el.replaceWith(d);
|
|||||||
<li><code><a title="connpy.grpc_layer" href="index.html">connpy.grpc_layer</a></code></li>
|
<li><code><a title="connpy.grpc_layer" href="index.html">connpy.grpc_layer</a></code></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
|
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.AIResponse" href="#connpy.grpc_layer.connpy_pb2.AIResponse">AIResponse</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.AIResponse.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.AIResponse.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.AskRequest" href="#connpy.grpc_layer.connpy_pb2.AskRequest">AskRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.AskRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.AskRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.BoolResponse" href="#connpy.grpc_layer.connpy_pb2.BoolResponse">BoolResponse</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.BoolResponse.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.BoolResponse.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.BulkRequest" href="#connpy.grpc_layer.connpy_pb2.BulkRequest">BulkRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.BulkRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.BulkRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.CopilotRequest" href="#connpy.grpc_layer.connpy_pb2.CopilotRequest">CopilotRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.CopilotRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.CopilotRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.CopilotResponse" href="#connpy.grpc_layer.connpy_pb2.CopilotResponse">CopilotResponse</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.CopilotResponse.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.CopilotResponse.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.DeleteRequest" href="#connpy.grpc_layer.connpy_pb2.DeleteRequest">DeleteRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.DeleteRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.DeleteRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.ExportRequest" href="#connpy.grpc_layer.connpy_pb2.ExportRequest">ExportRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.ExportRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.ExportRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.FilterRequest" href="#connpy.grpc_layer.connpy_pb2.FilterRequest">FilterRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.FilterRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.FilterRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.FullReplaceRequest" href="#connpy.grpc_layer.connpy_pb2.FullReplaceRequest">FullReplaceRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.FullReplaceRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.FullReplaceRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.IdRequest" href="#connpy.grpc_layer.connpy_pb2.IdRequest">IdRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.IdRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.IdRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.IntRequest" href="#connpy.grpc_layer.connpy_pb2.IntRequest">IntRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.IntRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.IntRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.InteractRequest" href="#connpy.grpc_layer.connpy_pb2.InteractRequest">InteractRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.InteractRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.InteractRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.InteractResponse" href="#connpy.grpc_layer.connpy_pb2.InteractResponse">InteractResponse</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.InteractResponse.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.InteractResponse.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.ListRequest" href="#connpy.grpc_layer.connpy_pb2.ListRequest">ListRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.ListRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.ListRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.MCPRequest" href="#connpy.grpc_layer.connpy_pb2.MCPRequest">MCPRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.MCPRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.MCPRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.MessageValue" href="#connpy.grpc_layer.connpy_pb2.MessageValue">MessageValue</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.MessageValue.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.MessageValue.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.MoveRequest" href="#connpy.grpc_layer.connpy_pb2.MoveRequest">MoveRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.MoveRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.MoveRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.NodeRequest" href="#connpy.grpc_layer.connpy_pb2.NodeRequest">NodeRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.NodeRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.NodeRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.NodeRunResult" href="#connpy.grpc_layer.connpy_pb2.NodeRunResult">NodeRunResult</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.NodeRunResult.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.NodeRunResult.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.PluginRequest" href="#connpy.grpc_layer.connpy_pb2.PluginRequest">PluginRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.PluginRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.PluginRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.ProfileRequest" href="#connpy.grpc_layer.connpy_pb2.ProfileRequest">ProfileRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.ProfileRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.ProfileRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.ProviderRequest" href="#connpy.grpc_layer.connpy_pb2.ProviderRequest">ProviderRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.ProviderRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.ProviderRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.RunRequest" href="#connpy.grpc_layer.connpy_pb2.RunRequest">RunRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.RunRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.RunRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.ScriptRequest" href="#connpy.grpc_layer.connpy_pb2.ScriptRequest">ScriptRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.ScriptRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.ScriptRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.StringRequest" href="#connpy.grpc_layer.connpy_pb2.StringRequest">StringRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.StringRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.StringRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.StringResponse" href="#connpy.grpc_layer.connpy_pb2.StringResponse">StringResponse</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.StringResponse.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.StringResponse.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.StructRequest" href="#connpy.grpc_layer.connpy_pb2.StructRequest">StructRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.StructRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.StructRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.StructResponse" href="#connpy.grpc_layer.connpy_pb2.StructResponse">StructResponse</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.StructResponse.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.StructResponse.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.TestRequest" href="#connpy.grpc_layer.connpy_pb2.TestRequest">TestRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.TestRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.TestRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.UpdateRequest" href="#connpy.grpc_layer.connpy_pb2.UpdateRequest">UpdateRequest</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.UpdateRequest.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.UpdateRequest.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.grpc_layer.connpy_pb2.ValueResponse" href="#connpy.grpc_layer.connpy_pb2.ValueResponse">ValueResponse</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2.ValueResponse.DESCRIPTOR" href="#connpy.grpc_layer.connpy_pb2.ValueResponse.DESCRIPTOR">DESCRIPTOR</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.grpc_layer API documentation</title>
|
<title>connpy.grpc_layer API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -102,7 +102,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.grpc_layer.remote_plugin_pb2 API documentation</title>
|
<title>connpy.grpc_layer.remote_plugin_pb2 API documentation</title>
|
||||||
<meta name="description" content="Generated protocol buffer code.">
|
<meta name="description" content="Generated protocol buffer code.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -62,7 +62,7 @@ el.replaceWith(d);
|
|||||||
<dl>
|
<dl>
|
||||||
<dt id="connpy.grpc_layer.remote_plugin_pb2.IdRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
<dt id="connpy.grpc_layer.remote_plugin_pb2.IdRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<div class="desc"><p>The type of the None singleton.</p></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -81,7 +81,7 @@ el.replaceWith(d);
|
|||||||
<dl>
|
<dl>
|
||||||
<dt id="connpy.grpc_layer.remote_plugin_pb2.OutputChunk.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
<dt id="connpy.grpc_layer.remote_plugin_pb2.OutputChunk.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<div class="desc"><p>The type of the None singleton.</p></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -100,7 +100,7 @@ el.replaceWith(d);
|
|||||||
<dl>
|
<dl>
|
||||||
<dt id="connpy.grpc_layer.remote_plugin_pb2.PluginInvokeRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
<dt id="connpy.grpc_layer.remote_plugin_pb2.PluginInvokeRequest.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<div class="desc"><p>The type of the None singleton.</p></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -119,7 +119,7 @@ el.replaceWith(d);
|
|||||||
<dl>
|
<dl>
|
||||||
<dt id="connpy.grpc_layer.remote_plugin_pb2.StringResponse.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
<dt id="connpy.grpc_layer.remote_plugin_pb2.StringResponse.DESCRIPTOR"><code class="name">var <span class="ident">DESCRIPTOR</span></code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<div class="desc"><p>The type of the None singleton.</p></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -168,7 +168,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.grpc_layer.remote_plugin_pb2_grpc API documentation</title>
|
<title>connpy.grpc_layer.remote_plugin_pb2_grpc API documentation</title>
|
||||||
<meta name="description" content="Client and server classes corresponding to protobuf-defined services.">
|
<meta name="description" content="Client and server classes corresponding to protobuf-defined services.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -366,7 +366,7 @@ def invoke_plugin(request,
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.grpc_layer.server API documentation</title>
|
<title>connpy.grpc_layer.server API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -96,7 +96,7 @@ el.replaceWith(d);
|
|||||||
interceptors = [LoggingInterceptor()] if debug else []
|
interceptors = [LoggingInterceptor()] if debug else []
|
||||||
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=interceptors)
|
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=interceptors)
|
||||||
|
|
||||||
connpy_pb2_grpc.add_NodeServiceServicer_to_server(NodeServicer(config), server)
|
connpy_pb2_grpc.add_NodeServiceServicer_to_server(NodeServicer(config, debug=debug), server)
|
||||||
connpy_pb2_grpc.add_ProfileServiceServicer_to_server(ProfileServicer(config), server)
|
connpy_pb2_grpc.add_ProfileServiceServicer_to_server(ProfileServicer(config), server)
|
||||||
connpy_pb2_grpc.add_ConfigServiceServicer_to_server(ConfigServicer(config), server)
|
connpy_pb2_grpc.add_ConfigServiceServicer_to_server(ConfigServicer(config), server)
|
||||||
plugin_servicer = PluginServicer(config)
|
plugin_servicer = PluginServicer(config)
|
||||||
@@ -207,6 +207,8 @@ el.replaceWith(d);
|
|||||||
daemon=True
|
daemon=True
|
||||||
)
|
)
|
||||||
ai_thread.start()
|
ai_thread.start()
|
||||||
|
except grpc.RpcError:
|
||||||
|
pass
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Request Listener Error: {e}")
|
print(f"Request Listener Error: {e}")
|
||||||
finally:
|
finally:
|
||||||
@@ -243,6 +245,22 @@ el.replaceWith(d);
|
|||||||
res = self.service.confirm(request.value)
|
res = self.service.confirm(request.value)
|
||||||
return connpy_pb2.BoolResponse(value=res)
|
return connpy_pb2.BoolResponse(value=res)
|
||||||
|
|
||||||
|
@handle_errors
|
||||||
|
def ask_copilot(self, request, context):
|
||||||
|
import json
|
||||||
|
node_info = json.loads(request.node_info_json) if request.node_info_json else None
|
||||||
|
result = self.service.ask_copilot(
|
||||||
|
request.terminal_buffer,
|
||||||
|
request.user_question,
|
||||||
|
node_info
|
||||||
|
)
|
||||||
|
return connpy_pb2.CopilotResponse(
|
||||||
|
commands=result.get("commands", []),
|
||||||
|
guide=result.get("guide", ""),
|
||||||
|
risk_level=result.get("risk_level", "low"),
|
||||||
|
error=result.get("error") or ""
|
||||||
|
)
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def list_sessions(self, request, context):
|
def list_sessions(self, request, context):
|
||||||
return connpy_pb2.ValueResponse(data=to_value(self.service.list_sessions()))
|
return connpy_pb2.ValueResponse(data=to_value(self.service.list_sessions()))
|
||||||
@@ -257,6 +275,17 @@ el.replaceWith(d);
|
|||||||
self.service.configure_provider(request.provider, request.model, request.api_key)
|
self.service.configure_provider(request.provider, request.model, request.api_key)
|
||||||
return Empty()
|
return Empty()
|
||||||
|
|
||||||
|
@handle_errors
|
||||||
|
def configure_mcp(self, request, context):
|
||||||
|
self.service.configure_mcp(
|
||||||
|
request.name,
|
||||||
|
url=request.url or None,
|
||||||
|
enabled=request.enabled,
|
||||||
|
auto_load_on_os=request.auto_load_on_os or None,
|
||||||
|
remove=request.remove
|
||||||
|
)
|
||||||
|
return Empty()
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def load_session_data(self, request, context):
|
def load_session_data(self, request, context):
|
||||||
return connpy_pb2.StructResponse(data=to_struct(self.service.load_session_data(request.value)))</code></pre>
|
return connpy_pb2.StructResponse(data=to_struct(self.service.load_session_data(request.value)))</code></pre>
|
||||||
@@ -271,6 +300,8 @@ el.replaceWith(d);
|
|||||||
<li><code><b><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer">AIServiceServicer</a></b></code>:
|
<li><code><b><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer">AIServiceServicer</a></b></code>:
|
||||||
<ul class="hlist">
|
<ul class="hlist">
|
||||||
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.ask" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.ask">ask</a></code></li>
|
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.ask" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.ask">ask</a></code></li>
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.ask_copilot" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.ask_copilot">ask_copilot</a></code></li>
|
||||||
|
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.configure_mcp" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.configure_mcp">configure_mcp</a></code></li>
|
||||||
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.configure_provider" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.configure_provider">configure_provider</a></code></li>
|
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.configure_provider" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.configure_provider">configure_provider</a></code></li>
|
||||||
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.confirm" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.confirm">confirm</a></code></li>
|
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.confirm" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.confirm">confirm</a></code></li>
|
||||||
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.delete_session" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.delete_session">delete_session</a></code></li>
|
<li><code><a title="connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.delete_session" href="connpy_pb2_grpc.html#connpy.grpc_layer.connpy_pb2_grpc.AIServiceServicer.delete_session">delete_session</a></code></li>
|
||||||
@@ -365,14 +396,15 @@ el.replaceWith(d);
|
|||||||
|
|
||||||
def _worker():
|
def _worker():
|
||||||
try:
|
try:
|
||||||
self.service.run_commands(
|
self.service.run_commands( nodes_filter=nodes_filter,
|
||||||
nodes_filter=nodes_filter,
|
|
||||||
commands=list(request.commands),
|
commands=list(request.commands),
|
||||||
folder=request.folder if request.folder else None,
|
folder=request.folder if request.folder else None,
|
||||||
prompt=request.prompt if request.prompt else None,
|
prompt=request.prompt if request.prompt else None,
|
||||||
parallel=request.parallel,
|
parallel=request.parallel,
|
||||||
|
timeout=request.timeout if request.timeout > 0 else 10,
|
||||||
variables=from_struct(request.vars) if request.HasField("vars") else None,
|
variables=from_struct(request.vars) if request.HasField("vars") else None,
|
||||||
on_node_complete=_on_complete
|
on_node_complete=_on_complete,
|
||||||
|
name=request.name if request.name else None
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Optionally pass error to stream, but handle_errors decorator covers top-level.
|
# Optionally pass error to stream, but handle_errors decorator covers top-level.
|
||||||
@@ -405,20 +437,22 @@ el.replaceWith(d);
|
|||||||
|
|
||||||
q = queue.Queue()
|
q = queue.Queue()
|
||||||
|
|
||||||
def _on_complete(unique, output, status, result):
|
def _on_complete(unique, node_output, node_status, node_result):
|
||||||
q.put({"unique_id": unique, "output": output, "status": status, "result": result})
|
q.put({"unique_id": unique, "output": node_output, "status": node_status, "result": node_result})
|
||||||
|
|
||||||
def _worker():
|
def _worker():
|
||||||
try:
|
try:
|
||||||
self.service.test_commands(
|
self.service.test_commands(
|
||||||
nodes_filter=nodes_filter,
|
nodes_filter=nodes_filter,
|
||||||
commands=list(request.commands),
|
commands=list(request.commands),
|
||||||
expected=request.expected,
|
expected=list(request.expected),
|
||||||
folder=request.folder if request.folder else None,
|
folder=request.folder if request.folder else None,
|
||||||
prompt=request.prompt if request.prompt else None,
|
prompt=request.prompt if request.prompt else None,
|
||||||
parallel=request.parallel,
|
parallel=request.parallel,
|
||||||
|
timeout=request.timeout if request.timeout > 0 else 10,
|
||||||
variables=from_struct(request.vars) if request.HasField("vars") else None,
|
variables=from_struct(request.vars) if request.HasField("vars") else None,
|
||||||
on_node_complete=_on_complete
|
on_node_complete=_on_complete,
|
||||||
|
name=request.name if request.name else None
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
q.put(e)
|
q.put(e)
|
||||||
@@ -613,7 +647,7 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
|
|||||||
</dd>
|
</dd>
|
||||||
<dt id="connpy.grpc_layer.server.NodeServicer"><code class="flex name class">
|
<dt id="connpy.grpc_layer.server.NodeServicer"><code class="flex name class">
|
||||||
<span>class <span class="ident">NodeServicer</span></span>
|
<span>class <span class="ident">NodeServicer</span></span>
|
||||||
<span>(</span><span>config)</span>
|
<span>(</span><span>config, debug=False)</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<details class="source">
|
<details class="source">
|
||||||
@@ -621,16 +655,24 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
|
|||||||
<span>Expand source code</span>
|
<span>Expand source code</span>
|
||||||
</summary>
|
</summary>
|
||||||
<pre><code class="python">class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
|
<pre><code class="python">class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
|
||||||
def __init__(self, config):
|
def __init__(self, config, debug=False):
|
||||||
self.service = NodeService(config)
|
self.service = NodeService(config)
|
||||||
|
self.server_debug = debug
|
||||||
|
if debug:
|
||||||
|
from rich.console import Console
|
||||||
|
from ..printer import connpy_theme, get_original_stdout
|
||||||
|
self.server_console = Console(theme=connpy_theme, file=get_original_stdout())
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def interact_node(self, request_iterator, context):
|
def interact_node(self, request_iterator, context):
|
||||||
import sys
|
import sys
|
||||||
import select
|
|
||||||
import os
|
import os
|
||||||
|
import asyncio
|
||||||
from connpy.core import node
|
from connpy.core import node
|
||||||
from ..services.profile_service import ProfileService
|
from ..services.profile_service import ProfileService
|
||||||
|
from connpy.tunnels import RemoteStream
|
||||||
|
import queue
|
||||||
|
import threading
|
||||||
|
|
||||||
# Fetch first setup packet
|
# Fetch first setup packet
|
||||||
try:
|
try:
|
||||||
@@ -641,7 +683,9 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
|
|||||||
unique_id = first_req.id
|
unique_id = first_req.id
|
||||||
sftp = first_req.sftp
|
sftp = first_req.sftp
|
||||||
debug = first_req.debug
|
debug = first_req.debug
|
||||||
printer.console.print(f"[debug][DEBUG][/debug] gRPC interact_node request for: [bold cyan]{unique_id}[/bold cyan]")
|
|
||||||
|
if self.server_debug:
|
||||||
|
self.server_console.print(f"[debug][DEBUG][/debug] gRPC interact_node request for: [bold cyan]{unique_id}[/bold cyan]")
|
||||||
|
|
||||||
if first_req.connection_params_json:
|
if first_req.connection_params_json:
|
||||||
import json
|
import json
|
||||||
@@ -700,7 +744,39 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
|
|||||||
if sftp:
|
if sftp:
|
||||||
n.protocol = "sftp"
|
n.protocol = "sftp"
|
||||||
|
|
||||||
connect = n._connect(debug=debug)
|
# Build a logger that captures debug messages as ANSI-colored bytes for the client
|
||||||
|
debug_chunks = []
|
||||||
|
if debug:
|
||||||
|
from io import StringIO
|
||||||
|
from rich.console import Console as RichConsole
|
||||||
|
from ..printer import connpy_theme
|
||||||
|
from .. import printer as _printer
|
||||||
|
|
||||||
|
def remote_logger(msg_type, message):
|
||||||
|
buf = StringIO()
|
||||||
|
c = RichConsole(file=buf, force_terminal=True, width=120, theme=connpy_theme)
|
||||||
|
if msg_type == "debug":
|
||||||
|
c.print(_printer._format_multiline("i", f"[DEBUG] {message}", style="info"))
|
||||||
|
elif msg_type == "success":
|
||||||
|
c.print(_printer._format_multiline("✓", message, style="success"))
|
||||||
|
elif msg_type == "error":
|
||||||
|
c.print(_printer._format_multiline("✗", message, style="error"))
|
||||||
|
else:
|
||||||
|
c.print(str(message))
|
||||||
|
rendered = buf.getvalue()
|
||||||
|
if rendered:
|
||||||
|
# Raw TTY needs \r\n instead of \n
|
||||||
|
rendered = rendered.replace('\n', '\r\n')
|
||||||
|
debug_chunks.append(rendered.encode())
|
||||||
|
else:
|
||||||
|
remote_logger = None
|
||||||
|
|
||||||
|
connect = n._connect(debug=debug, logger=remote_logger)
|
||||||
|
|
||||||
|
# Send debug output to client before checking result (always show the command)
|
||||||
|
for chunk in debug_chunks:
|
||||||
|
yield connpy_pb2.InteractResponse(stdout_data=chunk)
|
||||||
|
|
||||||
if connect != True:
|
if connect != True:
|
||||||
yield connpy_pb2.InteractResponse(success=False, error_message=str(connect))
|
yield connpy_pb2.InteractResponse(success=False, error_message=str(connect))
|
||||||
return
|
return
|
||||||
@@ -708,30 +784,6 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
|
|||||||
# Signal successful connection to the client
|
# Signal successful connection to the client
|
||||||
yield connpy_pb2.InteractResponse(success=True)
|
yield connpy_pb2.InteractResponse(success=True)
|
||||||
|
|
||||||
import threading
|
|
||||||
import queue
|
|
||||||
|
|
||||||
stdin_queue = queue.Queue()
|
|
||||||
running = True
|
|
||||||
|
|
||||||
def read_requests():
|
|
||||||
try:
|
|
||||||
for req in request_iterator:
|
|
||||||
if not running:
|
|
||||||
break
|
|
||||||
if req.cols > 0 and req.rows > 0:
|
|
||||||
try:
|
|
||||||
n.child.setwinsize(req.rows, req.cols)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if req.stdin_data:
|
|
||||||
stdin_queue.put(req.stdin_data)
|
|
||||||
except grpc.RpcError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
t = threading.Thread(target=read_requests, daemon=True)
|
|
||||||
t.start()
|
|
||||||
|
|
||||||
# Set initial window size if provided
|
# Set initial window size if provided
|
||||||
if first_req.cols > 0 and first_req.rows > 0:
|
if first_req.cols > 0 and first_req.rows > 0:
|
||||||
try:
|
try:
|
||||||
@@ -739,32 +791,210 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
try:
|
response_queue = queue.Queue()
|
||||||
while n.child.isalive() and running:
|
remote_stream = RemoteStream(request_iterator, response_queue)
|
||||||
r, _, _ = select.select([n.child.child_fd], [], [], 0.05)
|
|
||||||
if r:
|
|
||||||
try:
|
|
||||||
data = os.read(n.child.child_fd, 4096)
|
|
||||||
if not data:
|
|
||||||
break
|
|
||||||
yield connpy_pb2.InteractResponse(stdout_data=data)
|
|
||||||
except OSError:
|
|
||||||
break
|
|
||||||
|
|
||||||
while not stdin_queue.empty():
|
def run_async_loop():
|
||||||
data = stdin_queue.get_nowait()
|
|
||||||
try:
|
try:
|
||||||
os.write(n.child.child_fd, data)
|
n._setup_interact_environment(debug=debug, logger=None, async_mode=True)
|
||||||
except OSError:
|
def resize_callback(rows, cols):
|
||||||
running = False
|
|
||||||
break
|
|
||||||
finally:
|
|
||||||
running = False
|
|
||||||
try:
|
try:
|
||||||
n.child.terminate(force=True)
|
n.child.setwinsize(rows, cols)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
async def remote_copilot_handler(buffer, node_info, stream, child_fd, cmd_byte_positions=None):
|
||||||
|
import json
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
from ..services.ai_service import AIService
|
||||||
|
|
||||||
|
service = AIService(self.service.config)
|
||||||
|
|
||||||
|
if node_info is None:
|
||||||
|
node_info = {}
|
||||||
|
|
||||||
|
# Calculate real command blocks from history using the central service
|
||||||
|
raw_bytes = n.mylog.getvalue() if hasattr(n, 'mylog') else buffer
|
||||||
|
if not isinstance(raw_bytes, bytes):
|
||||||
|
raw_bytes = str(raw_bytes).encode()
|
||||||
|
|
||||||
|
from connpy.utils import log_cleaner
|
||||||
|
last_line = log_cleaner(raw_bytes.decode(errors='replace')).split('\n')[-1].strip()
|
||||||
|
blocks = service.build_context_blocks(raw_bytes, n.cmd_byte_positions, node_info, last_line=last_line)
|
||||||
|
node_info["context_blocks"] = blocks
|
||||||
|
|
||||||
|
node_info_json = json.dumps(node_info)
|
||||||
|
|
||||||
|
# Convert buffer to string if it's bytes for the preview
|
||||||
|
preview_str = buffer[-200:].decode(errors='replace') if isinstance(buffer, bytes) else str(buffer)[-200:]
|
||||||
|
|
||||||
|
# Generate a unique session ID for this copilot interaction to prevent race conditions
|
||||||
|
import uuid
|
||||||
|
copilot_session_id = str(uuid.uuid4())
|
||||||
|
node_info["session_id"] = copilot_session_id
|
||||||
|
node_info_json = json.dumps(node_info)
|
||||||
|
|
||||||
|
# 1. Send prompt to client
|
||||||
|
response_queue.put(connpy_pb2.InteractResponse(
|
||||||
|
copilot_prompt=True,
|
||||||
|
copilot_buffer_preview=preview_str,
|
||||||
|
copilot_node_info_json=node_info_json
|
||||||
|
))
|
||||||
|
|
||||||
|
while True:
|
||||||
|
# 0. Drain the queue of any stale messages before starting a new interaction
|
||||||
|
while not remote_stream.copilot_queue.empty():
|
||||||
|
try:
|
||||||
|
remote_stream.copilot_queue.get_nowait()
|
||||||
|
except:
|
||||||
|
break
|
||||||
|
|
||||||
|
# 2. Await the question from client via the copilot_queue
|
||||||
|
import threading
|
||||||
|
def preload_ai_deps():
|
||||||
|
try:
|
||||||
|
import litellm
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
threading.Thread(target=preload_ai_deps, daemon=True).start()
|
||||||
|
|
||||||
|
try:
|
||||||
|
req_data = await asyncio.wait_for(remote_stream.copilot_queue.get(), timeout=120)
|
||||||
|
if not req_data: return
|
||||||
|
|
||||||
|
# Validate session ID if provided by client (skip validation if not provided for CLI compatibility)
|
||||||
|
req_session_id = req_data.get("session_id")
|
||||||
|
if req_session_id and req_session_id != copilot_session_id:
|
||||||
|
continue # Ignore stale request from a previous session
|
||||||
|
|
||||||
|
if "question" not in req_data or not req_data["question"] or req_data["question"] == "CANCEL" or req_data.get("action") in ("cancel", "web_cancel"):
|
||||||
|
if req_data.get("action") == "web_cancel":
|
||||||
|
os.write(child_fd, b'\x05')
|
||||||
|
else:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
question = req_data["question"]
|
||||||
|
|
||||||
|
merged_node_info_str = req_data.get("node_info_json", "")
|
||||||
|
if merged_node_info_str:
|
||||||
|
try:
|
||||||
|
merged_node_info = json.loads(merged_node_info_str)
|
||||||
|
node_info.update(merged_node_info)
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
context_buffer = req_data.get("context_buffer", "")
|
||||||
|
if context_buffer.startswith('{"context_start_pos"'):
|
||||||
|
try:
|
||||||
|
parsed = json.loads(context_buffer)
|
||||||
|
start_pos = parsed["context_start_pos"]
|
||||||
|
selected_raw = raw_bytes[start_pos:]
|
||||||
|
context_buffer = n._logclean(selected_raw.decode(errors='replace'), var=True)
|
||||||
|
except Exception:
|
||||||
|
context_buffer = buffer
|
||||||
|
elif not context_buffer:
|
||||||
|
context_buffer = buffer
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
|
||||||
|
# 3. Call AI Service with streaming
|
||||||
|
def chunk_callback(chunk_text):
|
||||||
|
if chunk_text:
|
||||||
|
response_queue.put(connpy_pb2.InteractResponse(
|
||||||
|
copilot_stream_chunk=chunk_text
|
||||||
|
))
|
||||||
|
|
||||||
|
# Create a clean version of node_info for the AI to save tokens and match local CLI behavior
|
||||||
|
ai_node_info = {k: v for k, v in node_info.items() if k not in ("context_blocks", "full_buffer")}
|
||||||
|
|
||||||
|
ai_task = asyncio.create_task(service.aask_copilot(context_buffer, question, ai_node_info, chunk_callback=chunk_callback))
|
||||||
|
wait_action_task = asyncio.create_task(remote_stream.copilot_queue.get())
|
||||||
|
|
||||||
|
done, pending = await asyncio.wait(
|
||||||
|
[ai_task, wait_action_task],
|
||||||
|
return_when=asyncio.FIRST_COMPLETED
|
||||||
|
)
|
||||||
|
|
||||||
|
if wait_action_task in done:
|
||||||
|
req_data = wait_action_task.result()
|
||||||
|
ai_task.cancel()
|
||||||
|
if req_data.get("action") in ("cancel", "web_cancel") or req_data.get("question") == "CANCEL":
|
||||||
|
if req_data.get("action") == "web_cancel":
|
||||||
|
os.write(child_fd, b'\x05')
|
||||||
|
else:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
continue # Loop back instead of returning to keep session alive
|
||||||
|
else:
|
||||||
|
wait_action_task.cancel()
|
||||||
|
result = ai_task.result()
|
||||||
|
if not result:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
|
||||||
|
# 4. Send response back to client
|
||||||
|
response_queue.put(connpy_pb2.InteractResponse(
|
||||||
|
copilot_response_json=json.dumps(result)
|
||||||
|
))
|
||||||
|
|
||||||
|
# 5. Wait for user action
|
||||||
|
try:
|
||||||
|
action_data = await asyncio.wait_for(remote_stream.copilot_queue.get(), timeout=60)
|
||||||
|
if not action_data: return
|
||||||
|
action = action_data.get("action", "cancel")
|
||||||
|
|
||||||
|
if action == "continue":
|
||||||
|
continue # Loop back for next question
|
||||||
|
|
||||||
|
if action in ("cancel", "web_cancel"):
|
||||||
|
if action == "web_cancel":
|
||||||
|
os.write(child_fd, b'\x05')
|
||||||
|
else:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
|
||||||
|
def on_inject(cmd):
|
||||||
|
response_queue.put(connpy_pb2.InteractResponse(copilot_injected_command=cmd))
|
||||||
|
|
||||||
|
if action == "send_all":
|
||||||
|
commands = result.get("commands", [])
|
||||||
|
await n.inject_commands(commands, child_fd, on_inject=on_inject)
|
||||||
|
return
|
||||||
|
elif action.startswith("custom:"):
|
||||||
|
custom_cmds_raw = action[7:]
|
||||||
|
custom_cmds = [cmd.strip() for cmd in custom_cmds_raw.split('\n') if cmd.strip()]
|
||||||
|
await n.inject_commands(custom_cmds, child_fd, on_inject=on_inject)
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
os.write(child_fd, b'\x15\r')
|
||||||
|
return
|
||||||
|
|
||||||
|
asyncio.run(n._async_interact_loop(remote_stream, resize_callback, copilot_handler=remote_copilot_handler))
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
n._teardown_interact_environment()
|
||||||
|
response_queue.put(None) # Signal EOF
|
||||||
|
|
||||||
|
t_loop = threading.Thread(target=run_async_loop, daemon=True)
|
||||||
|
t_loop.start()
|
||||||
|
def response_generator():
|
||||||
|
while True:
|
||||||
|
data = response_queue.get()
|
||||||
|
if data is None:
|
||||||
|
if self.server_debug:
|
||||||
|
self.server_console.print(f"[debug][DEBUG][/debug] gRPC interact_node session closed for: [bold cyan]{unique_id}[/bold cyan]")
|
||||||
|
break
|
||||||
|
if isinstance(data, connpy_pb2.InteractResponse):
|
||||||
|
yield data
|
||||||
|
else:
|
||||||
|
yield connpy_pb2.InteractResponse(stdout_data=data)
|
||||||
|
yield from response_generator()
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def list_nodes(self, request, context):
|
def list_nodes(self, request, context):
|
||||||
f = request.filter_str if request.filter_str else None
|
f = request.filter_str if request.filter_str else None
|
||||||
@@ -1330,7 +1560,7 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.grpc_layer.stubs API documentation</title>
|
<title>connpy.grpc_layer.stubs API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -104,7 +104,6 @@ el.replaceWith(d);
|
|||||||
import queue
|
import queue
|
||||||
from rich.prompt import Prompt
|
from rich.prompt import Prompt
|
||||||
from rich.text import Text
|
from rich.text import Text
|
||||||
from rich.live import Live
|
|
||||||
from rich.panel import Panel
|
from rich.panel import Panel
|
||||||
from rich.markdown import Markdown
|
from rich.markdown import Markdown
|
||||||
|
|
||||||
@@ -135,7 +134,7 @@ el.replaceWith(d);
|
|||||||
responses = self.stub.ask(request_generator())
|
responses = self.stub.ask(request_generator())
|
||||||
|
|
||||||
full_content = ""
|
full_content = ""
|
||||||
live_display = None
|
header_printed = False
|
||||||
final_result = {"response": "", "chat_history": []}
|
final_result = {"response": "", "chat_history": []}
|
||||||
|
|
||||||
# Background thread to pull responses from gRPC into a local queue
|
# Background thread to pull responses from gRPC into a local queue
|
||||||
@@ -182,7 +181,6 @@ el.replaceWith(d);
|
|||||||
if response.status_update:
|
if response.status_update:
|
||||||
if response.requires_confirmation:
|
if response.requires_confirmation:
|
||||||
if status: status.stop()
|
if status: status.stop()
|
||||||
if live_display: live_display.stop()
|
|
||||||
|
|
||||||
# Show prompt and wait for answer
|
# Show prompt and wait for answer
|
||||||
prompt_text = Text.from_ansi(response.status_update)
|
prompt_text = Text.from_ansi(response.status_update)
|
||||||
@@ -191,7 +189,6 @@ el.replaceWith(d);
|
|||||||
if status:
|
if status:
|
||||||
status.update("[ai_status]Agent: Resuming...")
|
status.update("[ai_status]Agent: Resuming...")
|
||||||
status.start()
|
status.start()
|
||||||
if live_display: live_display.start()
|
|
||||||
|
|
||||||
req_queue.put(connpy_pb2.AskRequest(confirmation_answer=ans))
|
req_queue.put(connpy_pb2.AskRequest(confirmation_answer=ans))
|
||||||
continue
|
continue
|
||||||
@@ -202,41 +199,71 @@ el.replaceWith(d);
|
|||||||
|
|
||||||
if response.debug_message:
|
if response.debug_message:
|
||||||
if debug:
|
if debug:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
printer.console.print(Text.from_ansi(response.debug_message))
|
printer.console.print(Text.from_ansi(response.debug_message))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if response.important_message:
|
if response.important_message:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
printer.console.print(Text.from_ansi(response.important_message))
|
printer.console.print(Text.from_ansi(response.important_message))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if not response.is_final:
|
if not response.is_final:
|
||||||
full_content += response.text_chunk
|
if response.text_chunk:
|
||||||
|
if not header_printed:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
|
||||||
if not live_display and not debug:
|
from rich.console import Console as RichConsole
|
||||||
if status: status.stop()
|
from rich.rule import Rule
|
||||||
live_display = Live(
|
from ..printer import connpy_theme, get_original_stdout, IncrementalMarkdownParser
|
||||||
Panel(Markdown(full_content), title="AI Assistant", expand=False),
|
stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
|
||||||
console=printer.console,
|
|
||||||
refresh_per_second=8,
|
# Print header on first chunk
|
||||||
transient=False
|
stable_console.print(Rule("[bold engineer]Network Engineer[/bold engineer]", style="engineer"))
|
||||||
)
|
header_printed = True
|
||||||
live_display.start()
|
|
||||||
elif live_display:
|
# Initialize parser
|
||||||
live_display.update(Panel(Markdown(full_content), title="AI Assistant", expand=False))
|
md_parser = IncrementalMarkdownParser(console=stable_console)
|
||||||
|
|
||||||
|
full_content += response.text_chunk
|
||||||
|
md_parser.feed(response.text_chunk)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if response.is_final:
|
if response.is_final:
|
||||||
|
if header_printed:
|
||||||
|
from rich.rule import Rule
|
||||||
|
md_parser.flush()
|
||||||
|
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
|
||||||
final_result = from_struct(response.full_result)
|
final_result = from_struct(response.full_result)
|
||||||
responder = final_result.get("responder", "engineer")
|
responder = final_result.get("responder", "engineer")
|
||||||
alias = "architect" if responder == "architect" else "engineer"
|
alias = "architect" if responder == "architect" else "engineer"
|
||||||
role_label = "Network Architect" if responder == "architect" else "Network Engineer"
|
role_label = "Network Architect" if responder == "architect" else "Network Engineer"
|
||||||
title = f"[bold {alias}]{role_label}[/bold {alias}]"
|
title = f"[bold {alias}]{role_label}[/bold {alias}]"
|
||||||
|
|
||||||
if live_display:
|
if header_printed:
|
||||||
live_display.update(Panel(Markdown(full_content), title=title, border_style=alias, expand=False))
|
from rich.console import Console as RichConsole
|
||||||
live_display.stop()
|
from ..printer import connpy_theme, get_original_stdout
|
||||||
elif full_content:
|
stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
|
||||||
printer.console.print(Panel(Markdown(full_content), title=title, border_style=alias, expand=False))
|
stable_console.print(Rule(style=alias))
|
||||||
|
elif not full_content and final_result.get("response"):
|
||||||
|
# If nothing streamed but we have response (e.g. error or direct guide)
|
||||||
|
printer.console.print(Panel(Markdown(final_result["response"]), title=title, border_style=alias, expand=False))
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Check if it was a gRPC error that we should let handle_errors catch
|
# Check if it was a gRPC error that we should let handle_errors catch
|
||||||
@@ -268,6 +295,17 @@ el.replaceWith(d);
|
|||||||
req = connpy_pb2.ProviderRequest(provider=provider, model=model or "", api_key=api_key or "")
|
req = connpy_pb2.ProviderRequest(provider=provider, model=model or "", api_key=api_key or "")
|
||||||
self.stub.configure_provider(req)
|
self.stub.configure_provider(req)
|
||||||
|
|
||||||
|
@handle_errors
|
||||||
|
def configure_mcp(self, name, url=None, enabled=True, auto_load_on_os=None, remove=False):
|
||||||
|
req = connpy_pb2.MCPRequest(
|
||||||
|
name=name,
|
||||||
|
url=url or "",
|
||||||
|
enabled=enabled,
|
||||||
|
auto_load_on_os=auto_load_on_os or "",
|
||||||
|
remove=remove
|
||||||
|
)
|
||||||
|
self.stub.configure_mcp(req)
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def load_session_data(self, session_id):
|
def load_session_data(self, session_id):
|
||||||
return from_struct(self.stub.load_session_data(connpy_pb2.StringRequest(value=session_id)).data)</code></pre>
|
return from_struct(self.stub.load_session_data(connpy_pb2.StringRequest(value=session_id)).data)</code></pre>
|
||||||
@@ -288,7 +326,6 @@ def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debu
|
|||||||
import queue
|
import queue
|
||||||
from rich.prompt import Prompt
|
from rich.prompt import Prompt
|
||||||
from rich.text import Text
|
from rich.text import Text
|
||||||
from rich.live import Live
|
|
||||||
from rich.panel import Panel
|
from rich.panel import Panel
|
||||||
from rich.markdown import Markdown
|
from rich.markdown import Markdown
|
||||||
|
|
||||||
@@ -319,7 +356,7 @@ def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debu
|
|||||||
responses = self.stub.ask(request_generator())
|
responses = self.stub.ask(request_generator())
|
||||||
|
|
||||||
full_content = ""
|
full_content = ""
|
||||||
live_display = None
|
header_printed = False
|
||||||
final_result = {"response": "", "chat_history": []}
|
final_result = {"response": "", "chat_history": []}
|
||||||
|
|
||||||
# Background thread to pull responses from gRPC into a local queue
|
# Background thread to pull responses from gRPC into a local queue
|
||||||
@@ -366,7 +403,6 @@ def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debu
|
|||||||
if response.status_update:
|
if response.status_update:
|
||||||
if response.requires_confirmation:
|
if response.requires_confirmation:
|
||||||
if status: status.stop()
|
if status: status.stop()
|
||||||
if live_display: live_display.stop()
|
|
||||||
|
|
||||||
# Show prompt and wait for answer
|
# Show prompt and wait for answer
|
||||||
prompt_text = Text.from_ansi(response.status_update)
|
prompt_text = Text.from_ansi(response.status_update)
|
||||||
@@ -375,7 +411,6 @@ def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debu
|
|||||||
if status:
|
if status:
|
||||||
status.update("[ai_status]Agent: Resuming...")
|
status.update("[ai_status]Agent: Resuming...")
|
||||||
status.start()
|
status.start()
|
||||||
if live_display: live_display.start()
|
|
||||||
|
|
||||||
req_queue.put(connpy_pb2.AskRequest(confirmation_answer=ans))
|
req_queue.put(connpy_pb2.AskRequest(confirmation_answer=ans))
|
||||||
continue
|
continue
|
||||||
@@ -386,41 +421,71 @@ def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debu
|
|||||||
|
|
||||||
if response.debug_message:
|
if response.debug_message:
|
||||||
if debug:
|
if debug:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
printer.console.print(Text.from_ansi(response.debug_message))
|
printer.console.print(Text.from_ansi(response.debug_message))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if response.important_message:
|
if response.important_message:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
printer.console.print(Text.from_ansi(response.important_message))
|
printer.console.print(Text.from_ansi(response.important_message))
|
||||||
|
if status:
|
||||||
|
try: status.start()
|
||||||
|
except: pass
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if not response.is_final:
|
if not response.is_final:
|
||||||
full_content += response.text_chunk
|
if response.text_chunk:
|
||||||
|
if not header_printed:
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
|
||||||
if not live_display and not debug:
|
from rich.console import Console as RichConsole
|
||||||
if status: status.stop()
|
from rich.rule import Rule
|
||||||
live_display = Live(
|
from ..printer import connpy_theme, get_original_stdout, IncrementalMarkdownParser
|
||||||
Panel(Markdown(full_content), title="AI Assistant", expand=False),
|
stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
|
||||||
console=printer.console,
|
|
||||||
refresh_per_second=8,
|
# Print header on first chunk
|
||||||
transient=False
|
stable_console.print(Rule("[bold engineer]Network Engineer[/bold engineer]", style="engineer"))
|
||||||
)
|
header_printed = True
|
||||||
live_display.start()
|
|
||||||
elif live_display:
|
# Initialize parser
|
||||||
live_display.update(Panel(Markdown(full_content), title="AI Assistant", expand=False))
|
md_parser = IncrementalMarkdownParser(console=stable_console)
|
||||||
|
|
||||||
|
full_content += response.text_chunk
|
||||||
|
md_parser.feed(response.text_chunk)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if response.is_final:
|
if response.is_final:
|
||||||
|
if header_printed:
|
||||||
|
from rich.rule import Rule
|
||||||
|
md_parser.flush()
|
||||||
|
|
||||||
|
if status:
|
||||||
|
try: status.stop()
|
||||||
|
except: pass
|
||||||
|
|
||||||
final_result = from_struct(response.full_result)
|
final_result = from_struct(response.full_result)
|
||||||
responder = final_result.get("responder", "engineer")
|
responder = final_result.get("responder", "engineer")
|
||||||
alias = "architect" if responder == "architect" else "engineer"
|
alias = "architect" if responder == "architect" else "engineer"
|
||||||
role_label = "Network Architect" if responder == "architect" else "Network Engineer"
|
role_label = "Network Architect" if responder == "architect" else "Network Engineer"
|
||||||
title = f"[bold {alias}]{role_label}[/bold {alias}]"
|
title = f"[bold {alias}]{role_label}[/bold {alias}]"
|
||||||
|
|
||||||
if live_display:
|
if header_printed:
|
||||||
live_display.update(Panel(Markdown(full_content), title=title, border_style=alias, expand=False))
|
from rich.console import Console as RichConsole
|
||||||
live_display.stop()
|
from ..printer import connpy_theme, get_original_stdout
|
||||||
elif full_content:
|
stable_console = RichConsole(theme=connpy_theme, file=get_original_stdout())
|
||||||
printer.console.print(Panel(Markdown(full_content), title=title, border_style=alias, expand=False))
|
stable_console.print(Rule(style=alias))
|
||||||
|
elif not full_content and final_result.get("response"):
|
||||||
|
# If nothing streamed but we have response (e.g. error or direct guide)
|
||||||
|
printer.console.print(Panel(Markdown(final_result["response"]), title=title, border_style=alias, expand=False))
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Check if it was a gRPC error that we should let handle_errors catch
|
# Check if it was a gRPC error that we should let handle_errors catch
|
||||||
@@ -437,6 +502,27 @@ def ask(self, input_text, dryrun=False, chat_history=None, session_id=None, debu
|
|||||||
</details>
|
</details>
|
||||||
<div class="desc"></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
|
<dt id="connpy.grpc_layer.stubs.AIStub.configure_mcp"><code class="name flex">
|
||||||
|
<span>def <span class="ident">configure_mcp</span></span>(<span>self, name, url=None, enabled=True, auto_load_on_os=None, remove=False)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">@handle_errors
|
||||||
|
def configure_mcp(self, name, url=None, enabled=True, auto_load_on_os=None, remove=False):
|
||||||
|
req = connpy_pb2.MCPRequest(
|
||||||
|
name=name,
|
||||||
|
url=url or "",
|
||||||
|
enabled=enabled,
|
||||||
|
auto_load_on_os=auto_load_on_os or "",
|
||||||
|
remove=remove
|
||||||
|
)
|
||||||
|
self.stub.configure_mcp(req)</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
<dt id="connpy.grpc_layer.stubs.AIStub.configure_provider"><code class="name flex">
|
<dt id="connpy.grpc_layer.stubs.AIStub.configure_provider"><code class="name flex">
|
||||||
<span>def <span class="ident">configure_provider</span></span>(<span>self, provider, model=None, api_key=None)</span>
|
<span>def <span class="ident">configure_provider</span></span>(<span>self, provider, model=None, api_key=None)</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
@@ -642,9 +728,9 @@ def update_setting(self, key, value):
|
|||||||
folder=folder or "",
|
folder=folder or "",
|
||||||
prompt=prompt or "",
|
prompt=prompt or "",
|
||||||
parallel=parallel,
|
parallel=parallel,
|
||||||
|
timeout=timeout,
|
||||||
|
name=kwargs.get("name", "")
|
||||||
)
|
)
|
||||||
# Note: 'timeout', 'on_node_complete', and 'logger' are currently not
|
|
||||||
# sent over gRPC in the current proto definition.
|
|
||||||
if variables is not None:
|
if variables is not None:
|
||||||
req.vars.CopyFrom(to_struct(variables))
|
req.vars.CopyFrom(to_struct(variables))
|
||||||
|
|
||||||
@@ -654,7 +740,10 @@ def update_setting(self, key, value):
|
|||||||
for response in self.stub.run_commands(req):
|
for response in self.stub.run_commands(req):
|
||||||
if on_complete:
|
if on_complete:
|
||||||
on_complete(response.unique_id, response.output, response.status)
|
on_complete(response.unique_id, response.output, response.status)
|
||||||
final_results[response.unique_id] = response.output
|
final_results[response.unique_id] = {
|
||||||
|
"output": response.output,
|
||||||
|
"status": response.status
|
||||||
|
}
|
||||||
|
|
||||||
return final_results
|
return final_results
|
||||||
|
|
||||||
@@ -664,10 +753,12 @@ def update_setting(self, key, value):
|
|||||||
req = connpy_pb2.TestRequest(
|
req = connpy_pb2.TestRequest(
|
||||||
nodes=nodes_list,
|
nodes=nodes_list,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
expected=expected,
|
expected=expected if isinstance(expected, list) else [expected],
|
||||||
folder=kwargs.get("folder", ""),
|
folder=kwargs.get("folder", ""),
|
||||||
prompt=prompt or "",
|
prompt=prompt or "",
|
||||||
parallel=parallel,
|
parallel=parallel,
|
||||||
|
timeout=timeout,
|
||||||
|
name=kwargs.get("name", "")
|
||||||
)
|
)
|
||||||
if variables is not None:
|
if variables is not None:
|
||||||
req.vars.CopyFrom(to_struct(variables))
|
req.vars.CopyFrom(to_struct(variables))
|
||||||
@@ -728,9 +819,9 @@ def run_commands(self, nodes_filter, commands, variables=None, parallel=10, time
|
|||||||
folder=folder or "",
|
folder=folder or "",
|
||||||
prompt=prompt or "",
|
prompt=prompt or "",
|
||||||
parallel=parallel,
|
parallel=parallel,
|
||||||
|
timeout=timeout,
|
||||||
|
name=kwargs.get("name", "")
|
||||||
)
|
)
|
||||||
# Note: 'timeout', 'on_node_complete', and 'logger' are currently not
|
|
||||||
# sent over gRPC in the current proto definition.
|
|
||||||
if variables is not None:
|
if variables is not None:
|
||||||
req.vars.CopyFrom(to_struct(variables))
|
req.vars.CopyFrom(to_struct(variables))
|
||||||
|
|
||||||
@@ -740,7 +831,10 @@ def run_commands(self, nodes_filter, commands, variables=None, parallel=10, time
|
|||||||
for response in self.stub.run_commands(req):
|
for response in self.stub.run_commands(req):
|
||||||
if on_complete:
|
if on_complete:
|
||||||
on_complete(response.unique_id, response.output, response.status)
|
on_complete(response.unique_id, response.output, response.status)
|
||||||
final_results[response.unique_id] = response.output
|
final_results[response.unique_id] = {
|
||||||
|
"output": response.output,
|
||||||
|
"status": response.status
|
||||||
|
}
|
||||||
|
|
||||||
return final_results</code></pre>
|
return final_results</code></pre>
|
||||||
</details>
|
</details>
|
||||||
@@ -775,10 +869,12 @@ def test_commands(self, nodes_filter, commands, expected, variables=None, parall
|
|||||||
req = connpy_pb2.TestRequest(
|
req = connpy_pb2.TestRequest(
|
||||||
nodes=nodes_list,
|
nodes=nodes_list,
|
||||||
commands=commands,
|
commands=commands,
|
||||||
expected=expected,
|
expected=expected if isinstance(expected, list) else [expected],
|
||||||
folder=kwargs.get("folder", ""),
|
folder=kwargs.get("folder", ""),
|
||||||
prompt=prompt or "",
|
prompt=prompt or "",
|
||||||
parallel=parallel,
|
parallel=parallel,
|
||||||
|
timeout=timeout,
|
||||||
|
name=kwargs.get("name", "")
|
||||||
)
|
)
|
||||||
if variables is not None:
|
if variables is not None:
|
||||||
req.vars.CopyFrom(to_struct(variables))
|
req.vars.CopyFrom(to_struct(variables))
|
||||||
@@ -896,15 +992,100 @@ def set_reserved_names(self, names):
|
|||||||
self.remote_host = remote_host
|
self.remote_host = remote_host
|
||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
|
def _handle_remote_copilot(self, res, request_queue, response_queue, client_buffer_bytes, pause_generator, resume_generator, old_tty):
|
||||||
|
import json, asyncio, termios, sys, tty, queue
|
||||||
|
from ..core import copilot_terminal_mode
|
||||||
|
from . import connpy_pb2
|
||||||
|
|
||||||
|
pause_generator()
|
||||||
|
|
||||||
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
|
|
||||||
|
node_info = json.loads(res.copilot_node_info_json) if res.copilot_node_info_json else {}
|
||||||
|
blocks = node_info.get("context_blocks", [])
|
||||||
|
|
||||||
|
interface = CopilotInterface(
|
||||||
|
self.config,
|
||||||
|
history=getattr(self, 'copilot_history', None),
|
||||||
|
session_state=getattr(self, 'copilot_state', None)
|
||||||
|
)
|
||||||
|
self.copilot_history = interface.history
|
||||||
|
self.copilot_state = interface.session_state
|
||||||
|
|
||||||
|
async def on_ai_call_remote(active_buffer, question, chunk_callback, merged_node_info):
|
||||||
|
# Send request to server
|
||||||
|
request_queue.put(connpy_pb2.InteractRequest(
|
||||||
|
copilot_question=question,
|
||||||
|
copilot_context_buffer=active_buffer,
|
||||||
|
copilot_node_info_json=json.dumps(merged_node_info)
|
||||||
|
))
|
||||||
|
# Wait for chunks from server
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
chunk_res = response_queue.get(timeout=0.1)
|
||||||
|
if chunk_res is None: return {"error": "Server disconnected"}
|
||||||
|
if chunk_res.copilot_stream_chunk:
|
||||||
|
chunk_callback(chunk_res.copilot_stream_chunk)
|
||||||
|
elif chunk_res.copilot_response_json:
|
||||||
|
return json.loads(chunk_res.copilot_response_json)
|
||||||
|
except queue.Empty:
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
|
||||||
|
# Wrap in async loop
|
||||||
|
async def run_remote_copilot():
|
||||||
|
while True:
|
||||||
|
action, commands, custom_cmd = await interface.run_session(
|
||||||
|
raw_bytes=bytes(client_buffer_bytes),
|
||||||
|
node_info=node_info,
|
||||||
|
on_ai_call=on_ai_call_remote,
|
||||||
|
blocks=blocks
|
||||||
|
)
|
||||||
|
|
||||||
|
if action == "continue":
|
||||||
|
# Send continue signal to server to loop back for another question
|
||||||
|
request_queue.put(connpy_pb2.InteractRequest(copilot_action="continue"))
|
||||||
|
continue
|
||||||
|
|
||||||
|
return action, commands, custom_cmd
|
||||||
|
|
||||||
|
with copilot_terminal_mode():
|
||||||
|
action, commands, custom_cmd = asyncio.run(run_remote_copilot())
|
||||||
|
|
||||||
|
print("\033[2m Returning to session...\033[0m", flush=True)
|
||||||
|
# Prepare final action for server
|
||||||
|
action_sent = "cancel"
|
||||||
|
if action == "send_all" and commands:
|
||||||
|
# In remote mode, send the selected commands as a custom block
|
||||||
|
# so the server executes exactly what the user picked (e.g., selection '1')
|
||||||
|
action_sent = f"custom:{chr(10).join(commands)}"
|
||||||
|
elif action == "custom" and custom_cmd:
|
||||||
|
action_sent = f"custom:{chr(10).join(custom_cmd)}"
|
||||||
|
request_queue.put(connpy_pb2.InteractRequest(copilot_action=action_sent))
|
||||||
|
resume_generator()
|
||||||
|
tty.setraw(sys.stdin.fileno())
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
|
def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
|
||||||
import sys
|
import sys
|
||||||
import select
|
import select
|
||||||
import tty
|
import tty
|
||||||
import termios
|
import termios
|
||||||
|
import queue
|
||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
|
request_queue = queue.Queue()
|
||||||
|
client_buffer_bytes = bytearray()
|
||||||
|
pause_stdin = [False]
|
||||||
|
wake_r, wake_w = os.pipe()
|
||||||
|
|
||||||
|
def pause_generator():
|
||||||
|
pause_stdin[0] = True
|
||||||
|
os.write(wake_w, b'\x00')
|
||||||
|
|
||||||
|
def resume_generator():
|
||||||
|
pause_stdin[0] = False
|
||||||
|
|
||||||
def request_generator():
|
def request_generator():
|
||||||
cols, rows = 80, 24
|
cols, rows = 80, 24
|
||||||
try:
|
try:
|
||||||
@@ -918,8 +1099,25 @@ def set_reserved_names(self, names):
|
|||||||
)
|
)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
r, _, _ = select.select([sys.stdin.fileno()], [], [])
|
try:
|
||||||
if r:
|
while True:
|
||||||
|
req = request_queue.get_nowait()
|
||||||
|
if req is None:
|
||||||
|
return
|
||||||
|
yield req
|
||||||
|
except queue.Empty:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if pause_stdin[0]:
|
||||||
|
import time
|
||||||
|
time.sleep(0.05)
|
||||||
|
continue
|
||||||
|
|
||||||
|
r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
|
||||||
|
if wake_r in r:
|
||||||
|
os.read(wake_r, 1)
|
||||||
|
continue
|
||||||
|
if sys.stdin.fileno() in r and not pause_stdin[0]:
|
||||||
try:
|
try:
|
||||||
data = os.read(sys.stdin.fileno(), 1024)
|
data = os.read(sys.stdin.fileno(), 1024)
|
||||||
if not data:
|
if not data:
|
||||||
@@ -941,30 +1139,74 @@ def set_reserved_names(self, names):
|
|||||||
|
|
||||||
old_tty = termios.tcgetattr(sys.stdin)
|
old_tty = termios.tcgetattr(sys.stdin)
|
||||||
try:
|
try:
|
||||||
|
import time
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
response_iterator = self.stub.interact_node(request_generator())
|
response_iterator = self.stub.interact_node(request_generator())
|
||||||
|
|
||||||
# First response is connection status
|
import queue
|
||||||
|
response_queue = queue.Queue()
|
||||||
|
|
||||||
|
def response_consumer():
|
||||||
try:
|
try:
|
||||||
first_res = next(response_iterator)
|
for r in response_iterator:
|
||||||
if first_res.success:
|
response_queue.put(r)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
response_queue.put(None)
|
||||||
|
|
||||||
|
t_consumer = threading.Thread(target=response_consumer, daemon=True)
|
||||||
|
t_consumer.start()
|
||||||
|
|
||||||
|
# First phase: Wait for connection status, print early data
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
return
|
||||||
|
if res.stdout_data:
|
||||||
|
data = res.stdout_data
|
||||||
|
if debug:
|
||||||
|
data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
|
||||||
|
os.write(sys.stdout.fileno(), data)
|
||||||
|
|
||||||
|
if res.success:
|
||||||
# Connection established on server, show success message
|
# Connection established on server, show success message
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.success(conn_msg)
|
printer.success(conn_msg)
|
||||||
|
pause_stdin[0] = False
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
else:
|
break
|
||||||
|
|
||||||
|
if res.error_message:
|
||||||
# Connection failed on server
|
# Connection failed on server
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.error(f"Connection failed: {first_res.error_message}")
|
printer.error(f"Connection failed: {res.error_message}")
|
||||||
return
|
return
|
||||||
except StopIteration:
|
except queue.Empty:
|
||||||
return
|
return
|
||||||
|
|
||||||
for res in response_iterator:
|
# Second phase: Stream active session
|
||||||
|
# Clear screen filter is only applied before success (Phase 1).
|
||||||
|
# Once the user has a prompt, Ctrl+L must work normally.
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
break
|
||||||
|
if res.copilot_prompt:
|
||||||
|
self._handle_remote_copilot(
|
||||||
|
res, request_queue, response_queue,
|
||||||
|
client_buffer_bytes,
|
||||||
|
pause_generator, resume_generator, old_tty
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
if res.stdout_data:
|
if res.stdout_data:
|
||||||
os.write(sys.stdout.fileno(), res.stdout_data)
|
os.write(sys.stdout.fileno(), res.stdout_data)
|
||||||
|
client_buffer_bytes.extend(res.stdout_data)
|
||||||
finally:
|
finally:
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
|
os.close(wake_r)
|
||||||
|
os.close(wake_w)
|
||||||
|
|
||||||
@handle_errors
|
@handle_errors
|
||||||
def connect_dynamic(self, connection_params, debug=False):
|
def connect_dynamic(self, connection_params, debug=False):
|
||||||
@@ -972,10 +1214,22 @@ def set_reserved_names(self, names):
|
|||||||
import select
|
import select
|
||||||
import tty
|
import tty
|
||||||
import termios
|
import termios
|
||||||
|
import queue
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
|
|
||||||
params_json = json.dumps(connection_params)
|
params_json = json.dumps(connection_params)
|
||||||
|
request_queue = queue.Queue()
|
||||||
|
client_buffer_bytes = bytearray()
|
||||||
|
pause_stdin = [False]
|
||||||
|
wake_r, wake_w = os.pipe()
|
||||||
|
|
||||||
|
def pause_generator():
|
||||||
|
pause_stdin[0] = True
|
||||||
|
os.write(wake_w, b'\x00')
|
||||||
|
|
||||||
|
def resume_generator():
|
||||||
|
pause_stdin[0] = False
|
||||||
|
|
||||||
def request_generator():
|
def request_generator():
|
||||||
cols, rows = 80, 24
|
cols, rows = 80, 24
|
||||||
@@ -991,8 +1245,25 @@ def set_reserved_names(self, names):
|
|||||||
)
|
)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
r, _, _ = select.select([sys.stdin.fileno()], [], [])
|
try:
|
||||||
if r:
|
while True:
|
||||||
|
req = request_queue.get_nowait()
|
||||||
|
if req is None:
|
||||||
|
return
|
||||||
|
yield req
|
||||||
|
except queue.Empty:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if pause_stdin[0]:
|
||||||
|
import time
|
||||||
|
time.sleep(0.05)
|
||||||
|
continue
|
||||||
|
|
||||||
|
r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
|
||||||
|
if wake_r in r:
|
||||||
|
os.read(wake_r, 1)
|
||||||
|
continue
|
||||||
|
if sys.stdin.fileno() in r and not pause_stdin[0]:
|
||||||
try:
|
try:
|
||||||
data = os.read(sys.stdin.fileno(), 1024)
|
data = os.read(sys.stdin.fileno(), 1024)
|
||||||
if not data:
|
if not data:
|
||||||
@@ -1015,30 +1286,72 @@ def set_reserved_names(self, names):
|
|||||||
|
|
||||||
old_tty = termios.tcgetattr(sys.stdin)
|
old_tty = termios.tcgetattr(sys.stdin)
|
||||||
try:
|
try:
|
||||||
|
import time
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
response_iterator = self.stub.interact_node(request_generator())
|
response_iterator = self.stub.interact_node(request_generator())
|
||||||
|
|
||||||
# First response is connection status
|
import queue
|
||||||
|
response_queue = queue.Queue()
|
||||||
|
|
||||||
|
def response_consumer():
|
||||||
try:
|
try:
|
||||||
first_res = next(response_iterator)
|
for r in response_iterator:
|
||||||
if first_res.success:
|
response_queue.put(r)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
response_queue.put(None)
|
||||||
|
|
||||||
|
t_consumer = threading.Thread(target=response_consumer, daemon=True)
|
||||||
|
t_consumer.start()
|
||||||
|
|
||||||
|
# First phase: Wait for connection status, print early data
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
return
|
||||||
|
if res.stdout_data:
|
||||||
|
data = res.stdout_data
|
||||||
|
if debug:
|
||||||
|
data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
|
||||||
|
os.write(sys.stdout.fileno(), data)
|
||||||
|
|
||||||
|
if res.success:
|
||||||
# Connection established on server, show success message
|
# Connection established on server, show success message
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.success(conn_msg)
|
printer.success(conn_msg)
|
||||||
|
pause_stdin[0] = False
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
else:
|
break
|
||||||
|
|
||||||
|
if res.error_message:
|
||||||
# Connection failed on server
|
# Connection failed on server
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.error(f"Connection failed: {first_res.error_message}")
|
printer.error(f"Connection failed: {res.error_message}")
|
||||||
return
|
return
|
||||||
except StopIteration:
|
except queue.Empty:
|
||||||
return
|
return
|
||||||
|
|
||||||
for res in response_iterator:
|
# Second phase: Stream active session
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
break
|
||||||
|
if res.copilot_prompt:
|
||||||
|
self._handle_remote_copilot(
|
||||||
|
res, request_queue, response_queue,
|
||||||
|
client_buffer_bytes,
|
||||||
|
pause_generator, resume_generator, old_tty
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
if res.stdout_data:
|
if res.stdout_data:
|
||||||
os.write(sys.stdout.fileno(), res.stdout_data)
|
os.write(sys.stdout.fileno(), res.stdout_data)
|
||||||
|
client_buffer_bytes.extend(res.stdout_data)
|
||||||
finally:
|
finally:
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
|
os.close(wake_r)
|
||||||
|
os.close(wake_w)
|
||||||
|
|
||||||
@MethodHook
|
@MethodHook
|
||||||
@handle_errors
|
@handle_errors
|
||||||
@@ -1192,10 +1505,22 @@ def connect_dynamic(self, connection_params, debug=False):
|
|||||||
import select
|
import select
|
||||||
import tty
|
import tty
|
||||||
import termios
|
import termios
|
||||||
|
import queue
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
|
|
||||||
params_json = json.dumps(connection_params)
|
params_json = json.dumps(connection_params)
|
||||||
|
request_queue = queue.Queue()
|
||||||
|
client_buffer_bytes = bytearray()
|
||||||
|
pause_stdin = [False]
|
||||||
|
wake_r, wake_w = os.pipe()
|
||||||
|
|
||||||
|
def pause_generator():
|
||||||
|
pause_stdin[0] = True
|
||||||
|
os.write(wake_w, b'\x00')
|
||||||
|
|
||||||
|
def resume_generator():
|
||||||
|
pause_stdin[0] = False
|
||||||
|
|
||||||
def request_generator():
|
def request_generator():
|
||||||
cols, rows = 80, 24
|
cols, rows = 80, 24
|
||||||
@@ -1211,8 +1536,25 @@ def connect_dynamic(self, connection_params, debug=False):
|
|||||||
)
|
)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
r, _, _ = select.select([sys.stdin.fileno()], [], [])
|
try:
|
||||||
if r:
|
while True:
|
||||||
|
req = request_queue.get_nowait()
|
||||||
|
if req is None:
|
||||||
|
return
|
||||||
|
yield req
|
||||||
|
except queue.Empty:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if pause_stdin[0]:
|
||||||
|
import time
|
||||||
|
time.sleep(0.05)
|
||||||
|
continue
|
||||||
|
|
||||||
|
r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
|
||||||
|
if wake_r in r:
|
||||||
|
os.read(wake_r, 1)
|
||||||
|
continue
|
||||||
|
if sys.stdin.fileno() in r and not pause_stdin[0]:
|
||||||
try:
|
try:
|
||||||
data = os.read(sys.stdin.fileno(), 1024)
|
data = os.read(sys.stdin.fileno(), 1024)
|
||||||
if not data:
|
if not data:
|
||||||
@@ -1235,30 +1577,72 @@ def connect_dynamic(self, connection_params, debug=False):
|
|||||||
|
|
||||||
old_tty = termios.tcgetattr(sys.stdin)
|
old_tty = termios.tcgetattr(sys.stdin)
|
||||||
try:
|
try:
|
||||||
|
import time
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
response_iterator = self.stub.interact_node(request_generator())
|
response_iterator = self.stub.interact_node(request_generator())
|
||||||
|
|
||||||
# First response is connection status
|
import queue
|
||||||
|
response_queue = queue.Queue()
|
||||||
|
|
||||||
|
def response_consumer():
|
||||||
try:
|
try:
|
||||||
first_res = next(response_iterator)
|
for r in response_iterator:
|
||||||
if first_res.success:
|
response_queue.put(r)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
response_queue.put(None)
|
||||||
|
|
||||||
|
t_consumer = threading.Thread(target=response_consumer, daemon=True)
|
||||||
|
t_consumer.start()
|
||||||
|
|
||||||
|
# First phase: Wait for connection status, print early data
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
return
|
||||||
|
if res.stdout_data:
|
||||||
|
data = res.stdout_data
|
||||||
|
if debug:
|
||||||
|
data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
|
||||||
|
os.write(sys.stdout.fileno(), data)
|
||||||
|
|
||||||
|
if res.success:
|
||||||
# Connection established on server, show success message
|
# Connection established on server, show success message
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.success(conn_msg)
|
printer.success(conn_msg)
|
||||||
|
pause_stdin[0] = False
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
else:
|
break
|
||||||
|
|
||||||
|
if res.error_message:
|
||||||
# Connection failed on server
|
# Connection failed on server
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.error(f"Connection failed: {first_res.error_message}")
|
printer.error(f"Connection failed: {res.error_message}")
|
||||||
return
|
return
|
||||||
except StopIteration:
|
except queue.Empty:
|
||||||
return
|
return
|
||||||
|
|
||||||
for res in response_iterator:
|
# Second phase: Stream active session
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
break
|
||||||
|
if res.copilot_prompt:
|
||||||
|
self._handle_remote_copilot(
|
||||||
|
res, request_queue, response_queue,
|
||||||
|
client_buffer_bytes,
|
||||||
|
pause_generator, resume_generator, old_tty
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
if res.stdout_data:
|
if res.stdout_data:
|
||||||
os.write(sys.stdout.fileno(), res.stdout_data)
|
os.write(sys.stdout.fileno(), res.stdout_data)
|
||||||
|
client_buffer_bytes.extend(res.stdout_data)
|
||||||
finally:
|
finally:
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)</code></pre>
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
|
os.close(wake_r)
|
||||||
|
os.close(wake_w)</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -1276,9 +1660,22 @@ def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
|
|||||||
import select
|
import select
|
||||||
import tty
|
import tty
|
||||||
import termios
|
import termios
|
||||||
|
import queue
|
||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
|
request_queue = queue.Queue()
|
||||||
|
client_buffer_bytes = bytearray()
|
||||||
|
pause_stdin = [False]
|
||||||
|
wake_r, wake_w = os.pipe()
|
||||||
|
|
||||||
|
def pause_generator():
|
||||||
|
pause_stdin[0] = True
|
||||||
|
os.write(wake_w, b'\x00')
|
||||||
|
|
||||||
|
def resume_generator():
|
||||||
|
pause_stdin[0] = False
|
||||||
|
|
||||||
def request_generator():
|
def request_generator():
|
||||||
cols, rows = 80, 24
|
cols, rows = 80, 24
|
||||||
try:
|
try:
|
||||||
@@ -1292,8 +1689,25 @@ def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
|
|||||||
)
|
)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
r, _, _ = select.select([sys.stdin.fileno()], [], [])
|
try:
|
||||||
if r:
|
while True:
|
||||||
|
req = request_queue.get_nowait()
|
||||||
|
if req is None:
|
||||||
|
return
|
||||||
|
yield req
|
||||||
|
except queue.Empty:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if pause_stdin[0]:
|
||||||
|
import time
|
||||||
|
time.sleep(0.05)
|
||||||
|
continue
|
||||||
|
|
||||||
|
r, _, _ = select.select([sys.stdin.fileno(), wake_r], [], [], 0.05)
|
||||||
|
if wake_r in r:
|
||||||
|
os.read(wake_r, 1)
|
||||||
|
continue
|
||||||
|
if sys.stdin.fileno() in r and not pause_stdin[0]:
|
||||||
try:
|
try:
|
||||||
data = os.read(sys.stdin.fileno(), 1024)
|
data = os.read(sys.stdin.fileno(), 1024)
|
||||||
if not data:
|
if not data:
|
||||||
@@ -1315,30 +1729,74 @@ def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
|
|||||||
|
|
||||||
old_tty = termios.tcgetattr(sys.stdin)
|
old_tty = termios.tcgetattr(sys.stdin)
|
||||||
try:
|
try:
|
||||||
|
import time
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
response_iterator = self.stub.interact_node(request_generator())
|
response_iterator = self.stub.interact_node(request_generator())
|
||||||
|
|
||||||
# First response is connection status
|
import queue
|
||||||
|
response_queue = queue.Queue()
|
||||||
|
|
||||||
|
def response_consumer():
|
||||||
try:
|
try:
|
||||||
first_res = next(response_iterator)
|
for r in response_iterator:
|
||||||
if first_res.success:
|
response_queue.put(r)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
response_queue.put(None)
|
||||||
|
|
||||||
|
t_consumer = threading.Thread(target=response_consumer, daemon=True)
|
||||||
|
t_consumer.start()
|
||||||
|
|
||||||
|
# First phase: Wait for connection status, print early data
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
return
|
||||||
|
if res.stdout_data:
|
||||||
|
data = res.stdout_data
|
||||||
|
if debug:
|
||||||
|
data = data.replace(b'\x1b[H\x1b[2J', b'').replace(b'\x1bc', b'').replace(b'\x1b[3J', b'')
|
||||||
|
os.write(sys.stdout.fileno(), data)
|
||||||
|
|
||||||
|
if res.success:
|
||||||
# Connection established on server, show success message
|
# Connection established on server, show success message
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.success(conn_msg)
|
printer.success(conn_msg)
|
||||||
|
pause_stdin[0] = False
|
||||||
tty.setraw(sys.stdin.fileno())
|
tty.setraw(sys.stdin.fileno())
|
||||||
else:
|
break
|
||||||
|
|
||||||
|
if res.error_message:
|
||||||
# Connection failed on server
|
# Connection failed on server
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
printer.error(f"Connection failed: {first_res.error_message}")
|
printer.error(f"Connection failed: {res.error_message}")
|
||||||
return
|
return
|
||||||
except StopIteration:
|
except queue.Empty:
|
||||||
return
|
return
|
||||||
|
|
||||||
for res in response_iterator:
|
# Second phase: Stream active session
|
||||||
|
# Clear screen filter is only applied before success (Phase 1).
|
||||||
|
# Once the user has a prompt, Ctrl+L must work normally.
|
||||||
|
while True:
|
||||||
|
res = response_queue.get()
|
||||||
|
if res is None:
|
||||||
|
break
|
||||||
|
if res.copilot_prompt:
|
||||||
|
self._handle_remote_copilot(
|
||||||
|
res, request_queue, response_queue,
|
||||||
|
client_buffer_bytes,
|
||||||
|
pause_generator, resume_generator, old_tty
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
if res.stdout_data:
|
if res.stdout_data:
|
||||||
os.write(sys.stdout.fileno(), res.stdout_data)
|
os.write(sys.stdout.fileno(), res.stdout_data)
|
||||||
|
client_buffer_bytes.extend(res.stdout_data)
|
||||||
finally:
|
finally:
|
||||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)</code></pre>
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
|
||||||
|
os.close(wake_r)
|
||||||
|
os.close(wake_w)</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -2008,6 +2466,7 @@ def stop_api(self):
|
|||||||
<h4><code><a title="connpy.grpc_layer.stubs.AIStub" href="#connpy.grpc_layer.stubs.AIStub">AIStub</a></code></h4>
|
<h4><code><a title="connpy.grpc_layer.stubs.AIStub" href="#connpy.grpc_layer.stubs.AIStub">AIStub</a></code></h4>
|
||||||
<ul class="two-column">
|
<ul class="two-column">
|
||||||
<li><code><a title="connpy.grpc_layer.stubs.AIStub.ask" href="#connpy.grpc_layer.stubs.AIStub.ask">ask</a></code></li>
|
<li><code><a title="connpy.grpc_layer.stubs.AIStub.ask" href="#connpy.grpc_layer.stubs.AIStub.ask">ask</a></code></li>
|
||||||
|
<li><code><a title="connpy.grpc_layer.stubs.AIStub.configure_mcp" href="#connpy.grpc_layer.stubs.AIStub.configure_mcp">configure_mcp</a></code></li>
|
||||||
<li><code><a title="connpy.grpc_layer.stubs.AIStub.configure_provider" href="#connpy.grpc_layer.stubs.AIStub.configure_provider">configure_provider</a></code></li>
|
<li><code><a title="connpy.grpc_layer.stubs.AIStub.configure_provider" href="#connpy.grpc_layer.stubs.AIStub.configure_provider">configure_provider</a></code></li>
|
||||||
<li><code><a title="connpy.grpc_layer.stubs.AIStub.confirm" href="#connpy.grpc_layer.stubs.AIStub.confirm">confirm</a></code></li>
|
<li><code><a title="connpy.grpc_layer.stubs.AIStub.confirm" href="#connpy.grpc_layer.stubs.AIStub.confirm">confirm</a></code></li>
|
||||||
<li><code><a title="connpy.grpc_layer.stubs.AIStub.delete_session" href="#connpy.grpc_layer.stubs.AIStub.delete_session">delete_session</a></code></li>
|
<li><code><a title="connpy.grpc_layer.stubs.AIStub.delete_session" href="#connpy.grpc_layer.stubs.AIStub.delete_session">delete_session</a></code></li>
|
||||||
@@ -2102,7 +2561,7 @@ def stop_api(self):
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.grpc_layer.utils API documentation</title>
|
<title>connpy.grpc_layer.utils API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -138,7 +138,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1487
-667
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,349 @@
|
|||||||
|
<!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.mcp_client API documentation</title>
|
||||||
|
<meta name="description" content="">
|
||||||
|
<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">Module <code>connpy.mcp_client</code></h1>
|
||||||
|
</header>
|
||||||
|
<section id="section-intro">
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.mcp_client.MCPClientManager"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">MCPClientManager</span></span>
|
||||||
|
<span>(</span><span>config=None)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">class MCPClientManager:
|
||||||
|
"""Manages MCP SSE client connections for connpy."""
|
||||||
|
|
||||||
|
_instance = None
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
def __new__(cls, *args, **kwargs):
|
||||||
|
with cls._lock:
|
||||||
|
if cls._instance is None:
|
||||||
|
cls._instance = super(MCPClientManager, cls).__new__(cls)
|
||||||
|
cls._instance._initialized = False
|
||||||
|
return cls._instance
|
||||||
|
|
||||||
|
def __init__(self, config=None):
|
||||||
|
if self._initialized:
|
||||||
|
return
|
||||||
|
self.config = config
|
||||||
|
self.sessions: Dict[str, Dict[str, Any]] = {} # name -> {session, stack}
|
||||||
|
self.tool_cache: Dict[str, List[Dict[str, Any]]] = {}
|
||||||
|
self._connecting: Dict[str, asyncio.Future] = {}
|
||||||
|
self._initialized = True
|
||||||
|
|
||||||
|
async def get_tools_for_llm(self, os_filter: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Fetches tools from enabled MCP servers that match the OS filter.
|
||||||
|
"""
|
||||||
|
if not MCP_AVAILABLE:
|
||||||
|
return []
|
||||||
|
|
||||||
|
all_llm_tools = []
|
||||||
|
try:
|
||||||
|
mcp_config = self.config.config.get("ai", {}).get("mcp_servers", {})
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def _fetch(name, cfg):
|
||||||
|
if not cfg.get("enabled", True): return []
|
||||||
|
|
||||||
|
# Filter by OS if specified in config (primarily used for copilot strict matching)
|
||||||
|
auto_os = cfg.get("auto_load_on_os")
|
||||||
|
if os_filter is not None and auto_os and os_filter.lower() != auto_os.lower():
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
session = await self._ensure_connected(name, cfg)
|
||||||
|
if session:
|
||||||
|
if name in self.tool_cache: return self.tool_cache[name]
|
||||||
|
llm_tools = await self._fetch_tools_as_openai(name, session)
|
||||||
|
self.tool_cache[name] = llm_tools
|
||||||
|
return llm_tools
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return []
|
||||||
|
|
||||||
|
tasks = [ _fetch(name, cfg) for name, cfg in mcp_config.items() ]
|
||||||
|
|
||||||
|
if tasks:
|
||||||
|
results = await asyncio.gather(*tasks)
|
||||||
|
for tools in results:
|
||||||
|
all_llm_tools.extend(tools)
|
||||||
|
|
||||||
|
return all_llm_tools
|
||||||
|
|
||||||
|
async def _ensure_connected(self, name: str, cfg: Dict[str, Any]) -> Optional[Any]:
|
||||||
|
if not MCP_AVAILABLE: return None
|
||||||
|
|
||||||
|
if name in self.sessions and self.sessions[name].get("session"):
|
||||||
|
return self.sessions[name]["session"]
|
||||||
|
|
||||||
|
url = cfg.get("url")
|
||||||
|
if not url:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if name in self._connecting:
|
||||||
|
try:
|
||||||
|
return await asyncio.wait_for(asyncio.shield(self._connecting[name]), timeout=10.0)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
fut = loop.create_future()
|
||||||
|
self._connecting[name] = fut
|
||||||
|
|
||||||
|
try:
|
||||||
|
from contextlib import AsyncExitStack
|
||||||
|
stack = AsyncExitStack()
|
||||||
|
|
||||||
|
async def _do_connect():
|
||||||
|
read, write = await stack.enter_async_context(sse_client(url))
|
||||||
|
session = await stack.enter_async_context(ClientSession(read, write))
|
||||||
|
await session.initialize()
|
||||||
|
return session
|
||||||
|
|
||||||
|
session = await asyncio.wait_for(_do_connect(), timeout=15.0)
|
||||||
|
self.sessions[name] = {"session": session, "stack": stack}
|
||||||
|
fut.set_result(session)
|
||||||
|
return session
|
||||||
|
except Exception:
|
||||||
|
fut.set_result(None)
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
if name in self._connecting:
|
||||||
|
del self._connecting[name]
|
||||||
|
|
||||||
|
async def _fetch_tools_as_openai(self, server_name: str, session: Any) -> List[Dict[str, Any]]:
|
||||||
|
try:
|
||||||
|
result = await asyncio.wait_for(session.list_tools(), timeout=5.0)
|
||||||
|
openai_tools = []
|
||||||
|
for tool in result.tools:
|
||||||
|
# Use mcp_ prefix to ensure valid function name for LiteLLM/Gemini
|
||||||
|
prefixed_name = f"mcp_{server_name}__{tool.name}"
|
||||||
|
openai_tools.append({
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": prefixed_name,
|
||||||
|
"description": f"[{server_name}] {tool.description}",
|
||||||
|
"parameters": tool.inputSchema
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return openai_tools
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def call_tool(self, full_tool_name: str, arguments: Dict[str, Any]) -> Any:
|
||||||
|
"""Calls an MCP tool and returns text result."""
|
||||||
|
if not MCP_AVAILABLE:
|
||||||
|
return "Error: MCP SDK is not installed."
|
||||||
|
|
||||||
|
if "__" not in full_tool_name:
|
||||||
|
return f"Error: Tool {full_tool_name} is not a valid MCP tool."
|
||||||
|
|
||||||
|
clean_name = full_tool_name[4:] if full_tool_name.startswith("mcp_") else full_tool_name
|
||||||
|
server_name, tool_name = clean_name.split("__", 1)
|
||||||
|
|
||||||
|
if server_name not in self.sessions:
|
||||||
|
return f"Error: MCP server {server_name} is not connected."
|
||||||
|
|
||||||
|
session = self.sessions[server_name]["session"]
|
||||||
|
try:
|
||||||
|
result = await asyncio.wait_for(session.call_tool(tool_name, arguments), timeout=60.0)
|
||||||
|
text_outputs = [content.text for content in result.content if hasattr(content, "text")]
|
||||||
|
return "\n".join(text_outputs) if text_outputs else str(result)
|
||||||
|
except Exception as e:
|
||||||
|
return f"Error calling tool {tool_name} on {server_name}: {str(e)}"
|
||||||
|
|
||||||
|
async def shutdown(self):
|
||||||
|
"""Close all SSE connections."""
|
||||||
|
for name, data in self.sessions.items():
|
||||||
|
stack = data.get("stack")
|
||||||
|
if stack:
|
||||||
|
await stack.aclose()
|
||||||
|
self.sessions = {}</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Manages MCP SSE client connections for connpy.</p></div>
|
||||||
|
<h3>Methods</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.mcp_client.MCPClientManager.call_tool"><code class="name flex">
|
||||||
|
<span>async def <span class="ident">call_tool</span></span>(<span>self, full_tool_name: str, arguments: Dict[str, Any]) ‑> Any</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">async def call_tool(self, full_tool_name: str, arguments: Dict[str, Any]) -> Any:
|
||||||
|
"""Calls an MCP tool and returns text result."""
|
||||||
|
if not MCP_AVAILABLE:
|
||||||
|
return "Error: MCP SDK is not installed."
|
||||||
|
|
||||||
|
if "__" not in full_tool_name:
|
||||||
|
return f"Error: Tool {full_tool_name} is not a valid MCP tool."
|
||||||
|
|
||||||
|
clean_name = full_tool_name[4:] if full_tool_name.startswith("mcp_") else full_tool_name
|
||||||
|
server_name, tool_name = clean_name.split("__", 1)
|
||||||
|
|
||||||
|
if server_name not in self.sessions:
|
||||||
|
return f"Error: MCP server {server_name} is not connected."
|
||||||
|
|
||||||
|
session = self.sessions[server_name]["session"]
|
||||||
|
try:
|
||||||
|
result = await asyncio.wait_for(session.call_tool(tool_name, arguments), timeout=60.0)
|
||||||
|
text_outputs = [content.text for content in result.content if hasattr(content, "text")]
|
||||||
|
return "\n".join(text_outputs) if text_outputs else str(result)
|
||||||
|
except Exception as e:
|
||||||
|
return f"Error calling tool {tool_name} on {server_name}: {str(e)}"</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Calls an MCP tool and returns text result.</p></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.mcp_client.MCPClientManager.get_tools_for_llm"><code class="name flex">
|
||||||
|
<span>async def <span class="ident">get_tools_for_llm</span></span>(<span>self, os_filter: str | None = None) ‑> List[Dict[str, Any]]</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">async def get_tools_for_llm(self, os_filter: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Fetches tools from enabled MCP servers that match the OS filter.
|
||||||
|
"""
|
||||||
|
if not MCP_AVAILABLE:
|
||||||
|
return []
|
||||||
|
|
||||||
|
all_llm_tools = []
|
||||||
|
try:
|
||||||
|
mcp_config = self.config.config.get("ai", {}).get("mcp_servers", {})
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def _fetch(name, cfg):
|
||||||
|
if not cfg.get("enabled", True): return []
|
||||||
|
|
||||||
|
# Filter by OS if specified in config (primarily used for copilot strict matching)
|
||||||
|
auto_os = cfg.get("auto_load_on_os")
|
||||||
|
if os_filter is not None and auto_os and os_filter.lower() != auto_os.lower():
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
session = await self._ensure_connected(name, cfg)
|
||||||
|
if session:
|
||||||
|
if name in self.tool_cache: return self.tool_cache[name]
|
||||||
|
llm_tools = await self._fetch_tools_as_openai(name, session)
|
||||||
|
self.tool_cache[name] = llm_tools
|
||||||
|
return llm_tools
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return []
|
||||||
|
|
||||||
|
tasks = [ _fetch(name, cfg) for name, cfg in mcp_config.items() ]
|
||||||
|
|
||||||
|
if tasks:
|
||||||
|
results = await asyncio.gather(*tasks)
|
||||||
|
for tools in results:
|
||||||
|
all_llm_tools.extend(tools)
|
||||||
|
|
||||||
|
return all_llm_tools</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Fetches tools from enabled MCP servers that match the OS filter.</p></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.mcp_client.MCPClientManager.shutdown"><code class="name flex">
|
||||||
|
<span>async def <span class="ident">shutdown</span></span>(<span>self)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">async def shutdown(self):
|
||||||
|
"""Close all SSE connections."""
|
||||||
|
for name, data in self.sessions.items():
|
||||||
|
stack = data.get("stack")
|
||||||
|
if stack:
|
||||||
|
await stack.aclose()
|
||||||
|
self.sessions = {}</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Close all SSE connections.</p></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
</article>
|
||||||
|
<nav id="sidebar">
|
||||||
|
<div class="toc">
|
||||||
|
<ul></ul>
|
||||||
|
</div>
|
||||||
|
<ul id="index">
|
||||||
|
<li><h3>Super-module</h3>
|
||||||
|
<ul>
|
||||||
|
<li><code><a title="connpy" href="index.html">connpy</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.mcp_client.MCPClientManager" href="#connpy.mcp_client.MCPClientManager">MCPClientManager</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.mcp_client.MCPClientManager.call_tool" href="#connpy.mcp_client.MCPClientManager.call_tool">call_tool</a></code></li>
|
||||||
|
<li><code><a title="connpy.mcp_client.MCPClientManager.get_tools_for_llm" href="#connpy.mcp_client.MCPClientManager.get_tools_for_llm">get_tools_for_llm</a></code></li>
|
||||||
|
<li><code><a title="connpy.mcp_client.MCPClientManager.shutdown" href="#connpy.mcp_client.MCPClientManager.shutdown">shutdown</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>
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.proto API documentation</title>
|
<title>connpy.proto API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -60,7 +60,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.ai_service API documentation</title>
|
<title>connpy.services.ai_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -58,6 +58,138 @@ el.replaceWith(d);
|
|||||||
<pre><code class="python">class AIService(BaseService):
|
<pre><code class="python">class AIService(BaseService):
|
||||||
"""Business logic for interacting with AI agents and LLM configurations."""
|
"""Business logic for interacting with AI agents and LLM configurations."""
|
||||||
|
|
||||||
|
def build_context_blocks(self, raw_bytes: bytes, cmd_byte_positions: list, node_info: dict, last_line: str = "") -> list:
|
||||||
|
"""Identifies command blocks in the terminal history."""
|
||||||
|
blocks = []
|
||||||
|
if not raw_bytes:
|
||||||
|
return blocks
|
||||||
|
|
||||||
|
default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$'
|
||||||
|
device_prompt = node_info.get("prompt", default_prompt) if isinstance(node_info, dict) else default_prompt
|
||||||
|
prompt_re_str = re.sub(r'(?<!\\)\$', '', device_prompt)
|
||||||
|
try:
|
||||||
|
prompt_re = re.compile(prompt_re_str)
|
||||||
|
except Exception:
|
||||||
|
prompt_re = re.compile(re.sub(r'(?<!\\)\$', '', default_prompt))
|
||||||
|
|
||||||
|
parsed_positions = []
|
||||||
|
if cmd_byte_positions and len(cmd_byte_positions) >= 1:
|
||||||
|
for i in range(1, len(cmd_byte_positions)):
|
||||||
|
pos, known_cmd = cmd_byte_positions[i]
|
||||||
|
prev_pos = cmd_byte_positions[i-1][0]
|
||||||
|
|
||||||
|
if known_cmd:
|
||||||
|
prev_chunk = raw_bytes[prev_pos:pos]
|
||||||
|
prev_cleaned = log_cleaner(prev_chunk.decode(errors='replace'))
|
||||||
|
prev_lines = [l for l in prev_cleaned.split('\n') if l.strip()]
|
||||||
|
prompt_text = prev_lines[-1].strip() if prev_lines else ""
|
||||||
|
preview = f"{prompt_text}{known_cmd}" if prompt_text else known_cmd
|
||||||
|
parsed_positions.append({"pos": pos, "type": "VALID_CMD", "preview": preview[:80]})
|
||||||
|
else:
|
||||||
|
chunk = raw_bytes[prev_pos:pos]
|
||||||
|
cleaned = log_cleaner(chunk.decode(errors='replace'))
|
||||||
|
lines = [l for l in cleaned.split('\n') if l.strip()]
|
||||||
|
preview = lines[-1].strip() if lines else ""
|
||||||
|
|
||||||
|
if preview:
|
||||||
|
match = prompt_re.search(preview)
|
||||||
|
if match:
|
||||||
|
cmd_text = preview[match.end():].strip()
|
||||||
|
if cmd_text:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "VALID_CMD", "preview": preview[:80]})
|
||||||
|
else:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "EMPTY_PROMPT", "preview": ""})
|
||||||
|
else:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "SCROLLING", "preview": ""})
|
||||||
|
else:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "SCROLLING", "preview": ""})
|
||||||
|
|
||||||
|
last_newline = raw_bytes.rfind(b'\n')
|
||||||
|
current_prompt_pos = last_newline + 1 if last_newline != -1 else 0
|
||||||
|
current_end = len(raw_bytes)
|
||||||
|
|
||||||
|
for i, item in enumerate(parsed_positions):
|
||||||
|
if item["type"] == "VALID_CMD":
|
||||||
|
start_pos = item["pos"]
|
||||||
|
preview = item["preview"]
|
||||||
|
|
||||||
|
# Find the end position: next VALID_CMD or EMPTY_PROMPT
|
||||||
|
end_pos = current_prompt_pos
|
||||||
|
for j in range(i + 1, len(parsed_positions)):
|
||||||
|
next_item = parsed_positions[j]
|
||||||
|
if next_item["type"] in ("VALID_CMD", "EMPTY_PROMPT"):
|
||||||
|
end_pos = next_item["pos"]
|
||||||
|
break
|
||||||
|
|
||||||
|
blocks.append((start_pos, end_pos, preview))
|
||||||
|
|
||||||
|
# Always ensure there is a final block representing the current prompt
|
||||||
|
if not blocks:
|
||||||
|
blocks.append((current_prompt_pos, current_end, last_line[:80] if last_line else "CURRENT CONTEXT"))
|
||||||
|
elif blocks[-1][0] < current_prompt_pos:
|
||||||
|
blocks.append((current_prompt_pos, current_end, last_line[:80] if last_line else "CURRENT CONTEXT"))
|
||||||
|
|
||||||
|
return blocks
|
||||||
|
|
||||||
|
def process_copilot_input(self, input_text: str, session_state: dict) -> dict:
|
||||||
|
"""Parses slash commands and manages session state. Returns directive dict."""
|
||||||
|
text = input_text.strip()
|
||||||
|
if not text.startswith('/'):
|
||||||
|
return {"action": "execute", "clean_prompt": text, "overrides": {}}
|
||||||
|
|
||||||
|
parts = text.split(maxsplit=1)
|
||||||
|
cmd = parts[0].lower()
|
||||||
|
args = parts[1] if len(parts) > 1 else ""
|
||||||
|
|
||||||
|
# 1. State Commands (Persistent)
|
||||||
|
if cmd == "/os":
|
||||||
|
if args:
|
||||||
|
session_state['os'] = args
|
||||||
|
return {"action": "state_update", "message": f"OS context changed to {args}"}
|
||||||
|
elif cmd == "/prompt":
|
||||||
|
if args:
|
||||||
|
session_state['prompt'] = args
|
||||||
|
return {"action": "state_update", "message": f"Prompt regex changed to {args}"}
|
||||||
|
elif cmd == "/memorize":
|
||||||
|
if args:
|
||||||
|
session_state['memories'].append(args)
|
||||||
|
return {"action": "state_update", "message": f"Memory added: {args}"}
|
||||||
|
elif cmd == "/clear":
|
||||||
|
session_state['memories'] = []
|
||||||
|
return {"action": "state_update", "message": "Memory cleared"}
|
||||||
|
|
||||||
|
# 2. Hybrid Commands
|
||||||
|
elif cmd == "/architect":
|
||||||
|
if not args:
|
||||||
|
session_state['persona'] = 'architect'
|
||||||
|
return {"action": "state_update", "message": "Persona set to Architect"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"persona": "architect"}}
|
||||||
|
|
||||||
|
elif cmd == "/engineer":
|
||||||
|
if not args:
|
||||||
|
session_state['persona'] = 'engineer'
|
||||||
|
return {"action": "state_update", "message": "Persona set to Engineer"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"persona": "engineer"}}
|
||||||
|
|
||||||
|
elif cmd == "/trust":
|
||||||
|
if not args:
|
||||||
|
session_state['trust_mode'] = True
|
||||||
|
return {"action": "state_update", "message": "Auto-execute (trust) enabled for session"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"trust": True}}
|
||||||
|
|
||||||
|
elif cmd == "/untrust":
|
||||||
|
if not args:
|
||||||
|
session_state['trust_mode'] = False
|
||||||
|
return {"action": "state_update", "message": "Auto-execute (trust) disabled for session"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"trust": False}}
|
||||||
|
|
||||||
|
# Unknown command, execute normally
|
||||||
|
return {"action": "execute", "clean_prompt": text, "overrides": {}}
|
||||||
|
|
||||||
def ask(self, input_text, dryrun=False, chat_history=None, status=None, debug=False, session_id=None, console=None, chunk_callback=None, confirm_handler=None, trust=False, **overrides):
|
def ask(self, input_text, dryrun=False, chat_history=None, status=None, debug=False, session_id=None, console=None, chunk_callback=None, confirm_handler=None, trust=False, **overrides):
|
||||||
"""Send a prompt to the AI agent."""
|
"""Send a prompt to the AI agent."""
|
||||||
from connpy.ai import ai
|
from connpy.ai import ai
|
||||||
@@ -71,6 +203,21 @@ el.replaceWith(d);
|
|||||||
agent = ai(self.config, console=console)
|
agent = ai(self.config, console=console)
|
||||||
return agent.confirm(input_text)
|
return agent.confirm(input_text)
|
||||||
|
|
||||||
|
def ask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
|
||||||
|
"""Ask the AI copilot for terminal assistance."""
|
||||||
|
from connpy.ai import ai, run_ai_async
|
||||||
|
agent = ai(self.config)
|
||||||
|
future = run_ai_async(agent.aask_copilot(terminal_buffer, user_question, node_info, chunk_callback=chunk_callback))
|
||||||
|
return future.result()
|
||||||
|
|
||||||
|
async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
|
||||||
|
"""Ask the AI copilot for terminal assistance asynchronously."""
|
||||||
|
from connpy.ai import ai, run_ai_async
|
||||||
|
import asyncio
|
||||||
|
agent = ai(self.config)
|
||||||
|
future = run_ai_async(agent.aask_copilot(terminal_buffer, user_question, node_info, chunk_callback=chunk_callback))
|
||||||
|
return await asyncio.wrap_future(future)
|
||||||
|
|
||||||
|
|
||||||
def list_sessions(self):
|
def list_sessions(self):
|
||||||
"""Return a list of all saved AI sessions."""
|
"""Return a list of all saved AI sessions."""
|
||||||
@@ -99,6 +246,40 @@ el.replaceWith(d);
|
|||||||
self.config.config["ai"] = settings
|
self.config.config["ai"] = settings
|
||||||
self.config._saveconfig(self.config.file)
|
self.config._saveconfig(self.config.file)
|
||||||
|
|
||||||
|
def configure_mcp(self, name, url=None, enabled=None, auto_load_on_os=None, remove=False):
|
||||||
|
"""Update MCP server settings in the configuration with smart merging."""
|
||||||
|
ai_settings = self.config.config.get("ai", {})
|
||||||
|
mcp_servers = ai_settings.get("mcp_servers", {})
|
||||||
|
|
||||||
|
if remove:
|
||||||
|
if name in mcp_servers:
|
||||||
|
del mcp_servers[name]
|
||||||
|
else:
|
||||||
|
# Get existing or new
|
||||||
|
server_cfg = mcp_servers.get(name, {})
|
||||||
|
|
||||||
|
# Partial updates
|
||||||
|
if url is not None:
|
||||||
|
server_cfg["url"] = url
|
||||||
|
|
||||||
|
if enabled is not None:
|
||||||
|
server_cfg["enabled"] = bool(enabled)
|
||||||
|
elif "enabled" not in server_cfg:
|
||||||
|
server_cfg["enabled"] = True # Default for new entries
|
||||||
|
|
||||||
|
if auto_load_on_os is not None:
|
||||||
|
if auto_load_on_os == "": # Explicit clear
|
||||||
|
if "auto_load_on_os" in server_cfg:
|
||||||
|
del server_cfg["auto_load_on_os"]
|
||||||
|
else:
|
||||||
|
server_cfg["auto_load_on_os"] = auto_load_on_os
|
||||||
|
|
||||||
|
mcp_servers[name] = server_cfg
|
||||||
|
|
||||||
|
ai_settings["mcp_servers"] = mcp_servers
|
||||||
|
self.config.config["ai"] = ai_settings
|
||||||
|
self.config._saveconfig(self.config.file)
|
||||||
|
|
||||||
def load_session_data(self, session_id):
|
def load_session_data(self, session_id):
|
||||||
"""Load a session's raw data by ID."""
|
"""Load a session's raw data by ID."""
|
||||||
from connpy.ai import ai
|
from connpy.ai import ai
|
||||||
@@ -118,6 +299,24 @@ el.replaceWith(d);
|
|||||||
</ul>
|
</ul>
|
||||||
<h3>Methods</h3>
|
<h3>Methods</h3>
|
||||||
<dl>
|
<dl>
|
||||||
|
<dt id="connpy.services.ai_service.AIService.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">async def aask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
|
||||||
|
"""Ask the AI copilot for terminal assistance asynchronously."""
|
||||||
|
from connpy.ai import ai, run_ai_async
|
||||||
|
import asyncio
|
||||||
|
agent = ai(self.config)
|
||||||
|
future = run_ai_async(agent.aask_copilot(terminal_buffer, user_question, node_info, chunk_callback=chunk_callback))
|
||||||
|
return await asyncio.wrap_future(future)</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Ask the AI copilot for terminal assistance asynchronously.</p></div>
|
||||||
|
</dd>
|
||||||
<dt id="connpy.services.ai_service.AIService.ask"><code class="name flex">
|
<dt id="connpy.services.ai_service.AIService.ask"><code class="name flex">
|
||||||
<span>def <span class="ident">ask</span></span>(<span>self,<br>input_text,<br>dryrun=False,<br>chat_history=None,<br>status=None,<br>debug=False,<br>session_id=None,<br>console=None,<br>chunk_callback=None,<br>confirm_handler=None,<br>trust=False,<br>**overrides)</span>
|
<span>def <span class="ident">ask</span></span>(<span>self,<br>input_text,<br>dryrun=False,<br>chat_history=None,<br>status=None,<br>debug=False,<br>session_id=None,<br>console=None,<br>chunk_callback=None,<br>confirm_handler=None,<br>trust=False,<br>**overrides)</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
@@ -134,6 +333,150 @@ el.replaceWith(d);
|
|||||||
</details>
|
</details>
|
||||||
<div class="desc"><p>Send a prompt to the AI agent.</p></div>
|
<div class="desc"><p>Send a prompt to the AI agent.</p></div>
|
||||||
</dd>
|
</dd>
|
||||||
|
<dt id="connpy.services.ai_service.AIService.ask_copilot"><code class="name flex">
|
||||||
|
<span>def <span class="ident">ask_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">def ask_copilot(self, terminal_buffer, user_question, node_info=None, chunk_callback=None):
|
||||||
|
"""Ask the AI copilot for terminal assistance."""
|
||||||
|
from connpy.ai import ai, run_ai_async
|
||||||
|
agent = ai(self.config)
|
||||||
|
future = run_ai_async(agent.aask_copilot(terminal_buffer, user_question, node_info, chunk_callback=chunk_callback))
|
||||||
|
return future.result()</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Ask the AI copilot for terminal assistance.</p></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.services.ai_service.AIService.build_context_blocks"><code class="name flex">
|
||||||
|
<span>def <span class="ident">build_context_blocks</span></span>(<span>self,<br>raw_bytes: bytes,<br>cmd_byte_positions: list,<br>node_info: dict,<br>last_line: str = '') ‑> list</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def build_context_blocks(self, raw_bytes: bytes, cmd_byte_positions: list, node_info: dict, last_line: str = "") -> list:
|
||||||
|
"""Identifies command blocks in the terminal history."""
|
||||||
|
blocks = []
|
||||||
|
if not raw_bytes:
|
||||||
|
return blocks
|
||||||
|
|
||||||
|
default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$'
|
||||||
|
device_prompt = node_info.get("prompt", default_prompt) if isinstance(node_info, dict) else default_prompt
|
||||||
|
prompt_re_str = re.sub(r'(?<!\\)\$', '', device_prompt)
|
||||||
|
try:
|
||||||
|
prompt_re = re.compile(prompt_re_str)
|
||||||
|
except Exception:
|
||||||
|
prompt_re = re.compile(re.sub(r'(?<!\\)\$', '', default_prompt))
|
||||||
|
|
||||||
|
parsed_positions = []
|
||||||
|
if cmd_byte_positions and len(cmd_byte_positions) >= 1:
|
||||||
|
for i in range(1, len(cmd_byte_positions)):
|
||||||
|
pos, known_cmd = cmd_byte_positions[i]
|
||||||
|
prev_pos = cmd_byte_positions[i-1][0]
|
||||||
|
|
||||||
|
if known_cmd:
|
||||||
|
prev_chunk = raw_bytes[prev_pos:pos]
|
||||||
|
prev_cleaned = log_cleaner(prev_chunk.decode(errors='replace'))
|
||||||
|
prev_lines = [l for l in prev_cleaned.split('\n') if l.strip()]
|
||||||
|
prompt_text = prev_lines[-1].strip() if prev_lines else ""
|
||||||
|
preview = f"{prompt_text}{known_cmd}" if prompt_text else known_cmd
|
||||||
|
parsed_positions.append({"pos": pos, "type": "VALID_CMD", "preview": preview[:80]})
|
||||||
|
else:
|
||||||
|
chunk = raw_bytes[prev_pos:pos]
|
||||||
|
cleaned = log_cleaner(chunk.decode(errors='replace'))
|
||||||
|
lines = [l for l in cleaned.split('\n') if l.strip()]
|
||||||
|
preview = lines[-1].strip() if lines else ""
|
||||||
|
|
||||||
|
if preview:
|
||||||
|
match = prompt_re.search(preview)
|
||||||
|
if match:
|
||||||
|
cmd_text = preview[match.end():].strip()
|
||||||
|
if cmd_text:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "VALID_CMD", "preview": preview[:80]})
|
||||||
|
else:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "EMPTY_PROMPT", "preview": ""})
|
||||||
|
else:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "SCROLLING", "preview": ""})
|
||||||
|
else:
|
||||||
|
parsed_positions.append({"pos": pos, "type": "SCROLLING", "preview": ""})
|
||||||
|
|
||||||
|
last_newline = raw_bytes.rfind(b'\n')
|
||||||
|
current_prompt_pos = last_newline + 1 if last_newline != -1 else 0
|
||||||
|
current_end = len(raw_bytes)
|
||||||
|
|
||||||
|
for i, item in enumerate(parsed_positions):
|
||||||
|
if item["type"] == "VALID_CMD":
|
||||||
|
start_pos = item["pos"]
|
||||||
|
preview = item["preview"]
|
||||||
|
|
||||||
|
# Find the end position: next VALID_CMD or EMPTY_PROMPT
|
||||||
|
end_pos = current_prompt_pos
|
||||||
|
for j in range(i + 1, len(parsed_positions)):
|
||||||
|
next_item = parsed_positions[j]
|
||||||
|
if next_item["type"] in ("VALID_CMD", "EMPTY_PROMPT"):
|
||||||
|
end_pos = next_item["pos"]
|
||||||
|
break
|
||||||
|
|
||||||
|
blocks.append((start_pos, end_pos, preview))
|
||||||
|
|
||||||
|
# Always ensure there is a final block representing the current prompt
|
||||||
|
if not blocks:
|
||||||
|
blocks.append((current_prompt_pos, current_end, last_line[:80] if last_line else "CURRENT CONTEXT"))
|
||||||
|
elif blocks[-1][0] < current_prompt_pos:
|
||||||
|
blocks.append((current_prompt_pos, current_end, last_line[:80] if last_line else "CURRENT CONTEXT"))
|
||||||
|
|
||||||
|
return blocks</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Identifies command blocks in the terminal history.</p></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.services.ai_service.AIService.configure_mcp"><code class="name flex">
|
||||||
|
<span>def <span class="ident">configure_mcp</span></span>(<span>self, name, url=None, enabled=None, auto_load_on_os=None, remove=False)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def configure_mcp(self, name, url=None, enabled=None, auto_load_on_os=None, remove=False):
|
||||||
|
"""Update MCP server settings in the configuration with smart merging."""
|
||||||
|
ai_settings = self.config.config.get("ai", {})
|
||||||
|
mcp_servers = ai_settings.get("mcp_servers", {})
|
||||||
|
|
||||||
|
if remove:
|
||||||
|
if name in mcp_servers:
|
||||||
|
del mcp_servers[name]
|
||||||
|
else:
|
||||||
|
# Get existing or new
|
||||||
|
server_cfg = mcp_servers.get(name, {})
|
||||||
|
|
||||||
|
# Partial updates
|
||||||
|
if url is not None:
|
||||||
|
server_cfg["url"] = url
|
||||||
|
|
||||||
|
if enabled is not None:
|
||||||
|
server_cfg["enabled"] = bool(enabled)
|
||||||
|
elif "enabled" not in server_cfg:
|
||||||
|
server_cfg["enabled"] = True # Default for new entries
|
||||||
|
|
||||||
|
if auto_load_on_os is not None:
|
||||||
|
if auto_load_on_os == "": # Explicit clear
|
||||||
|
if "auto_load_on_os" in server_cfg:
|
||||||
|
del server_cfg["auto_load_on_os"]
|
||||||
|
else:
|
||||||
|
server_cfg["auto_load_on_os"] = auto_load_on_os
|
||||||
|
|
||||||
|
mcp_servers[name] = server_cfg
|
||||||
|
|
||||||
|
ai_settings["mcp_servers"] = mcp_servers
|
||||||
|
self.config.config["ai"] = ai_settings
|
||||||
|
self.config._saveconfig(self.config.file)</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Update MCP server settings in the configuration with smart merging.</p></div>
|
||||||
|
</dd>
|
||||||
<dt id="connpy.services.ai_service.AIService.configure_provider"><code class="name flex">
|
<dt id="connpy.services.ai_service.AIService.configure_provider"><code class="name flex">
|
||||||
<span>def <span class="ident">configure_provider</span></span>(<span>self, provider, model=None, api_key=None)</span>
|
<span>def <span class="ident">configure_provider</span></span>(<span>self, provider, model=None, api_key=None)</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
@@ -223,6 +566,75 @@ el.replaceWith(d);
|
|||||||
</details>
|
</details>
|
||||||
<div class="desc"><p>Load a session's raw data by ID.</p></div>
|
<div class="desc"><p>Load a session's raw data by ID.</p></div>
|
||||||
</dd>
|
</dd>
|
||||||
|
<dt id="connpy.services.ai_service.AIService.process_copilot_input"><code class="name flex">
|
||||||
|
<span>def <span class="ident">process_copilot_input</span></span>(<span>self, input_text: str, session_state: dict) ‑> dict</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def process_copilot_input(self, input_text: str, session_state: dict) -> dict:
|
||||||
|
"""Parses slash commands and manages session state. Returns directive dict."""
|
||||||
|
text = input_text.strip()
|
||||||
|
if not text.startswith('/'):
|
||||||
|
return {"action": "execute", "clean_prompt": text, "overrides": {}}
|
||||||
|
|
||||||
|
parts = text.split(maxsplit=1)
|
||||||
|
cmd = parts[0].lower()
|
||||||
|
args = parts[1] if len(parts) > 1 else ""
|
||||||
|
|
||||||
|
# 1. State Commands (Persistent)
|
||||||
|
if cmd == "/os":
|
||||||
|
if args:
|
||||||
|
session_state['os'] = args
|
||||||
|
return {"action": "state_update", "message": f"OS context changed to {args}"}
|
||||||
|
elif cmd == "/prompt":
|
||||||
|
if args:
|
||||||
|
session_state['prompt'] = args
|
||||||
|
return {"action": "state_update", "message": f"Prompt regex changed to {args}"}
|
||||||
|
elif cmd == "/memorize":
|
||||||
|
if args:
|
||||||
|
session_state['memories'].append(args)
|
||||||
|
return {"action": "state_update", "message": f"Memory added: {args}"}
|
||||||
|
elif cmd == "/clear":
|
||||||
|
session_state['memories'] = []
|
||||||
|
return {"action": "state_update", "message": "Memory cleared"}
|
||||||
|
|
||||||
|
# 2. Hybrid Commands
|
||||||
|
elif cmd == "/architect":
|
||||||
|
if not args:
|
||||||
|
session_state['persona'] = 'architect'
|
||||||
|
return {"action": "state_update", "message": "Persona set to Architect"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"persona": "architect"}}
|
||||||
|
|
||||||
|
elif cmd == "/engineer":
|
||||||
|
if not args:
|
||||||
|
session_state['persona'] = 'engineer'
|
||||||
|
return {"action": "state_update", "message": "Persona set to Engineer"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"persona": "engineer"}}
|
||||||
|
|
||||||
|
elif cmd == "/trust":
|
||||||
|
if not args:
|
||||||
|
session_state['trust_mode'] = True
|
||||||
|
return {"action": "state_update", "message": "Auto-execute (trust) enabled for session"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"trust": True}}
|
||||||
|
|
||||||
|
elif cmd == "/untrust":
|
||||||
|
if not args:
|
||||||
|
session_state['trust_mode'] = False
|
||||||
|
return {"action": "state_update", "message": "Auto-execute (trust) disabled for session"}
|
||||||
|
else:
|
||||||
|
return {"action": "execute", "clean_prompt": args, "overrides": {"trust": False}}
|
||||||
|
|
||||||
|
# Unknown command, execute normally
|
||||||
|
return {"action": "execute", "clean_prompt": text, "overrides": {}}</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Parses slash commands and manages session state. Returns directive dict.</p></div>
|
||||||
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
<h3>Inherited members</h3>
|
<h3>Inherited members</h3>
|
||||||
<ul class="hlist">
|
<ul class="hlist">
|
||||||
@@ -250,13 +662,18 @@ el.replaceWith(d);
|
|||||||
<ul>
|
<ul>
|
||||||
<li>
|
<li>
|
||||||
<h4><code><a title="connpy.services.ai_service.AIService" href="#connpy.services.ai_service.AIService">AIService</a></code></h4>
|
<h4><code><a title="connpy.services.ai_service.AIService" href="#connpy.services.ai_service.AIService">AIService</a></code></h4>
|
||||||
<ul class="two-column">
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.services.ai_service.AIService.aask_copilot" href="#connpy.services.ai_service.AIService.aask_copilot">aask_copilot</a></code></li>
|
||||||
<li><code><a title="connpy.services.ai_service.AIService.ask" href="#connpy.services.ai_service.AIService.ask">ask</a></code></li>
|
<li><code><a title="connpy.services.ai_service.AIService.ask" href="#connpy.services.ai_service.AIService.ask">ask</a></code></li>
|
||||||
|
<li><code><a title="connpy.services.ai_service.AIService.ask_copilot" href="#connpy.services.ai_service.AIService.ask_copilot">ask_copilot</a></code></li>
|
||||||
|
<li><code><a title="connpy.services.ai_service.AIService.build_context_blocks" href="#connpy.services.ai_service.AIService.build_context_blocks">build_context_blocks</a></code></li>
|
||||||
|
<li><code><a title="connpy.services.ai_service.AIService.configure_mcp" href="#connpy.services.ai_service.AIService.configure_mcp">configure_mcp</a></code></li>
|
||||||
<li><code><a title="connpy.services.ai_service.AIService.configure_provider" href="#connpy.services.ai_service.AIService.configure_provider">configure_provider</a></code></li>
|
<li><code><a title="connpy.services.ai_service.AIService.configure_provider" href="#connpy.services.ai_service.AIService.configure_provider">configure_provider</a></code></li>
|
||||||
<li><code><a title="connpy.services.ai_service.AIService.confirm" href="#connpy.services.ai_service.AIService.confirm">confirm</a></code></li>
|
<li><code><a title="connpy.services.ai_service.AIService.confirm" href="#connpy.services.ai_service.AIService.confirm">confirm</a></code></li>
|
||||||
<li><code><a title="connpy.services.ai_service.AIService.delete_session" href="#connpy.services.ai_service.AIService.delete_session">delete_session</a></code></li>
|
<li><code><a title="connpy.services.ai_service.AIService.delete_session" href="#connpy.services.ai_service.AIService.delete_session">delete_session</a></code></li>
|
||||||
<li><code><a title="connpy.services.ai_service.AIService.list_sessions" href="#connpy.services.ai_service.AIService.list_sessions">list_sessions</a></code></li>
|
<li><code><a title="connpy.services.ai_service.AIService.list_sessions" href="#connpy.services.ai_service.AIService.list_sessions">list_sessions</a></code></li>
|
||||||
<li><code><a title="connpy.services.ai_service.AIService.load_session_data" href="#connpy.services.ai_service.AIService.load_session_data">load_session_data</a></code></li>
|
<li><code><a title="connpy.services.ai_service.AIService.load_session_data" href="#connpy.services.ai_service.AIService.load_session_data">load_session_data</a></code></li>
|
||||||
|
<li><code><a title="connpy.services.ai_service.AIService.process_copilot_input" href="#connpy.services.ai_service.AIService.process_copilot_input">process_copilot_input</a></code></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
@@ -265,7 +682,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.base API documentation</title>
|
<title>connpy.services.base API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -152,7 +152,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.config_service API documentation</title>
|
<title>connpy.services.config_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -117,6 +117,10 @@ el.replaceWith(d);
|
|||||||
if not isinstance(user_styles, dict):
|
if not isinstance(user_styles, dict):
|
||||||
raise InvalidConfigurationError("Theme file must be a YAML dictionary.")
|
raise InvalidConfigurationError("Theme file must be a YAML dictionary.")
|
||||||
|
|
||||||
|
# Support both direct styles and nested under 'theme' key
|
||||||
|
if "theme" in user_styles and isinstance(user_styles["theme"], dict):
|
||||||
|
user_styles = user_styles["theme"]
|
||||||
|
|
||||||
# Filter for valid styles only (prevent junk in config)
|
# Filter for valid styles only (prevent junk in config)
|
||||||
valid_styles = {k: v for k, v in user_styles.items() if k in STYLES}
|
valid_styles = {k: v for k, v in user_styles.items() if k in STYLES}
|
||||||
|
|
||||||
@@ -174,6 +178,10 @@ el.replaceWith(d);
|
|||||||
if not isinstance(user_styles, dict):
|
if not isinstance(user_styles, dict):
|
||||||
raise InvalidConfigurationError("Theme file must be a YAML dictionary.")
|
raise InvalidConfigurationError("Theme file must be a YAML dictionary.")
|
||||||
|
|
||||||
|
# Support both direct styles and nested under 'theme' key
|
||||||
|
if "theme" in user_styles and isinstance(user_styles["theme"], dict):
|
||||||
|
user_styles = user_styles["theme"]
|
||||||
|
|
||||||
# Filter for valid styles only (prevent junk in config)
|
# Filter for valid styles only (prevent junk in config)
|
||||||
valid_styles = {k: v for k, v in user_styles.items() if k in STYLES}
|
valid_styles = {k: v for k, v in user_styles.items() if k in STYLES}
|
||||||
|
|
||||||
@@ -311,7 +319,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.context_service API documentation</title>
|
<title>connpy.services.context_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -370,7 +370,7 @@ def current_context(self) -> str:
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.exceptions API documentation</title>
|
<title>connpy.services.exceptions API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -268,7 +268,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.execution_service API documentation</title>
|
<title>connpy.services.execution_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -64,11 +64,12 @@ el.replaceWith(d);
|
|||||||
commands: List[str],
|
commands: List[str],
|
||||||
variables: Optional[Dict[str, Any]] = None,
|
variables: Optional[Dict[str, Any]] = None,
|
||||||
parallel: int = 10,
|
parallel: int = 10,
|
||||||
timeout: int = 10,
|
timeout: int = 20,
|
||||||
folder: Optional[str] = None,
|
folder: Optional[str] = None,
|
||||||
prompt: Optional[str] = None,
|
prompt: Optional[str] = None,
|
||||||
on_node_complete: Optional[Callable] = None,
|
on_node_complete: Optional[Callable] = None,
|
||||||
logger: Optional[Callable] = None
|
logger: Optional[Callable] = None,
|
||||||
|
name: Optional[str] = None
|
||||||
) -> Dict[str, str]:
|
) -> Dict[str, str]:
|
||||||
|
|
||||||
"""Execute commands on a set of nodes."""
|
"""Execute commands on a set of nodes."""
|
||||||
@@ -92,7 +93,15 @@ el.replaceWith(d);
|
|||||||
logger=logger
|
logger=logger
|
||||||
)
|
)
|
||||||
|
|
||||||
return results
|
# Combine output and status for the caller
|
||||||
|
full_results = {}
|
||||||
|
for unique in results:
|
||||||
|
full_results[unique] = {
|
||||||
|
"output": results[unique],
|
||||||
|
"status": executor.status.get(unique, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
return full_results
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ConnpyError(f"Execution failed: {e}")
|
raise ConnpyError(f"Execution failed: {e}")
|
||||||
|
|
||||||
@@ -103,10 +112,12 @@ el.replaceWith(d);
|
|||||||
expected: List[str],
|
expected: List[str],
|
||||||
variables: Optional[Dict[str, Any]] = None,
|
variables: Optional[Dict[str, Any]] = None,
|
||||||
parallel: int = 10,
|
parallel: int = 10,
|
||||||
timeout: int = 10,
|
timeout: int = 20,
|
||||||
|
folder: Optional[str] = None,
|
||||||
prompt: Optional[str] = None,
|
prompt: Optional[str] = None,
|
||||||
on_node_complete: Optional[Callable] = None,
|
on_node_complete: Optional[Callable] = None,
|
||||||
logger: Optional[Callable] = None
|
logger: Optional[Callable] = None,
|
||||||
|
name: Optional[str] = None
|
||||||
) -> Dict[str, Dict[str, bool]]:
|
) -> Dict[str, Dict[str, bool]]:
|
||||||
|
|
||||||
"""Run commands and verify expected output on a set of nodes."""
|
"""Run commands and verify expected output on a set of nodes."""
|
||||||
@@ -125,6 +136,7 @@ el.replaceWith(d);
|
|||||||
vars=variables,
|
vars=variables,
|
||||||
parallel=parallel,
|
parallel=parallel,
|
||||||
timeout=timeout,
|
timeout=timeout,
|
||||||
|
folder=folder,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
on_complete=on_node_complete,
|
on_complete=on_node_complete,
|
||||||
logger=logger
|
logger=logger
|
||||||
@@ -146,37 +158,52 @@ el.replaceWith(d);
|
|||||||
|
|
||||||
return self.run_commands(nodes_filter, commands, parallel=parallel)
|
return self.run_commands(nodes_filter, commands, parallel=parallel)
|
||||||
|
|
||||||
def run_yaml_playbook(self, playbook_path: str, parallel: int = 10) -> Dict[str, Any]:
|
def run_yaml_playbook(self, playbook_data: str, parallel: int = 10) -> Dict[str, Any]:
|
||||||
"""Run a structured Connpy YAML automation playbook."""
|
"""Run a structured Connpy YAML automation playbook (from path or content)."""
|
||||||
if not os.path.exists(playbook_path):
|
playbook = None
|
||||||
raise ConnpyError(f"Playbook file not found: {playbook_path}")
|
if playbook_data.startswith("---YAML---\n"):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(playbook_path, "r") as f:
|
content = playbook_data[len("---YAML---\n"):]
|
||||||
|
playbook = yaml.load(content, Loader=yaml.FullLoader)
|
||||||
|
except Exception as e:
|
||||||
|
raise ConnpyError(f"Failed to parse YAML content: {e}")
|
||||||
|
else:
|
||||||
|
if not os.path.exists(playbook_data):
|
||||||
|
raise ConnpyError(f"Playbook file not found: {playbook_data}")
|
||||||
|
try:
|
||||||
|
with open(playbook_data, "r") as f:
|
||||||
playbook = yaml.load(f, Loader=yaml.FullLoader)
|
playbook = yaml.load(f, Loader=yaml.FullLoader)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ConnpyError(f"Failed to load playbook {playbook_path}: {e}")
|
raise ConnpyError(f"Failed to load playbook {playbook_data}: {e}")
|
||||||
|
|
||||||
# Basic validation
|
# Basic validation
|
||||||
if not isinstance(playbook, dict) or "nodes" not in playbook or "commands" not in playbook:
|
if not isinstance(playbook, dict) or "nodes" not in playbook or "commands" not in playbook:
|
||||||
raise ConnpyError("Invalid playbook format: missing 'nodes' or 'commands' keys.")
|
raise ConnpyError("Invalid playbook format: missing 'nodes' or 'commands' keys.")
|
||||||
|
|
||||||
action = playbook.get("action", "run")
|
action = playbook.get("action", "run")
|
||||||
|
options = playbook.get("options", {})
|
||||||
|
|
||||||
|
# Extract all fields similar to RunHandler.cli_run
|
||||||
|
exec_args = {
|
||||||
|
"nodes_filter": playbook["nodes"],
|
||||||
|
"commands": playbook["commands"],
|
||||||
|
"variables": playbook.get("variables"),
|
||||||
|
"parallel": options.get("parallel", parallel),
|
||||||
|
"timeout": playbook.get("timeout", options.get("timeout", 20)),
|
||||||
|
"prompt": options.get("prompt"),
|
||||||
|
"name": playbook.get("name", "Task")
|
||||||
|
}
|
||||||
|
|
||||||
|
# Map 'output' field to folder path if it's not stdout/null
|
||||||
|
output_cfg = playbook.get("output")
|
||||||
|
if output_cfg not in [None, "stdout"]:
|
||||||
|
exec_args["folder"] = output_cfg
|
||||||
|
|
||||||
if action == "run":
|
if action == "run":
|
||||||
return self.run_commands(
|
return self.run_commands(**exec_args)
|
||||||
nodes_filter=playbook["nodes"],
|
|
||||||
commands=playbook["commands"],
|
|
||||||
parallel=parallel,
|
|
||||||
timeout=playbook.get("timeout", 10)
|
|
||||||
)
|
|
||||||
elif action == "test":
|
elif action == "test":
|
||||||
return self.test_commands(
|
exec_args["expected"] = playbook.get("expected", [])
|
||||||
nodes_filter=playbook["nodes"],
|
return self.test_commands(**exec_args)
|
||||||
commands=playbook["commands"],
|
|
||||||
expected=playbook.get("expected", []),
|
|
||||||
parallel=parallel,
|
|
||||||
timeout=playbook.get("timeout", 10)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
raise ConnpyError(f"Unsupported playbook action: {action}")</code></pre>
|
raise ConnpyError(f"Unsupported playbook action: {action}")</code></pre>
|
||||||
</details>
|
</details>
|
||||||
@@ -217,7 +244,7 @@ el.replaceWith(d);
|
|||||||
<div class="desc"><p>Run a plain-text script containing one command per line.</p></div>
|
<div class="desc"><p>Run a plain-text script containing one command per line.</p></div>
|
||||||
</dd>
|
</dd>
|
||||||
<dt id="connpy.services.execution_service.ExecutionService.run_commands"><code class="name flex">
|
<dt id="connpy.services.execution_service.ExecutionService.run_commands"><code class="name flex">
|
||||||
<span>def <span class="ident">run_commands</span></span>(<span>self,<br>nodes_filter: str,<br>commands: List[str],<br>variables: Dict[str, Any] | None = None,<br>parallel: int = 10,<br>timeout: int = 10,<br>folder: str | None = None,<br>prompt: str | None = None,<br>on_node_complete: Callable | None = None,<br>logger: Callable | None = None) ‑> Dict[str, str]</span>
|
<span>def <span class="ident">run_commands</span></span>(<span>self,<br>nodes_filter: str,<br>commands: List[str],<br>variables: Dict[str, Any] | None = None,<br>parallel: int = 10,<br>timeout: int = 20,<br>folder: str | None = None,<br>prompt: str | None = None,<br>on_node_complete: Callable | None = None,<br>logger: Callable | None = None,<br>name: str | None = None) ‑> Dict[str, str]</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<details class="source">
|
<details class="source">
|
||||||
@@ -230,11 +257,12 @@ el.replaceWith(d);
|
|||||||
commands: List[str],
|
commands: List[str],
|
||||||
variables: Optional[Dict[str, Any]] = None,
|
variables: Optional[Dict[str, Any]] = None,
|
||||||
parallel: int = 10,
|
parallel: int = 10,
|
||||||
timeout: int = 10,
|
timeout: int = 20,
|
||||||
folder: Optional[str] = None,
|
folder: Optional[str] = None,
|
||||||
prompt: Optional[str] = None,
|
prompt: Optional[str] = None,
|
||||||
on_node_complete: Optional[Callable] = None,
|
on_node_complete: Optional[Callable] = None,
|
||||||
logger: Optional[Callable] = None
|
logger: Optional[Callable] = None,
|
||||||
|
name: Optional[str] = None
|
||||||
) -> Dict[str, str]:
|
) -> Dict[str, str]:
|
||||||
|
|
||||||
"""Execute commands on a set of nodes."""
|
"""Execute commands on a set of nodes."""
|
||||||
@@ -258,58 +286,81 @@ el.replaceWith(d);
|
|||||||
logger=logger
|
logger=logger
|
||||||
)
|
)
|
||||||
|
|
||||||
return results
|
# Combine output and status for the caller
|
||||||
|
full_results = {}
|
||||||
|
for unique in results:
|
||||||
|
full_results[unique] = {
|
||||||
|
"output": results[unique],
|
||||||
|
"status": executor.status.get(unique, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
return full_results
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ConnpyError(f"Execution failed: {e}")</code></pre>
|
raise ConnpyError(f"Execution failed: {e}")</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"><p>Execute commands on a set of nodes.</p></div>
|
<div class="desc"><p>Execute commands on a set of nodes.</p></div>
|
||||||
</dd>
|
</dd>
|
||||||
<dt id="connpy.services.execution_service.ExecutionService.run_yaml_playbook"><code class="name flex">
|
<dt id="connpy.services.execution_service.ExecutionService.run_yaml_playbook"><code class="name flex">
|
||||||
<span>def <span class="ident">run_yaml_playbook</span></span>(<span>self, playbook_path: str, parallel: int = 10) ‑> Dict[str, Any]</span>
|
<span>def <span class="ident">run_yaml_playbook</span></span>(<span>self, playbook_data: str, parallel: int = 10) ‑> Dict[str, Any]</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<details class="source">
|
<details class="source">
|
||||||
<summary>
|
<summary>
|
||||||
<span>Expand source code</span>
|
<span>Expand source code</span>
|
||||||
</summary>
|
</summary>
|
||||||
<pre><code class="python">def run_yaml_playbook(self, playbook_path: str, parallel: int = 10) -> Dict[str, Any]:
|
<pre><code class="python">def run_yaml_playbook(self, playbook_data: str, parallel: int = 10) -> Dict[str, Any]:
|
||||||
"""Run a structured Connpy YAML automation playbook."""
|
"""Run a structured Connpy YAML automation playbook (from path or content)."""
|
||||||
if not os.path.exists(playbook_path):
|
playbook = None
|
||||||
raise ConnpyError(f"Playbook file not found: {playbook_path}")
|
if playbook_data.startswith("---YAML---\n"):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(playbook_path, "r") as f:
|
content = playbook_data[len("---YAML---\n"):]
|
||||||
|
playbook = yaml.load(content, Loader=yaml.FullLoader)
|
||||||
|
except Exception as e:
|
||||||
|
raise ConnpyError(f"Failed to parse YAML content: {e}")
|
||||||
|
else:
|
||||||
|
if not os.path.exists(playbook_data):
|
||||||
|
raise ConnpyError(f"Playbook file not found: {playbook_data}")
|
||||||
|
try:
|
||||||
|
with open(playbook_data, "r") as f:
|
||||||
playbook = yaml.load(f, Loader=yaml.FullLoader)
|
playbook = yaml.load(f, Loader=yaml.FullLoader)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ConnpyError(f"Failed to load playbook {playbook_path}: {e}")
|
raise ConnpyError(f"Failed to load playbook {playbook_data}: {e}")
|
||||||
|
|
||||||
# Basic validation
|
# Basic validation
|
||||||
if not isinstance(playbook, dict) or "nodes" not in playbook or "commands" not in playbook:
|
if not isinstance(playbook, dict) or "nodes" not in playbook or "commands" not in playbook:
|
||||||
raise ConnpyError("Invalid playbook format: missing 'nodes' or 'commands' keys.")
|
raise ConnpyError("Invalid playbook format: missing 'nodes' or 'commands' keys.")
|
||||||
|
|
||||||
action = playbook.get("action", "run")
|
action = playbook.get("action", "run")
|
||||||
|
options = playbook.get("options", {})
|
||||||
|
|
||||||
|
# Extract all fields similar to RunHandler.cli_run
|
||||||
|
exec_args = {
|
||||||
|
"nodes_filter": playbook["nodes"],
|
||||||
|
"commands": playbook["commands"],
|
||||||
|
"variables": playbook.get("variables"),
|
||||||
|
"parallel": options.get("parallel", parallel),
|
||||||
|
"timeout": playbook.get("timeout", options.get("timeout", 20)),
|
||||||
|
"prompt": options.get("prompt"),
|
||||||
|
"name": playbook.get("name", "Task")
|
||||||
|
}
|
||||||
|
|
||||||
|
# Map 'output' field to folder path if it's not stdout/null
|
||||||
|
output_cfg = playbook.get("output")
|
||||||
|
if output_cfg not in [None, "stdout"]:
|
||||||
|
exec_args["folder"] = output_cfg
|
||||||
|
|
||||||
if action == "run":
|
if action == "run":
|
||||||
return self.run_commands(
|
return self.run_commands(**exec_args)
|
||||||
nodes_filter=playbook["nodes"],
|
|
||||||
commands=playbook["commands"],
|
|
||||||
parallel=parallel,
|
|
||||||
timeout=playbook.get("timeout", 10)
|
|
||||||
)
|
|
||||||
elif action == "test":
|
elif action == "test":
|
||||||
return self.test_commands(
|
exec_args["expected"] = playbook.get("expected", [])
|
||||||
nodes_filter=playbook["nodes"],
|
return self.test_commands(**exec_args)
|
||||||
commands=playbook["commands"],
|
|
||||||
expected=playbook.get("expected", []),
|
|
||||||
parallel=parallel,
|
|
||||||
timeout=playbook.get("timeout", 10)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
raise ConnpyError(f"Unsupported playbook action: {action}")</code></pre>
|
raise ConnpyError(f"Unsupported playbook action: {action}")</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"><p>Run a structured Connpy YAML automation playbook.</p></div>
|
<div class="desc"><p>Run a structured Connpy YAML automation playbook (from path or content).</p></div>
|
||||||
</dd>
|
</dd>
|
||||||
<dt id="connpy.services.execution_service.ExecutionService.test_commands"><code class="name flex">
|
<dt id="connpy.services.execution_service.ExecutionService.test_commands"><code class="name flex">
|
||||||
<span>def <span class="ident">test_commands</span></span>(<span>self,<br>nodes_filter: str,<br>commands: List[str],<br>expected: List[str],<br>variables: Dict[str, Any] | None = None,<br>parallel: int = 10,<br>timeout: int = 10,<br>prompt: str | None = None,<br>on_node_complete: Callable | None = None,<br>logger: Callable | None = None) ‑> Dict[str, Dict[str, bool]]</span>
|
<span>def <span class="ident">test_commands</span></span>(<span>self,<br>nodes_filter: str,<br>commands: List[str],<br>expected: List[str],<br>variables: Dict[str, Any] | None = None,<br>parallel: int = 10,<br>timeout: int = 20,<br>folder: str | None = None,<br>prompt: str | None = None,<br>on_node_complete: Callable | None = None,<br>logger: Callable | None = None,<br>name: str | None = None) ‑> Dict[str, Dict[str, bool]]</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<details class="source">
|
<details class="source">
|
||||||
@@ -323,10 +374,12 @@ el.replaceWith(d);
|
|||||||
expected: List[str],
|
expected: List[str],
|
||||||
variables: Optional[Dict[str, Any]] = None,
|
variables: Optional[Dict[str, Any]] = None,
|
||||||
parallel: int = 10,
|
parallel: int = 10,
|
||||||
timeout: int = 10,
|
timeout: int = 20,
|
||||||
|
folder: Optional[str] = None,
|
||||||
prompt: Optional[str] = None,
|
prompt: Optional[str] = None,
|
||||||
on_node_complete: Optional[Callable] = None,
|
on_node_complete: Optional[Callable] = None,
|
||||||
logger: Optional[Callable] = None
|
logger: Optional[Callable] = None,
|
||||||
|
name: Optional[str] = None
|
||||||
) -> Dict[str, Dict[str, bool]]:
|
) -> Dict[str, Dict[str, bool]]:
|
||||||
|
|
||||||
"""Run commands and verify expected output on a set of nodes."""
|
"""Run commands and verify expected output on a set of nodes."""
|
||||||
@@ -345,6 +398,7 @@ el.replaceWith(d);
|
|||||||
vars=variables,
|
vars=variables,
|
||||||
parallel=parallel,
|
parallel=parallel,
|
||||||
timeout=timeout,
|
timeout=timeout,
|
||||||
|
folder=folder,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
on_complete=on_node_complete,
|
on_complete=on_node_complete,
|
||||||
logger=logger
|
logger=logger
|
||||||
@@ -395,7 +449,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.import_export_service API documentation</title>
|
<title>connpy.services.import_export_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -73,13 +73,45 @@ el.replaceWith(d);
|
|||||||
def export_to_dict(self, folders=None):
|
def export_to_dict(self, folders=None):
|
||||||
"""Export nodes/folders to a dictionary."""
|
"""Export nodes/folders to a dictionary."""
|
||||||
if not folders:
|
if not folders:
|
||||||
return self.config._getallnodesfull(extract=False)
|
return deepcopy(self.config.connections)
|
||||||
else:
|
else:
|
||||||
# Validate folders exist
|
# Validate folders exist
|
||||||
for f in folders:
|
for f in folders:
|
||||||
if f != "@" and f not in self.config._getallfolders():
|
if f != "@" and f not in self.config._getallfolders():
|
||||||
raise NodeNotFoundError(f"Folder '{f}' not found.")
|
raise NodeNotFoundError(f"Folder '{f}' not found.")
|
||||||
return self.config._getallnodesfull(folders, extract=False)
|
|
||||||
|
flat = self.config._getallnodesfull(folders, extract=False)
|
||||||
|
nested = {}
|
||||||
|
for k, v in flat.items():
|
||||||
|
uniques = self.config._explode_unique(k)
|
||||||
|
if not uniques:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if "folder" in uniques and "subfolder" in uniques:
|
||||||
|
f_name = uniques["folder"]
|
||||||
|
s_name = uniques["subfolder"]
|
||||||
|
i_name = uniques["id"]
|
||||||
|
|
||||||
|
if f_name not in nested:
|
||||||
|
nested[f_name] = {"type": "folder"}
|
||||||
|
if s_name not in nested[f_name]:
|
||||||
|
nested[f_name][s_name] = {"type": "subfolder"}
|
||||||
|
|
||||||
|
nested[f_name][s_name][i_name] = v
|
||||||
|
|
||||||
|
elif "folder" in uniques:
|
||||||
|
f_name = uniques["folder"]
|
||||||
|
i_name = uniques["id"]
|
||||||
|
|
||||||
|
if f_name not in nested:
|
||||||
|
nested[f_name] = {"type": "folder"}
|
||||||
|
|
||||||
|
nested[f_name][i_name] = v
|
||||||
|
else:
|
||||||
|
i_name = uniques["id"]
|
||||||
|
nested[i_name] = v
|
||||||
|
|
||||||
|
return nested
|
||||||
|
|
||||||
def import_from_file(self, file_path):
|
def import_from_file(self, file_path):
|
||||||
"""Import nodes/folders from a YAML file."""
|
"""Import nodes/folders from a YAML file."""
|
||||||
@@ -98,28 +130,37 @@ el.replaceWith(d);
|
|||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
raise InvalidConfigurationError("Invalid import data format: expected a dictionary of nodes.")
|
raise InvalidConfigurationError("Invalid import data format: expected a dictionary of nodes.")
|
||||||
|
|
||||||
# Process imports
|
def _traverse_import(node_data, current_folder='', current_subfolder=''):
|
||||||
for k, v in data.items():
|
for k, v in node_data.items():
|
||||||
uniques = self.config._explode_unique(k)
|
if k == "type":
|
||||||
|
continue
|
||||||
|
if isinstance(v, dict):
|
||||||
|
node_type = v.get("type", "connection")
|
||||||
|
if node_type == "folder":
|
||||||
|
self.config._folder_add(folder=k)
|
||||||
|
_traverse_import(v, current_folder=k, current_subfolder='')
|
||||||
|
elif node_type == "subfolder":
|
||||||
|
self.config._folder_add(folder=current_folder, subfolder=k)
|
||||||
|
_traverse_import(v, current_folder=current_folder, current_subfolder=k)
|
||||||
|
elif node_type == "connection":
|
||||||
|
unique_id = k
|
||||||
|
if current_subfolder:
|
||||||
|
unique_id = f"{k}@{current_subfolder}@{current_folder}"
|
||||||
|
elif current_folder:
|
||||||
|
unique_id = f"{k}@{current_folder}"
|
||||||
|
self._validate_node_name(unique_id)
|
||||||
|
|
||||||
# Ensure folders exist
|
kwargs = deepcopy(v)
|
||||||
if "folder" in uniques:
|
kwargs['id'] = k
|
||||||
folder_name = f"@{uniques['folder']}"
|
kwargs['folder'] = current_folder
|
||||||
if folder_name not in self.config._getallfolders():
|
kwargs['subfolder'] = current_subfolder
|
||||||
folder_uniques = self.config._explode_unique(folder_name)
|
|
||||||
self.config._folder_add(**folder_uniques)
|
|
||||||
|
|
||||||
if "subfolder" in uniques:
|
self.config._connections_add(**kwargs)
|
||||||
sub_name = f"@{uniques['subfolder']}@{uniques['folder']}"
|
else:
|
||||||
if sub_name not in self.config._getallfolders():
|
# Invalid format skip
|
||||||
sub_uniques = self.config._explode_unique(sub_name)
|
pass
|
||||||
self.config._folder_add(**sub_uniques)
|
|
||||||
|
|
||||||
# Add node/connection
|
|
||||||
v.update(uniques)
|
|
||||||
self._validate_node_name(k)
|
|
||||||
self.config._connections_add(**v)
|
|
||||||
|
|
||||||
|
_traverse_import(data)
|
||||||
self.config._saveconfig(self.config.file)</code></pre>
|
self.config._saveconfig(self.config.file)</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"><p>Business logic for YAML/JSON inventory import and export.</p>
|
<div class="desc"><p>Business logic for YAML/JSON inventory import and export.</p>
|
||||||
@@ -146,13 +187,45 @@ el.replaceWith(d);
|
|||||||
<pre><code class="python">def export_to_dict(self, folders=None):
|
<pre><code class="python">def export_to_dict(self, folders=None):
|
||||||
"""Export nodes/folders to a dictionary."""
|
"""Export nodes/folders to a dictionary."""
|
||||||
if not folders:
|
if not folders:
|
||||||
return self.config._getallnodesfull(extract=False)
|
return deepcopy(self.config.connections)
|
||||||
else:
|
else:
|
||||||
# Validate folders exist
|
# Validate folders exist
|
||||||
for f in folders:
|
for f in folders:
|
||||||
if f != "@" and f not in self.config._getallfolders():
|
if f != "@" and f not in self.config._getallfolders():
|
||||||
raise NodeNotFoundError(f"Folder '{f}' not found.")
|
raise NodeNotFoundError(f"Folder '{f}' not found.")
|
||||||
return self.config._getallnodesfull(folders, extract=False)</code></pre>
|
|
||||||
|
flat = self.config._getallnodesfull(folders, extract=False)
|
||||||
|
nested = {}
|
||||||
|
for k, v in flat.items():
|
||||||
|
uniques = self.config._explode_unique(k)
|
||||||
|
if not uniques:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if "folder" in uniques and "subfolder" in uniques:
|
||||||
|
f_name = uniques["folder"]
|
||||||
|
s_name = uniques["subfolder"]
|
||||||
|
i_name = uniques["id"]
|
||||||
|
|
||||||
|
if f_name not in nested:
|
||||||
|
nested[f_name] = {"type": "folder"}
|
||||||
|
if s_name not in nested[f_name]:
|
||||||
|
nested[f_name][s_name] = {"type": "subfolder"}
|
||||||
|
|
||||||
|
nested[f_name][s_name][i_name] = v
|
||||||
|
|
||||||
|
elif "folder" in uniques:
|
||||||
|
f_name = uniques["folder"]
|
||||||
|
i_name = uniques["id"]
|
||||||
|
|
||||||
|
if f_name not in nested:
|
||||||
|
nested[f_name] = {"type": "folder"}
|
||||||
|
|
||||||
|
nested[f_name][i_name] = v
|
||||||
|
else:
|
||||||
|
i_name = uniques["id"]
|
||||||
|
nested[i_name] = v
|
||||||
|
|
||||||
|
return nested</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"><p>Export nodes/folders to a dictionary.</p></div>
|
<div class="desc"><p>Export nodes/folders to a dictionary.</p></div>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -191,28 +264,37 @@ el.replaceWith(d);
|
|||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
raise InvalidConfigurationError("Invalid import data format: expected a dictionary of nodes.")
|
raise InvalidConfigurationError("Invalid import data format: expected a dictionary of nodes.")
|
||||||
|
|
||||||
# Process imports
|
def _traverse_import(node_data, current_folder='', current_subfolder=''):
|
||||||
for k, v in data.items():
|
for k, v in node_data.items():
|
||||||
uniques = self.config._explode_unique(k)
|
if k == "type":
|
||||||
|
continue
|
||||||
|
if isinstance(v, dict):
|
||||||
|
node_type = v.get("type", "connection")
|
||||||
|
if node_type == "folder":
|
||||||
|
self.config._folder_add(folder=k)
|
||||||
|
_traverse_import(v, current_folder=k, current_subfolder='')
|
||||||
|
elif node_type == "subfolder":
|
||||||
|
self.config._folder_add(folder=current_folder, subfolder=k)
|
||||||
|
_traverse_import(v, current_folder=current_folder, current_subfolder=k)
|
||||||
|
elif node_type == "connection":
|
||||||
|
unique_id = k
|
||||||
|
if current_subfolder:
|
||||||
|
unique_id = f"{k}@{current_subfolder}@{current_folder}"
|
||||||
|
elif current_folder:
|
||||||
|
unique_id = f"{k}@{current_folder}"
|
||||||
|
self._validate_node_name(unique_id)
|
||||||
|
|
||||||
# Ensure folders exist
|
kwargs = deepcopy(v)
|
||||||
if "folder" in uniques:
|
kwargs['id'] = k
|
||||||
folder_name = f"@{uniques['folder']}"
|
kwargs['folder'] = current_folder
|
||||||
if folder_name not in self.config._getallfolders():
|
kwargs['subfolder'] = current_subfolder
|
||||||
folder_uniques = self.config._explode_unique(folder_name)
|
|
||||||
self.config._folder_add(**folder_uniques)
|
|
||||||
|
|
||||||
if "subfolder" in uniques:
|
self.config._connections_add(**kwargs)
|
||||||
sub_name = f"@{uniques['subfolder']}@{uniques['folder']}"
|
else:
|
||||||
if sub_name not in self.config._getallfolders():
|
# Invalid format skip
|
||||||
sub_uniques = self.config._explode_unique(sub_name)
|
pass
|
||||||
self.config._folder_add(**sub_uniques)
|
|
||||||
|
|
||||||
# Add node/connection
|
|
||||||
v.update(uniques)
|
|
||||||
self._validate_node_name(k)
|
|
||||||
self.config._connections_add(**v)
|
|
||||||
|
|
||||||
|
_traverse_import(data)
|
||||||
self.config._saveconfig(self.config.file)</code></pre>
|
self.config._saveconfig(self.config.file)</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"><p>Import nodes/folders from a dictionary.</p></div>
|
<div class="desc"><p>Import nodes/folders from a dictionary.</p></div>
|
||||||
@@ -279,7 +361,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+737
-112
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.node_service API documentation</title>
|
<title>connpy.services.node_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -117,6 +117,12 @@ el.replaceWith(d);
|
|||||||
case_sensitive = self.config.config.get("case", False)
|
case_sensitive = self.config.config.get("case", False)
|
||||||
|
|
||||||
if filter_str:
|
if filter_str:
|
||||||
|
if filter_str.startswith("@"):
|
||||||
|
if not case_sensitive:
|
||||||
|
folders = [f for f in folders if f.lower() == filter_str.lower()]
|
||||||
|
else:
|
||||||
|
folders = [f for f in folders if f == filter_str]
|
||||||
|
else:
|
||||||
flags = re.IGNORECASE if not case_sensitive else 0
|
flags = re.IGNORECASE if not case_sensitive else 0
|
||||||
folders = [f for f in folders if re.search(filter_str, f, flags)]
|
folders = [f for f in folders if re.search(filter_str, f, flags)]
|
||||||
return folders
|
return folders
|
||||||
@@ -139,8 +145,15 @@ el.replaceWith(d);
|
|||||||
"""Generate and update the internal nodes cache."""
|
"""Generate and update the internal nodes cache."""
|
||||||
self.config._generate_nodes_cache(nodes=nodes, folders=folders, profiles=profiles)
|
self.config._generate_nodes_cache(nodes=nodes, folders=folders, profiles=profiles)
|
||||||
|
|
||||||
def validate_parent_folder(self, unique_id):
|
def validate_parent_folder(self, unique_id, is_folder=False):
|
||||||
"""Check if parent folder exists for a given node unique ID."""
|
"""Check if parent folder exists for a given node unique ID."""
|
||||||
|
if is_folder:
|
||||||
|
uniques = self.config._explode_unique(unique_id)
|
||||||
|
if uniques and "subfolder" in uniques and "folder" in uniques:
|
||||||
|
parent_folder = f"@{uniques['folder']}"
|
||||||
|
if parent_folder not in self.config._getallfolders():
|
||||||
|
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||||
|
else:
|
||||||
node_folder = unique_id.partition("@")[2]
|
node_folder = unique_id.partition("@")[2]
|
||||||
if node_folder:
|
if node_folder:
|
||||||
parent_folder = f"@{node_folder}"
|
parent_folder = f"@{node_folder}"
|
||||||
@@ -165,7 +178,7 @@ el.replaceWith(d);
|
|||||||
|
|
||||||
# Check if parent folder exists when creating a subfolder
|
# Check if parent folder exists when creating a subfolder
|
||||||
if "subfolder" in uniques:
|
if "subfolder" in uniques:
|
||||||
self.validate_parent_folder(unique_id)
|
self.validate_parent_folder(unique_id, is_folder=True)
|
||||||
|
|
||||||
self.config._folder_add(**uniques)
|
self.config._folder_add(**uniques)
|
||||||
self.config._saveconfig(self.config.file)
|
self.config._saveconfig(self.config.file)
|
||||||
@@ -347,7 +360,7 @@ el.replaceWith(d);
|
|||||||
|
|
||||||
# Check if parent folder exists when creating a subfolder
|
# Check if parent folder exists when creating a subfolder
|
||||||
if "subfolder" in uniques:
|
if "subfolder" in uniques:
|
||||||
self.validate_parent_folder(unique_id)
|
self.validate_parent_folder(unique_id, is_folder=True)
|
||||||
|
|
||||||
self.config._folder_add(**uniques)
|
self.config._folder_add(**uniques)
|
||||||
self.config._saveconfig(self.config.file)
|
self.config._saveconfig(self.config.file)
|
||||||
@@ -563,6 +576,12 @@ el.replaceWith(d);
|
|||||||
case_sensitive = self.config.config.get("case", False)
|
case_sensitive = self.config.config.get("case", False)
|
||||||
|
|
||||||
if filter_str:
|
if filter_str:
|
||||||
|
if filter_str.startswith("@"):
|
||||||
|
if not case_sensitive:
|
||||||
|
folders = [f for f in folders if f.lower() == filter_str.lower()]
|
||||||
|
else:
|
||||||
|
folders = [f for f in folders if f == filter_str]
|
||||||
|
else:
|
||||||
flags = re.IGNORECASE if not case_sensitive else 0
|
flags = re.IGNORECASE if not case_sensitive else 0
|
||||||
folders = [f for f in folders if re.search(filter_str, f, flags)]
|
folders = [f for f in folders if re.search(filter_str, f, flags)]
|
||||||
return folders</code></pre>
|
return folders</code></pre>
|
||||||
@@ -693,15 +712,22 @@ el.replaceWith(d);
|
|||||||
<div class="desc"><p>Explicitly update an existing node.</p></div>
|
<div class="desc"><p>Explicitly update an existing node.</p></div>
|
||||||
</dd>
|
</dd>
|
||||||
<dt id="connpy.services.node_service.NodeService.validate_parent_folder"><code class="name flex">
|
<dt id="connpy.services.node_service.NodeService.validate_parent_folder"><code class="name flex">
|
||||||
<span>def <span class="ident">validate_parent_folder</span></span>(<span>self, unique_id)</span>
|
<span>def <span class="ident">validate_parent_folder</span></span>(<span>self, unique_id, is_folder=False)</span>
|
||||||
</code></dt>
|
</code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<details class="source">
|
<details class="source">
|
||||||
<summary>
|
<summary>
|
||||||
<span>Expand source code</span>
|
<span>Expand source code</span>
|
||||||
</summary>
|
</summary>
|
||||||
<pre><code class="python">def validate_parent_folder(self, unique_id):
|
<pre><code class="python">def validate_parent_folder(self, unique_id, is_folder=False):
|
||||||
"""Check if parent folder exists for a given node unique ID."""
|
"""Check if parent folder exists for a given node unique ID."""
|
||||||
|
if is_folder:
|
||||||
|
uniques = self.config._explode_unique(unique_id)
|
||||||
|
if uniques and "subfolder" in uniques and "folder" in uniques:
|
||||||
|
parent_folder = f"@{uniques['folder']}"
|
||||||
|
if parent_folder not in self.config._getallfolders():
|
||||||
|
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||||
|
else:
|
||||||
node_folder = unique_id.partition("@")[2]
|
node_folder = unique_id.partition("@")[2]
|
||||||
if node_folder:
|
if node_folder:
|
||||||
parent_folder = f"@{node_folder}"
|
parent_folder = f"@{node_folder}"
|
||||||
@@ -760,7 +786,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.plugin_service API documentation</title>
|
<title>connpy.services.plugin_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -284,14 +284,26 @@ el.replaceWith(d);
|
|||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
|
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
buf = io.StringIO()
|
import queue
|
||||||
|
import threading
|
||||||
|
|
||||||
|
q = queue.Queue()
|
||||||
|
|
||||||
|
class QueueIO(io.StringIO):
|
||||||
|
def write(self, s):
|
||||||
|
q.put(s)
|
||||||
|
return len(s)
|
||||||
|
def flush(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
buf = QueueIO()
|
||||||
old_console = printer._get_console()
|
old_console = printer._get_console()
|
||||||
old_err_console = printer._get_err_console()
|
old_err_console = printer._get_err_console()
|
||||||
|
|
||||||
|
def run_plugin():
|
||||||
printer.set_thread_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
printer.set_thread_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
||||||
printer.set_thread_err_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
printer.set_thread_err_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
||||||
printer.set_thread_stream(buf)
|
printer.set_thread_stream(buf)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if hasattr(module, "Entrypoint"):
|
if hasattr(module, "Entrypoint"):
|
||||||
module.Entrypoint(args, parser, app)
|
module.Entrypoint(args, parser, app)
|
||||||
@@ -303,9 +315,16 @@ el.replaceWith(d);
|
|||||||
printer.set_thread_console(old_console)
|
printer.set_thread_console(old_console)
|
||||||
printer.set_thread_err_console(old_err_console)
|
printer.set_thread_err_console(old_err_console)
|
||||||
printer.set_thread_stream(None)
|
printer.set_thread_stream(None)
|
||||||
|
q.put(None)
|
||||||
|
|
||||||
for line in buf.getvalue().splitlines(keepends=True):
|
t = threading.Thread(target=run_plugin, daemon=True)
|
||||||
yield line</code></pre>
|
t.start()
|
||||||
|
|
||||||
|
while True:
|
||||||
|
item = q.get()
|
||||||
|
if item is None:
|
||||||
|
break
|
||||||
|
yield item</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"><p>Business logic for enabling, disabling, and listing plugins.</p>
|
<div class="desc"><p>Business logic for enabling, disabling, and listing plugins.</p>
|
||||||
<p>Initialize the service.</p>
|
<p>Initialize the service.</p>
|
||||||
@@ -560,14 +579,26 @@ el.replaceWith(d);
|
|||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
|
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
buf = io.StringIO()
|
import queue
|
||||||
|
import threading
|
||||||
|
|
||||||
|
q = queue.Queue()
|
||||||
|
|
||||||
|
class QueueIO(io.StringIO):
|
||||||
|
def write(self, s):
|
||||||
|
q.put(s)
|
||||||
|
return len(s)
|
||||||
|
def flush(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
buf = QueueIO()
|
||||||
old_console = printer._get_console()
|
old_console = printer._get_console()
|
||||||
old_err_console = printer._get_err_console()
|
old_err_console = printer._get_err_console()
|
||||||
|
|
||||||
|
def run_plugin():
|
||||||
printer.set_thread_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
printer.set_thread_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
||||||
printer.set_thread_err_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
printer.set_thread_err_console(Console(file=buf, theme=printer.connpy_theme, force_terminal=True))
|
||||||
printer.set_thread_stream(buf)
|
printer.set_thread_stream(buf)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if hasattr(module, "Entrypoint"):
|
if hasattr(module, "Entrypoint"):
|
||||||
module.Entrypoint(args, parser, app)
|
module.Entrypoint(args, parser, app)
|
||||||
@@ -579,9 +610,16 @@ el.replaceWith(d);
|
|||||||
printer.set_thread_console(old_console)
|
printer.set_thread_console(old_console)
|
||||||
printer.set_thread_err_console(old_err_console)
|
printer.set_thread_err_console(old_err_console)
|
||||||
printer.set_thread_stream(None)
|
printer.set_thread_stream(None)
|
||||||
|
q.put(None)
|
||||||
|
|
||||||
for line in buf.getvalue().splitlines(keepends=True):
|
t = threading.Thread(target=run_plugin, daemon=True)
|
||||||
yield line</code></pre>
|
t.start()
|
||||||
|
|
||||||
|
while True:
|
||||||
|
item = q.get()
|
||||||
|
if item is None:
|
||||||
|
break
|
||||||
|
yield item</code></pre>
|
||||||
</details>
|
</details>
|
||||||
<div class="desc"></div>
|
<div class="desc"></div>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -671,7 +709,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.profile_service API documentation</title>
|
<title>connpy.services.profile_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -429,7 +429,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.provider API documentation</title>
|
<title>connpy.services.provider API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -164,7 +164,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.sync_service API documentation</title>
|
<title>connpy.services.sync_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -964,7 +964,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.services.system_service API documentation</title>
|
<title>connpy.services.system_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -325,7 +325,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.conftest API documentation</title>
|
<title>connpy.tests.conftest API documentation</title>
|
||||||
<meta name="description" content="Shared fixtures for connpy tests …">
|
<meta name="description" content="Shared fixtures for connpy tests …">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -258,7 +258,7 @@ def tmp_config_dir(tmp_path):
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests API documentation</title>
|
<title>connpy.tests API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -48,6 +48,10 @@ el.replaceWith(d);
|
|||||||
<dd>
|
<dd>
|
||||||
<div class="desc"><p>Tests for connpy.ai module.</p></div>
|
<div class="desc"><p>Tests for connpy.ai module.</p></div>
|
||||||
</dd>
|
</dd>
|
||||||
|
<dt><code class="name"><a title="connpy.tests.test_ai_copilot" href="test_ai_copilot.html">connpy.tests.test_ai_copilot</a></code></dt>
|
||||||
|
<dd>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
<dt><code class="name"><a title="connpy.tests.test_capture" href="test_capture.html">connpy.tests.test_capture</a></code></dt>
|
<dt><code class="name"><a title="connpy.tests.test_capture" href="test_capture.html">connpy.tests.test_capture</a></code></dt>
|
||||||
<dd>
|
<dd>
|
||||||
<div class="desc"><p>Tests for connpy.core_plugins.capture</p></div>
|
<div class="desc"><p>Tests for connpy.core_plugins.capture</p></div>
|
||||||
@@ -131,6 +135,7 @@ el.replaceWith(d);
|
|||||||
<ul>
|
<ul>
|
||||||
<li><code><a title="connpy.tests.conftest" href="conftest.html">connpy.tests.conftest</a></code></li>
|
<li><code><a title="connpy.tests.conftest" href="conftest.html">connpy.tests.conftest</a></code></li>
|
||||||
<li><code><a title="connpy.tests.test_ai" href="test_ai.html">connpy.tests.test_ai</a></code></li>
|
<li><code><a title="connpy.tests.test_ai" href="test_ai.html">connpy.tests.test_ai</a></code></li>
|
||||||
|
<li><code><a title="connpy.tests.test_ai_copilot" href="test_ai_copilot.html">connpy.tests.test_ai_copilot</a></code></li>
|
||||||
<li><code><a title="connpy.tests.test_capture" href="test_capture.html">connpy.tests.test_capture</a></code></li>
|
<li><code><a title="connpy.tests.test_capture" href="test_capture.html">connpy.tests.test_capture</a></code></li>
|
||||||
<li><code><a title="connpy.tests.test_completion" href="test_completion.html">connpy.tests.test_completion</a></code></li>
|
<li><code><a title="connpy.tests.test_completion" href="test_completion.html">connpy.tests.test_completion</a></code></li>
|
||||||
<li><code><a title="connpy.tests.test_configfile" href="test_configfile.html">connpy.tests.test_configfile</a></code></li>
|
<li><code><a title="connpy.tests.test_configfile" href="test_configfile.html">connpy.tests.test_configfile</a></code></li>
|
||||||
@@ -152,7 +157,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_ai API documentation</title>
|
<title>connpy.tests.test_ai API documentation</title>
|
||||||
<meta name="description" content="Tests for connpy.ai module.">
|
<meta name="description" content="Tests for connpy.ai module.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -1731,7 +1731,7 @@ def myai(self, ai_config, mock_litellm):
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,315 @@
|
|||||||
|
<!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.tests.test_ai_copilot API documentation</title>
|
||||||
|
<meta name="description" content="">
|
||||||
|
<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">Module <code>connpy.tests.test_ai_copilot</code></h1>
|
||||||
|
</header>
|
||||||
|
<section id="section-intro">
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.tests.test_ai_copilot.mock_acompletion"><code class="name flex">
|
||||||
|
<span>def <span class="ident">mock_acompletion</span></span>(<span>)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">@pytest.fixture
|
||||||
|
def mock_acompletion():
|
||||||
|
# Patch acompletion inside connpy.ai.aask_copilot
|
||||||
|
with patch('litellm.acompletion') as mock:
|
||||||
|
yield mock</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tests.test_ai_copilot.test_aask_copilot_fallback"><code class="name flex">
|
||||||
|
<span>def <span class="ident">test_aask_copilot_fallback</span></span>(<span>mock_acompletion)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def test_aask_copilot_fallback(mock_acompletion):
|
||||||
|
agent = ai(DummyConfig())
|
||||||
|
|
||||||
|
# Setup mock response for streaming
|
||||||
|
class MockDelta:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.content = content
|
||||||
|
|
||||||
|
class MockChoice:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.delta = MockDelta(content)
|
||||||
|
|
||||||
|
class MockChunk:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.choices = [MockChoice(content)]
|
||||||
|
|
||||||
|
async def mock_ac(*args, **kwargs):
|
||||||
|
return MockAsyncIterator([
|
||||||
|
MockChunk("Here is some text response instead of tool call.")
|
||||||
|
])
|
||||||
|
|
||||||
|
mock_acompletion.side_effect = mock_ac
|
||||||
|
|
||||||
|
async def run_test():
|
||||||
|
return await agent.aask_copilot("Router#", "What do I do?")
|
||||||
|
|
||||||
|
result = asyncio.run(run_test())
|
||||||
|
|
||||||
|
if result["error"]:
|
||||||
|
print(f"ERROR OCCURRED: {result['error']}")
|
||||||
|
|
||||||
|
assert result["error"] is None
|
||||||
|
assert result["guide"] == "Here is some text response instead of tool call."
|
||||||
|
assert result["risk_level"] == "low"</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tests.test_ai_copilot.test_aask_copilot_tool_call"><code class="name flex">
|
||||||
|
<span>def <span class="ident">test_aask_copilot_tool_call</span></span>(<span>mock_acompletion)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def test_aask_copilot_tool_call(mock_acompletion):
|
||||||
|
agent = ai(DummyConfig())
|
||||||
|
|
||||||
|
# Setup mock response for streaming
|
||||||
|
class MockDelta:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.content = content
|
||||||
|
|
||||||
|
class MockChoice:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.delta = MockDelta(content)
|
||||||
|
|
||||||
|
class MockChunk:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.choices = [MockChoice(content)]
|
||||||
|
|
||||||
|
# acompletion is awaited and returns an async iterator
|
||||||
|
async def mock_ac(*args, **kwargs):
|
||||||
|
return MockAsyncIterator([
|
||||||
|
MockChunk("<guide>Check the interfaces and running config.</guide>"),
|
||||||
|
MockChunk("<commands>\nshow ip int br\nshow run\n</commands>"),
|
||||||
|
MockChunk("<risk>low</risk>")
|
||||||
|
])
|
||||||
|
|
||||||
|
mock_acompletion.side_effect = mock_ac
|
||||||
|
|
||||||
|
async def run_test():
|
||||||
|
return await agent.aask_copilot("Router#", "What do I do?")
|
||||||
|
|
||||||
|
result = asyncio.run(run_test())
|
||||||
|
|
||||||
|
if result["error"]:
|
||||||
|
print(f"ERROR OCCURRED: {result['error']}")
|
||||||
|
|
||||||
|
assert result["error"] is None
|
||||||
|
assert result["guide"] == "Check the interfaces and running config."
|
||||||
|
assert result["risk_level"] == "low"
|
||||||
|
assert result["commands"] == ["show ip int br", "show run"]</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tests.test_ai_copilot.test_ingress_task_interception"><code class="name flex">
|
||||||
|
<span>def <span class="ident">test_ingress_task_interception</span></span>(<span>)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def test_ingress_task_interception():
|
||||||
|
async def run_test():
|
||||||
|
c = node("test_node", "1.2.3.4")
|
||||||
|
c.mylog = MagicMock()
|
||||||
|
c.mylog.getvalue.return_value = b"Some session log"
|
||||||
|
c.unique = "test_node"
|
||||||
|
c.host = "1.2.3.4"
|
||||||
|
c.tags = {"os": "cisco_ios"}
|
||||||
|
|
||||||
|
class MockStream:
|
||||||
|
def __init__(self):
|
||||||
|
self.data = [b"a", b"b", b"\x00", b"c", b""]
|
||||||
|
async def read(self):
|
||||||
|
if self.data:
|
||||||
|
return self.data.pop(0)
|
||||||
|
return b""
|
||||||
|
def setup(self, resize_callback):
|
||||||
|
pass
|
||||||
|
|
||||||
|
stream = MockStream()
|
||||||
|
|
||||||
|
called_copilot = False
|
||||||
|
async def mock_handler(buffer, node_info, s, child_fd):
|
||||||
|
nonlocal called_copilot
|
||||||
|
called_copilot = True
|
||||||
|
assert buffer == "Some session log"
|
||||||
|
assert node_info["os"] == "cisco_ios"
|
||||||
|
|
||||||
|
c.child = MagicMock()
|
||||||
|
c.child.child_fd = 123
|
||||||
|
c.child.after = b""
|
||||||
|
c.child.buffer = b""
|
||||||
|
|
||||||
|
async def mock_ingress():
|
||||||
|
while True:
|
||||||
|
data = await stream.read()
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
|
||||||
|
if mock_handler and b'\x00' in data:
|
||||||
|
buffer = c.mylog.getvalue().decode()
|
||||||
|
node_info = {"name": getattr(c, 'unique', 'unknown'), "host": getattr(c, 'host', 'unknown')}
|
||||||
|
if isinstance(getattr(c, 'tags', None), dict):
|
||||||
|
node_info["os"] = c.tags.get("os", "unknown")
|
||||||
|
await mock_handler(buffer, node_info, stream, c.child.child_fd)
|
||||||
|
continue
|
||||||
|
|
||||||
|
await mock_ingress()
|
||||||
|
assert called_copilot
|
||||||
|
|
||||||
|
asyncio.run(run_test())</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tests.test_ai_copilot.test_logclean_ansi"><code class="name flex">
|
||||||
|
<span>def <span class="ident">test_logclean_ansi</span></span>(<span>)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def test_logclean_ansi():
|
||||||
|
c = node("test_node", "1.2.3.4")
|
||||||
|
raw = "Router#\x1b[K\x1b[m show ip"
|
||||||
|
clean = c._logclean(raw, var=True)
|
||||||
|
assert "\x1b" not in clean</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.tests.test_ai_copilot.DummyConfig"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">DummyConfig</span></span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">class DummyConfig:
|
||||||
|
def __init__(self):
|
||||||
|
self.config = {"ai": {"engineer_api_key": "test_key", "engineer_model": "test_model"}}
|
||||||
|
self.defaultdir = "/tmp"</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tests.test_ai_copilot.MockAsyncIterator"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">MockAsyncIterator</span></span>
|
||||||
|
<span>(</span><span>items)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">class MockAsyncIterator:
|
||||||
|
def __init__(self, items):
|
||||||
|
self.items = items
|
||||||
|
def __aiter__(self):
|
||||||
|
return self
|
||||||
|
async def __anext__(self):
|
||||||
|
if not self.items:
|
||||||
|
raise StopAsyncIteration
|
||||||
|
return self.items.pop(0)</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
</article>
|
||||||
|
<nav id="sidebar">
|
||||||
|
<div class="toc">
|
||||||
|
<ul></ul>
|
||||||
|
</div>
|
||||||
|
<ul id="index">
|
||||||
|
<li><h3>Super-module</h3>
|
||||||
|
<ul>
|
||||||
|
<li><code><a title="connpy.tests" href="index.html">connpy.tests</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.tests.test_ai_copilot.mock_acompletion" href="#connpy.tests.test_ai_copilot.mock_acompletion">mock_acompletion</a></code></li>
|
||||||
|
<li><code><a title="connpy.tests.test_ai_copilot.test_aask_copilot_fallback" href="#connpy.tests.test_ai_copilot.test_aask_copilot_fallback">test_aask_copilot_fallback</a></code></li>
|
||||||
|
<li><code><a title="connpy.tests.test_ai_copilot.test_aask_copilot_tool_call" href="#connpy.tests.test_ai_copilot.test_aask_copilot_tool_call">test_aask_copilot_tool_call</a></code></li>
|
||||||
|
<li><code><a title="connpy.tests.test_ai_copilot.test_ingress_task_interception" href="#connpy.tests.test_ai_copilot.test_ingress_task_interception">test_ingress_task_interception</a></code></li>
|
||||||
|
<li><code><a title="connpy.tests.test_ai_copilot.test_logclean_ansi" href="#connpy.tests.test_ai_copilot.test_logclean_ansi">test_logclean_ansi</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.tests.test_ai_copilot.DummyConfig" href="#connpy.tests.test_ai_copilot.DummyConfig">DummyConfig</a></code></h4>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.tests.test_ai_copilot.MockAsyncIterator" href="#connpy.tests.test_ai_copilot.MockAsyncIterator">MockAsyncIterator</a></code></h4>
|
||||||
|
</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>
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_capture API documentation</title>
|
<title>connpy.tests.test_capture API documentation</title>
|
||||||
<meta name="description" content="Tests for connpy.core_plugins.capture">
|
<meta name="description" content="Tests for connpy.core_plugins.capture">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -245,7 +245,7 @@ def mock_connapp():
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_completion API documentation</title>
|
<title>connpy.tests.test_completion API documentation</title>
|
||||||
<meta name="description" content="Tests for connpy.completion module.">
|
<meta name="description" content="Tests for connpy.completion module.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -257,7 +257,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_configfile API documentation</title>
|
<title>connpy.tests.test_configfile API documentation</title>
|
||||||
<meta name="description" content="Tests for connpy.configfile module.">
|
<meta name="description" content="Tests for connpy.configfile module.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -2005,7 +2005,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_connapp API documentation</title>
|
<title>connpy.tests.test_connapp API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -699,7 +699,7 @@ def test_run(mock_run_commands, app):
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_core API documentation</title>
|
<title>connpy.tests.test_core API documentation</title>
|
||||||
<meta name="description" content="Tests for connpy.core module — node and nodes classes.">
|
<meta name="description" content="Tests for connpy.core module — node and nodes classes.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -1369,7 +1369,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_execution_service API documentation</title>
|
<title>connpy.tests.test_execution_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -142,7 +142,7 @@ Regression: ExecutionService.test_commands currently ignores on_node_complete.</
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_grpc_layer API documentation</title>
|
<title>connpy.tests.test_grpc_layer API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -581,8 +581,8 @@ def test_interact_node_uses_passed_name(self, mock_node, servicer):
|
|||||||
|
|
||||||
mock_resp = MagicMock()
|
mock_resp = MagicMock()
|
||||||
mock_resp.success = True
|
mock_resp.success = True
|
||||||
|
mock_resp.stdout_data = b''
|
||||||
stub.stub.interact_node.return_value = iter([mock_resp])
|
stub.stub.interact_node.return_value = iter([mock_resp])
|
||||||
|
|
||||||
with patch("connpy.printer.success") as mock_success:
|
with patch("connpy.printer.success") as mock_success:
|
||||||
with patch("sys.stdin.fileno", return_value=0):
|
with patch("sys.stdin.fileno", return_value=0):
|
||||||
mock_select.return_value = ([], [], [])
|
mock_select.return_value = ([], [], [])
|
||||||
@@ -626,8 +626,8 @@ def test_connect_dynamic_msg_formatting_ssm(self, mock_select, mock_read, mock_s
|
|||||||
|
|
||||||
mock_resp = MagicMock()
|
mock_resp = MagicMock()
|
||||||
mock_resp.success = True
|
mock_resp.success = True
|
||||||
|
mock_resp.stdout_data = b''
|
||||||
stub.stub.interact_node.return_value = iter([mock_resp])
|
stub.stub.interact_node.return_value = iter([mock_resp])
|
||||||
|
|
||||||
with patch("connpy.printer.success") as mock_success:
|
with patch("connpy.printer.success") as mock_success:
|
||||||
with patch("sys.stdin.fileno", return_value=0):
|
with patch("sys.stdin.fileno", return_value=0):
|
||||||
mock_select.return_value = ([], [], [])
|
mock_select.return_value = ([], [], [])
|
||||||
@@ -709,7 +709,7 @@ def test_connect_dynamic_msg_formatting_ssm(self, mock_select, mock_read, mock_s
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_hooks API documentation</title>
|
<title>connpy.tests.test_hooks API documentation</title>
|
||||||
<meta name="description" content="Tests for connpy.hooks module — MethodHook and ClassHook.">
|
<meta name="description" content="Tests for connpy.hooks module — MethodHook and ClassHook.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -673,7 +673,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_node_service API documentation</title>
|
<title>connpy.tests.test_node_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -178,7 +178,7 @@ Regression: connapp._mod calls add_node instead of update_node.</p></div>
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_plugins API documentation</title>
|
<title>connpy.tests.test_plugins API documentation</title>
|
||||||
<meta name="description" content="Tests for connpy.plugins module.">
|
<meta name="description" content="Tests for connpy.plugins module.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -917,7 +917,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_printer API documentation</title>
|
<title>connpy.tests.test_printer API documentation</title>
|
||||||
<meta name="description" content="Tests for connpy.printer module.">
|
<meta name="description" content="Tests for connpy.printer module.">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -459,7 +459,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_printer_concurrency API documentation</title>
|
<title>connpy.tests.test_printer_concurrency API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -148,7 +148,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_profile_service API documentation</title>
|
<title>connpy.tests.test_profile_service API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -192,7 +192,7 @@ Regression: ProfileService currently doesn't resolve inheritance within profiles
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_provider API documentation</title>
|
<title>connpy.tests.test_provider API documentation</title>
|
||||||
<meta name="description" content="">
|
<meta name="description" content="">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -139,7 +139,7 @@ el.replaceWith(d);
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||||
<meta name="generator" content="pdoc3 0.11.6">
|
<meta name="generator" content="pdoc3 0.11.5">
|
||||||
<title>connpy.tests.test_sync API documentation</title>
|
<title>connpy.tests.test_sync API documentation</title>
|
||||||
<meta name="description" content="Tests for connpy.services.sync_service">
|
<meta name="description" content="Tests for connpy.services.sync_service">
|
||||||
<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/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||||
@@ -354,7 +354,7 @@ def test_perform_restore(self, mock_remove, mock_dirname, mock_exists, MockZipFi
|
|||||||
</nav>
|
</nav>
|
||||||
</main>
|
</main>
|
||||||
<footer id="footer">
|
<footer id="footer">
|
||||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
<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>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,551 @@
|
|||||||
|
<!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.tunnels API documentation</title>
|
||||||
|
<meta name="description" content="">
|
||||||
|
<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">Module <code>connpy.tunnels</code></h1>
|
||||||
|
</header>
|
||||||
|
<section id="section-intro">
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.tunnels.LocalStream"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">LocalStream</span></span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">class LocalStream:
|
||||||
|
"""
|
||||||
|
Asynchronous stream wrapper for local stdin/stdout.
|
||||||
|
Handles terminal raw mode, async I/O, and SIGWINCH signals.
|
||||||
|
"""
|
||||||
|
def __init__(self):
|
||||||
|
self.stdin_fd = sys.stdin.fileno()
|
||||||
|
self.stdout_fd = sys.stdout.fileno()
|
||||||
|
self.original_tty_settings = None
|
||||||
|
self.resize_callback = None
|
||||||
|
self._reader_queue = asyncio.Queue()
|
||||||
|
self._loop = None
|
||||||
|
|
||||||
|
def setup(self, resize_callback=None):
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
self.resize_callback = resize_callback
|
||||||
|
|
||||||
|
# Save original terminal settings
|
||||||
|
try:
|
||||||
|
self.original_tty_settings = termios.tcgetattr(self.stdin_fd)
|
||||||
|
tty.setraw(self.stdin_fd)
|
||||||
|
except termios.error:
|
||||||
|
# Not a TTY, maybe piped or redirected
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Set stdin non-blocking
|
||||||
|
flags = fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL)
|
||||||
|
fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
|
||||||
|
|
||||||
|
# Setup read callback
|
||||||
|
self._loop.add_reader(self.stdin_fd, self._read_ready)
|
||||||
|
|
||||||
|
# Register SIGWINCH
|
||||||
|
if resize_callback:
|
||||||
|
try:
|
||||||
|
self._loop.add_signal_handler(signal.SIGWINCH, self._handle_winch)
|
||||||
|
except (NotImplementedError, RuntimeError):
|
||||||
|
# signal handling not supported on some loops (e.g., Windows Proactor)
|
||||||
|
pass
|
||||||
|
|
||||||
|
def stop_reading(self):
|
||||||
|
"""Temporarily stop reading from stdin."""
|
||||||
|
if self._loop and self.stdin_fd is not None:
|
||||||
|
try:
|
||||||
|
self._loop.remove_reader(self.stdin_fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def start_reading(self):
|
||||||
|
"""Resume reading from stdin."""
|
||||||
|
if self._loop and self.stdin_fd is not None:
|
||||||
|
try:
|
||||||
|
# Ensure we don't add it twice
|
||||||
|
self._loop.remove_reader(self.stdin_fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._loop.add_reader(self.stdin_fd, self._read_ready)
|
||||||
|
|
||||||
|
def teardown(self):
|
||||||
|
if self._loop:
|
||||||
|
try:
|
||||||
|
self._loop.remove_reader(self.stdin_fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if self.resize_callback:
|
||||||
|
try:
|
||||||
|
self._loop.remove_signal_handler(signal.SIGWINCH)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Restore terminal settings
|
||||||
|
if self.original_tty_settings is not None:
|
||||||
|
try:
|
||||||
|
termios.tcsetattr(self.stdin_fd, termios.TCSADRAIN, self.original_tty_settings)
|
||||||
|
except termios.error:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Restore blocking mode for stdin
|
||||||
|
try:
|
||||||
|
flags = fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL)
|
||||||
|
fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _read_ready(self):
|
||||||
|
try:
|
||||||
|
# Read whatever is available
|
||||||
|
data = os.read(self.stdin_fd, 4096)
|
||||||
|
if data:
|
||||||
|
self._reader_queue.put_nowait(data)
|
||||||
|
else:
|
||||||
|
self._reader_queue.put_nowait(b'') # EOF
|
||||||
|
except BlockingIOError:
|
||||||
|
pass
|
||||||
|
except OSError:
|
||||||
|
self._reader_queue.put_nowait(b'') # EOF on error
|
||||||
|
|
||||||
|
async def read(self) -> bytes:
|
||||||
|
"""Asynchronously read bytes from stdin."""
|
||||||
|
return await self._reader_queue.get()
|
||||||
|
|
||||||
|
async def write(self, data: bytes):
|
||||||
|
"""Asynchronously write bytes to stdout."""
|
||||||
|
if not data:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.write(self.stdout_fd, data)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _handle_winch(self):
|
||||||
|
if self.resize_callback:
|
||||||
|
try:
|
||||||
|
# Use ioctl to get the current window size
|
||||||
|
s = struct.pack("HHHH", 0, 0, 0, 0)
|
||||||
|
a = fcntl.ioctl(self.stdout_fd, termios.TIOCGWINSZ, s)
|
||||||
|
rows, cols, _, _ = struct.unpack("HHHH", a)
|
||||||
|
|
||||||
|
# We schedule the callback safely inside the asyncio loop
|
||||||
|
# instead of running it raw in the signal handler
|
||||||
|
self._loop.call_soon(self.resize_callback, rows, cols)
|
||||||
|
except Exception:
|
||||||
|
pass</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Asynchronous stream wrapper for local stdin/stdout.
|
||||||
|
Handles terminal raw mode, async I/O, and SIGWINCH signals.</p></div>
|
||||||
|
<h3>Methods</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.tunnels.LocalStream.read"><code class="name flex">
|
||||||
|
<span>async def <span class="ident">read</span></span>(<span>self) ‑> bytes</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">async def read(self) -> bytes:
|
||||||
|
"""Asynchronously read bytes from stdin."""
|
||||||
|
return await self._reader_queue.get()</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Asynchronously read bytes from stdin.</p></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tunnels.LocalStream.setup"><code class="name flex">
|
||||||
|
<span>def <span class="ident">setup</span></span>(<span>self, resize_callback=None)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def setup(self, resize_callback=None):
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
self.resize_callback = resize_callback
|
||||||
|
|
||||||
|
# Save original terminal settings
|
||||||
|
try:
|
||||||
|
self.original_tty_settings = termios.tcgetattr(self.stdin_fd)
|
||||||
|
tty.setraw(self.stdin_fd)
|
||||||
|
except termios.error:
|
||||||
|
# Not a TTY, maybe piped or redirected
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Set stdin non-blocking
|
||||||
|
flags = fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL)
|
||||||
|
fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
|
||||||
|
|
||||||
|
# Setup read callback
|
||||||
|
self._loop.add_reader(self.stdin_fd, self._read_ready)
|
||||||
|
|
||||||
|
# Register SIGWINCH
|
||||||
|
if resize_callback:
|
||||||
|
try:
|
||||||
|
self._loop.add_signal_handler(signal.SIGWINCH, self._handle_winch)
|
||||||
|
except (NotImplementedError, RuntimeError):
|
||||||
|
# signal handling not supported on some loops (e.g., Windows Proactor)
|
||||||
|
pass</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tunnels.LocalStream.start_reading"><code class="name flex">
|
||||||
|
<span>def <span class="ident">start_reading</span></span>(<span>self)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def start_reading(self):
|
||||||
|
"""Resume reading from stdin."""
|
||||||
|
if self._loop and self.stdin_fd is not None:
|
||||||
|
try:
|
||||||
|
# Ensure we don't add it twice
|
||||||
|
self._loop.remove_reader(self.stdin_fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._loop.add_reader(self.stdin_fd, self._read_ready)</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Resume reading from stdin.</p></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tunnels.LocalStream.stop_reading"><code class="name flex">
|
||||||
|
<span>def <span class="ident">stop_reading</span></span>(<span>self)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def stop_reading(self):
|
||||||
|
"""Temporarily stop reading from stdin."""
|
||||||
|
if self._loop and self.stdin_fd is not None:
|
||||||
|
try:
|
||||||
|
self._loop.remove_reader(self.stdin_fd)
|
||||||
|
except Exception:
|
||||||
|
pass</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Temporarily stop reading from stdin.</p></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tunnels.LocalStream.teardown"><code class="name flex">
|
||||||
|
<span>def <span class="ident">teardown</span></span>(<span>self)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def teardown(self):
|
||||||
|
if self._loop:
|
||||||
|
try:
|
||||||
|
self._loop.remove_reader(self.stdin_fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if self.resize_callback:
|
||||||
|
try:
|
||||||
|
self._loop.remove_signal_handler(signal.SIGWINCH)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Restore terminal settings
|
||||||
|
if self.original_tty_settings is not None:
|
||||||
|
try:
|
||||||
|
termios.tcsetattr(self.stdin_fd, termios.TCSADRAIN, self.original_tty_settings)
|
||||||
|
except termios.error:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Restore blocking mode for stdin
|
||||||
|
try:
|
||||||
|
flags = fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL)
|
||||||
|
fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
|
||||||
|
except Exception:
|
||||||
|
pass</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tunnels.LocalStream.write"><code class="name flex">
|
||||||
|
<span>async def <span class="ident">write</span></span>(<span>self, data: bytes)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">async def write(self, data: bytes):
|
||||||
|
"""Asynchronously write bytes to stdout."""
|
||||||
|
if not data:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.write(self.stdout_fd, data)
|
||||||
|
except OSError:
|
||||||
|
pass</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Asynchronously write bytes to stdout.</p></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tunnels.RemoteStream"><code class="flex name class">
|
||||||
|
<span>class <span class="ident">RemoteStream</span></span>
|
||||||
|
<span>(</span><span>request_iterator, response_queue)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">class RemoteStream:
|
||||||
|
"""
|
||||||
|
Asynchronous stream wrapper for gRPC remote connections.
|
||||||
|
Bridges the blocking gRPC iterators with the async _async_interact_loop.
|
||||||
|
"""
|
||||||
|
def __init__(self, request_iterator, response_queue):
|
||||||
|
self.request_iterator = request_iterator
|
||||||
|
self.response_queue = response_queue
|
||||||
|
self.running = True
|
||||||
|
self._reader_queue = asyncio.Queue()
|
||||||
|
self.copilot_queue = asyncio.Queue()
|
||||||
|
self.resize_callback = None
|
||||||
|
self._loop = None
|
||||||
|
self.t = None
|
||||||
|
|
||||||
|
def setup(self, resize_callback=None):
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
self.resize_callback = resize_callback
|
||||||
|
|
||||||
|
def read_requests():
|
||||||
|
try:
|
||||||
|
for req in self.request_iterator:
|
||||||
|
if not self.running:
|
||||||
|
break
|
||||||
|
if req.cols > 0 and req.rows > 0:
|
||||||
|
if self.resize_callback:
|
||||||
|
self._loop.call_soon_threadsafe(self.resize_callback, req.rows, req.cols)
|
||||||
|
# Copilot dispatching
|
||||||
|
copilot_msg = {}
|
||||||
|
if getattr(req, "copilot_question", ""):
|
||||||
|
copilot_msg.update({
|
||||||
|
"question": req.copilot_question,
|
||||||
|
"context_buffer": getattr(req, "copilot_context_buffer", ""),
|
||||||
|
"node_info_json": getattr(req, "copilot_node_info_json", "")
|
||||||
|
})
|
||||||
|
if getattr(req, "copilot_action", ""):
|
||||||
|
copilot_msg["action"] = req.copilot_action
|
||||||
|
|
||||||
|
if copilot_msg:
|
||||||
|
self._loop.call_soon_threadsafe(self.copilot_queue.put_nowait, copilot_msg)
|
||||||
|
if req.stdin_data:
|
||||||
|
self._loop.call_soon_threadsafe(self._reader_queue.put_nowait, req.stdin_data)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
if self._loop and not self._loop.is_closed():
|
||||||
|
try:
|
||||||
|
self._loop.call_soon_threadsafe(self._reader_queue.put_nowait, b'')
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
self.t = threading.Thread(target=read_requests, daemon=True)
|
||||||
|
self.t.start()
|
||||||
|
|
||||||
|
def teardown(self):
|
||||||
|
self.running = False
|
||||||
|
self.response_queue.put(None) # Signal EOF
|
||||||
|
|
||||||
|
async def read(self) -> bytes:
|
||||||
|
"""Asynchronously read bytes from the gRPC iterator queue."""
|
||||||
|
return await self._reader_queue.get()
|
||||||
|
|
||||||
|
async def write(self, data: bytes):
|
||||||
|
"""Asynchronously write bytes to the gRPC response queue."""
|
||||||
|
if data:
|
||||||
|
self.response_queue.put(data)</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Asynchronous stream wrapper for gRPC remote connections.
|
||||||
|
Bridges the blocking gRPC iterators with the async _async_interact_loop.</p></div>
|
||||||
|
<h3>Methods</h3>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.tunnels.RemoteStream.read"><code class="name flex">
|
||||||
|
<span>async def <span class="ident">read</span></span>(<span>self) ‑> bytes</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">async def read(self) -> bytes:
|
||||||
|
"""Asynchronously read bytes from the gRPC iterator queue."""
|
||||||
|
return await self._reader_queue.get()</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Asynchronously read bytes from the gRPC iterator queue.</p></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tunnels.RemoteStream.setup"><code class="name flex">
|
||||||
|
<span>def <span class="ident">setup</span></span>(<span>self, resize_callback=None)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def setup(self, resize_callback=None):
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
self.resize_callback = resize_callback
|
||||||
|
|
||||||
|
def read_requests():
|
||||||
|
try:
|
||||||
|
for req in self.request_iterator:
|
||||||
|
if not self.running:
|
||||||
|
break
|
||||||
|
if req.cols > 0 and req.rows > 0:
|
||||||
|
if self.resize_callback:
|
||||||
|
self._loop.call_soon_threadsafe(self.resize_callback, req.rows, req.cols)
|
||||||
|
# Copilot dispatching
|
||||||
|
copilot_msg = {}
|
||||||
|
if getattr(req, "copilot_question", ""):
|
||||||
|
copilot_msg.update({
|
||||||
|
"question": req.copilot_question,
|
||||||
|
"context_buffer": getattr(req, "copilot_context_buffer", ""),
|
||||||
|
"node_info_json": getattr(req, "copilot_node_info_json", "")
|
||||||
|
})
|
||||||
|
if getattr(req, "copilot_action", ""):
|
||||||
|
copilot_msg["action"] = req.copilot_action
|
||||||
|
|
||||||
|
if copilot_msg:
|
||||||
|
self._loop.call_soon_threadsafe(self.copilot_queue.put_nowait, copilot_msg)
|
||||||
|
if req.stdin_data:
|
||||||
|
self._loop.call_soon_threadsafe(self._reader_queue.put_nowait, req.stdin_data)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
if self._loop and not self._loop.is_closed():
|
||||||
|
try:
|
||||||
|
self._loop.call_soon_threadsafe(self._reader_queue.put_nowait, b'')
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
self.t = threading.Thread(target=read_requests, daemon=True)
|
||||||
|
self.t.start()</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tunnels.RemoteStream.teardown"><code class="name flex">
|
||||||
|
<span>def <span class="ident">teardown</span></span>(<span>self)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def teardown(self):
|
||||||
|
self.running = False
|
||||||
|
self.response_queue.put(None) # Signal EOF</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"></div>
|
||||||
|
</dd>
|
||||||
|
<dt id="connpy.tunnels.RemoteStream.write"><code class="name flex">
|
||||||
|
<span>async def <span class="ident">write</span></span>(<span>self, data: bytes)</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">async def write(self, data: bytes):
|
||||||
|
"""Asynchronously write bytes to the gRPC response queue."""
|
||||||
|
if data:
|
||||||
|
self.response_queue.put(data)</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Asynchronously write bytes to the gRPC response queue.</p></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
</article>
|
||||||
|
<nav id="sidebar">
|
||||||
|
<div class="toc">
|
||||||
|
<ul></ul>
|
||||||
|
</div>
|
||||||
|
<ul id="index">
|
||||||
|
<li><h3>Super-module</h3>
|
||||||
|
<ul>
|
||||||
|
<li><code><a title="connpy" href="index.html">connpy</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.tunnels.LocalStream" href="#connpy.tunnels.LocalStream">LocalStream</a></code></h4>
|
||||||
|
<ul class="two-column">
|
||||||
|
<li><code><a title="connpy.tunnels.LocalStream.read" href="#connpy.tunnels.LocalStream.read">read</a></code></li>
|
||||||
|
<li><code><a title="connpy.tunnels.LocalStream.setup" href="#connpy.tunnels.LocalStream.setup">setup</a></code></li>
|
||||||
|
<li><code><a title="connpy.tunnels.LocalStream.start_reading" href="#connpy.tunnels.LocalStream.start_reading">start_reading</a></code></li>
|
||||||
|
<li><code><a title="connpy.tunnels.LocalStream.stop_reading" href="#connpy.tunnels.LocalStream.stop_reading">stop_reading</a></code></li>
|
||||||
|
<li><code><a title="connpy.tunnels.LocalStream.teardown" href="#connpy.tunnels.LocalStream.teardown">teardown</a></code></li>
|
||||||
|
<li><code><a title="connpy.tunnels.LocalStream.write" href="#connpy.tunnels.LocalStream.write">write</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h4><code><a title="connpy.tunnels.RemoteStream" href="#connpy.tunnels.RemoteStream">RemoteStream</a></code></h4>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.tunnels.RemoteStream.read" href="#connpy.tunnels.RemoteStream.read">read</a></code></li>
|
||||||
|
<li><code><a title="connpy.tunnels.RemoteStream.setup" href="#connpy.tunnels.RemoteStream.setup">setup</a></code></li>
|
||||||
|
<li><code><a title="connpy.tunnels.RemoteStream.teardown" href="#connpy.tunnels.RemoteStream.teardown">teardown</a></code></li>
|
||||||
|
<li><code><a title="connpy.tunnels.RemoteStream.write" href="#connpy.tunnels.RemoteStream.write">write</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>
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
<!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.utils API documentation</title>
|
||||||
|
<meta name="description" content="">
|
||||||
|
<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">Module <code>connpy.utils</code></h1>
|
||||||
|
</header>
|
||||||
|
<section id="section-intro">
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||||
|
<dl>
|
||||||
|
<dt id="connpy.utils.log_cleaner"><code class="name flex">
|
||||||
|
<span>def <span class="ident">log_cleaner</span></span>(<span>data: str) ‑> str</span>
|
||||||
|
</code></dt>
|
||||||
|
<dd>
|
||||||
|
<details class="source">
|
||||||
|
<summary>
|
||||||
|
<span>Expand source code</span>
|
||||||
|
</summary>
|
||||||
|
<pre><code class="python">def log_cleaner(data: str) -> str:
|
||||||
|
"""
|
||||||
|
Stateless utility to remove ANSI sequences and process cursor movements.
|
||||||
|
"""
|
||||||
|
if not data:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
lines = data.split('\n')
|
||||||
|
cleaned_lines = []
|
||||||
|
|
||||||
|
# Regex to capture: ANSI sequences, control characters (\r, \b, etc), and plain text chunks
|
||||||
|
token_re = re.compile(r'(\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/ ]*[@-~])|\r|\b|\x7f|[\x00-\x1F]|[^\x1B\r\b\x7f\x00-\x1F]+)')
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
buffer = []
|
||||||
|
cursor = 0
|
||||||
|
|
||||||
|
for token in token_re.findall(line):
|
||||||
|
if token == '\r':
|
||||||
|
cursor = 0
|
||||||
|
elif token in ('\b', '\x7f'):
|
||||||
|
if cursor > 0:
|
||||||
|
cursor -= 1
|
||||||
|
elif token.startswith('\x1B[') and len(token) >= 3:
|
||||||
|
# Parse CSI: \x1B[ <params> <final_char>
|
||||||
|
final = token[-1]
|
||||||
|
param_str = token[2:-1]
|
||||||
|
n = int(param_str) if param_str.isdigit() else 1
|
||||||
|
|
||||||
|
if final == 'D': # CUB – Cursor Back
|
||||||
|
cursor = max(0, cursor - n)
|
||||||
|
elif final == 'C': # CUF – Cursor Forward
|
||||||
|
cursor = min(len(buffer), cursor + n)
|
||||||
|
elif final == 'K': # EL – Erase in Line
|
||||||
|
if n == 0 or param_str == '': # Clear to end
|
||||||
|
buffer = buffer[:cursor]
|
||||||
|
elif n == 1: # Clear to start
|
||||||
|
buffer[:cursor] = [' '] * cursor
|
||||||
|
elif n == 2: # Clear entire line
|
||||||
|
buffer = []
|
||||||
|
cursor = 0
|
||||||
|
elif final == 'G': # CHA – Cursor Horizontal Absolute (1-indexed)
|
||||||
|
cursor = max(0, n - 1)
|
||||||
|
# Pad buffer if cursor is beyond current length
|
||||||
|
if cursor > len(buffer):
|
||||||
|
buffer.extend([' '] * (cursor - len(buffer)))
|
||||||
|
elif final == 'P': # DCH – Delete Characters
|
||||||
|
del buffer[cursor:cursor + n]
|
||||||
|
elif final == '@': # ICH – Insert Characters
|
||||||
|
buffer[cursor:cursor] = [' '] * n
|
||||||
|
# All other CSI sequences are silently discarded
|
||||||
|
elif token.startswith('\x1B'):
|
||||||
|
continue
|
||||||
|
elif len(token) == 1 and ord(token) < 32:
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
for char in token:
|
||||||
|
if cursor == len(buffer):
|
||||||
|
buffer.append(char)
|
||||||
|
else:
|
||||||
|
buffer[cursor] = char
|
||||||
|
cursor += 1
|
||||||
|
cleaned_lines.append("".join(buffer))
|
||||||
|
|
||||||
|
return "\n".join(cleaned_lines).replace('\n\n', '\n').strip()</code></pre>
|
||||||
|
</details>
|
||||||
|
<div class="desc"><p>Stateless utility to remove ANSI sequences and process cursor movements.</p></div>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
</section>
|
||||||
|
</article>
|
||||||
|
<nav id="sidebar">
|
||||||
|
<div class="toc">
|
||||||
|
<ul></ul>
|
||||||
|
</div>
|
||||||
|
<ul id="index">
|
||||||
|
<li><h3>Super-module</h3>
|
||||||
|
<ul>
|
||||||
|
<li><code><a title="connpy" href="index.html">connpy</a></code></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||||
|
<ul class="">
|
||||||
|
<li><code><a title="connpy.utils.log_cleaner" href="#connpy.utils.log_cleaner">log_cleaner</a></code></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>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user