SSH Connection Pooling
The dpersistantssh package implements a high-performance connection pool to manage SSH sessions for remote tool execution.
The Problem
Executing single shell commands over SSH typically requires:
- TCP Handshake
- SSH Key Exchange
- Authentication
- Channel Creation
- Execution & Teardown
For AI agents running multiple diagnostic tools (like top, then df, then tail), this overhead causes significant latency, slowing down the ReAct loop.
The Solution: Connection Pooling
The package maintains a global sync.Map of active *ssh.Client instances.
Workflow
- Request: An agent requests a command execution on
serverA. - Pool Check: The system checks the
sync.Mapfor an existing client connected toserverA. - Reuse: If found and healthy, a new
*ssh.Session(channel) is opened over the existing client connection, bypassing the TCP/Authentication overhead. - New Connection: If not found, a new connection is established and stored in the map for future use.
Dial Cooldowns
To prevent an AI agent from accidentally launching a DoS attack against an offline server (e.g., repeatedly trying to connect in a tight loop), the system implements a Dial Cooldown. If a connection attempt fails, the server is flagged, and subsequent attempts are blocked for a brief cooldown period (e.g., 30 seconds), instantly returning an error to the agent to force a replan.
Mermaid Diagram: Pooling Logic
graph TD
Agent[Agent Tool Call] --> Check{Check sync.Map}
Check -- Hit --> Session[Open SSH Session]
Check -- Miss --> Dial{Dial SSH Server}
Dial -- Success --> Store[Store in sync.Map]
Store --> Session
Dial -- Fail --> Cooldown[Set Dial Cooldown]
Cooldown --> Error[Return Network Error]
Session --> Exec[Run Command]
Exec --> Close[Close Session]
Close --> Return[Return Output]
Guidance for AI Agents
- Fast Diagnostics: Because of connection pooling, running sequential commands on the same server is very fast. You don't need to try and pack every command into a single chained bash script if separate tool calls are cleaner.