Python SDK
+Native Python client library for Pilot Protocol with CLI tools and type hints.
+ +Package: pilotprotocol • PyPI: pypi.org/project/pilotprotocol • Requires: Python 3.10+
Installation
+pip install pilotprotocol
+ This installs:
+-
+
- Python SDK —
pilotprotocolmodule withDriverclass
+ - CLI Tools —
pilotctl,pilot-daemon,pilot-gatewayexecutables
+ - Native Binaries — Platform-specific Go binaries bundled in the wheel +
Quick Start
+ +1. Start the Daemon
+The daemon must be running before using the SDK:
+pilot-daemon start --hostname my-agent
+
+ 2. Use the SDK
+from pilotprotocol import Driver
+
+# Driver automatically connects to daemon at /tmp/pilot.sock
+with Driver() as d:
+ # Get agent information
+ info = d.info()
+ print(f"Address: {info['address']}")
+ print(f"Hostname: {info.get('hostname', 'none')}")
+
+ # Open a stream connection to a peer (port 1000)
+ with d.dial("other-agent:1000") as conn:
+ conn.write(b"Hello from Python!")
+ response = conn.read(4096)
+ print(f"Got: {response}")
+
+ API Reference
+ +Driver
+Main entry point for interacting with the Pilot Protocol daemon. Use as a context manager for automatic cleanup.
+ +Constructor
+driver = Driver(socket_path: str = "/tmp/pilot.sock")
+ Parameters:
+-
+
socket_path— Path to the daemon's Unix socket (default:/tmp/pilot.sock)
+
Core Methods
+ +info()
+d.info() -> dict
+ Returns agent information.
+Returns:
+{
+ "address": "0:0000.0000.0042", # Virtual address
+ "hostname": "my-agent", # Hostname (optional)
+ "public": false, # Public visibility
+ "uptime": 3600 # Uptime in seconds
+}
+
+ dial()
+d.dial(addr: str) -> Conn
+ Opens a stream connection to a peer. Returns a Conn object that supports context management.
Parameters:
+-
+
addr— Peer address with port:"hostname:port"or"N:XXXX.YYYY.YYYY:PORT"
+
Example:
+with d.dial("other-agent:1000") as conn:
+ conn.write(b"data")
+ response = conn.read(1024)
+
+ listen()
+d.listen(port: int) -> Listener
+ Listens for incoming connections on a port. Returns a Listener object.
Example:
+with d.listen(5000) as listener:
+ conn = listener.accept()
+ data = conn.read(1024)
+
+ resolve_hostname()
+d.resolve_hostname(hostname: str) -> dict
+ Resolves a hostname to a virtual address.
+Returns: {"address": "0:0000.0000.0042", "hostname": "other-agent"}
ping()
+d.ping(addr: str) -> dict
+ Pings a peer and returns RTT statistics.
+Returns:
+{
+ "min_ms": 12.3, # Min RTT (ms)
+ "avg_ms": 15.7, # Avg RTT (ms)
+ "max_ms": 18.2, # Max RTT (ms)
+ "count": 10 # Packets sent
+}
+
+ High-Level Service Methods
+These methods provide convenient access to built-in services:
+ +send_message()
+d.send_message(target: str, data: bytes, msg_type: str = "text") -> dict
+ Sends a message via the data exchange service (port 1001).
+Parameters:
+-
+
target— Hostname or protocol address
+ data— Message data (text, JSON, or binary)
+ msg_type— Message type:"text","json", or"binary"
+
Example:
+result = d.send_message("other-agent", b"Hello!", "text")
+print(result['ack']) # "ACK TYPE 1 6 bytes"
+
+ send_file()
+d.send_file(target: str, file_path: str) -> dict
+ Sends a file via the data exchange service (port 1001).
+Example:
+result = d.send_file("other-agent", "/path/to/file.pdf")
+print(f"Sent {result['sent']} bytes")
+
+ publish_event()
+d.publish_event(target: str, topic: str, data: bytes) -> dict
+ Publishes an event via the event stream service (port 1002).
+Example:
+d.publish_event("other-agent", "sensor/temp", b"23.5")
+
+ subscribe_event()
+d.subscribe_event(target: str, topic: str, callback: callable) -> None
+ Subscribes to events from the event stream service (port 1002). Wildcards supported: * (single-level), ** (multi-level).
Example:
+def on_event(topic, data):
+ print(f"{topic}: {data}")
+
+d.subscribe_event("other-agent", "sensor/**", on_event)
+
+ submit_task()
+d.submit_task(target: str, task_data: dict) -> dict
+ Submits a task via the task submit service (port 1003).
+Example:
+result = d.submit_task("worker-agent", {
+ "command": "process",
+ "params": {"input": "data.txt"}
+})
+
+ Administration Methods
+ +set_hostname()
+d.set_hostname(hostname: str) -> dict
+ Sets or updates the node's hostname.
+ +set_public()
+d.set_public(public: bool) -> dict
+ Sets the node's public visibility for discovery.
+ +set_tags()
+d.set_tags(tags: list[str]) -> dict
+ Sets capability tags for this node.
+Example:
+d.set_tags(["python", "ml-inference", "gpu"])
+
+ set_webhook()
+d.set_webhook(url: str) -> dict
+ Sets or clears the webhook URL for events.
+ +Conn
+Represents an active stream connection. Supports context management.
+ +write()
+conn.write(data: bytes) -> int
+ Writes data to the connection. Returns number of bytes written.
+ +read()
+conn.read(size: int = 65536) -> bytes
+ Reads data from the connection (blocks until data arrives).
+ +close()
+conn.close() -> None
+ Closes the connection.
+ +Listener
+Listens for incoming connections. Supports context management.
+ +accept()
+listener.accept() -> Conn
+ Accepts an incoming connection (blocks until a connection arrives). Returns a Conn object.
close()
+listener.close() -> None
+ Closes the listener.
+ +Usage Examples
+ +Echo Server
+from pilotprotocol import Driver
+
+with Driver() as d:
+ # Listen on port 5000
+ with d.listen(5000) as listener:
+ print("Listening on port 5000...")
+
+ while True:
+ conn = listener.accept()
+ print("Connection accepted")
+
+ data = conn.read(4096)
+ print(f"Received: {data.decode()}")
+
+ conn.write(data) # Echo back
+ conn.close()
+ print("Connection closed")
+
+ Send Messages
+from pilotprotocol import Driver
+import json
+
+with Driver() as d:
+ # Send text message
+ result = d.send_message("other-agent", b"Hello!", "text")
+ print(f"Sent: {result}")
+
+ # Send JSON data
+ json_data = json.dumps({
+ "command": "status",
+ "timestamp": 1234567890
+ }).encode()
+ result = d.send_message("other-agent", json_data, "json")
+ print(f"Response: {result}")
+
+ Pub/Sub Events
+from pilotprotocol import Driver
+
+with Driver() as d:
+ # Publish events
+ d.publish_event("other-agent", "sensor/temperature", b"23.5")
+ d.publish_event("other-agent", "sensor/humidity", b"65")
+
+ # Subscribe to events
+ def on_event(topic, data):
+ print(f"{topic}: {data.decode()}")
+
+ d.subscribe_event("other-agent", "sensor/**", on_event)
+
+ File Transfer
+from pilotprotocol import Driver
+
+with Driver() as d:
+ # Send a file
+ result = d.send_file("other-agent", "/path/to/document.pdf")
+ print(f"Sent {result['filename']}: {result['sent']} bytes")
+
+ Low-Level Streams
+For custom protocols, use dial() and listen() directly:
from pilotprotocol import Driver
+
+with Driver() as d:
+ # Client: connect to custom port
+ with d.dial("other-agent:5000") as conn:
+ conn.write(b"CUSTOM PROTOCOL MESSAGE")
+ response = conn.read(1024)
+ print(response)
+
+ Error Handling
+The SDK raises Python exceptions for errors:
+from pilotprotocol import Driver, PilotError
+
+with Driver() as d:
+ try:
+ conn = d.dial("nonexistent-agent:1000")
+ except PilotError as e:
+ print(f"Error: {e}")
+ # e.g., "no route to host"
+
+ Common exceptions:
+-
+
PilotError— Connection failures, protocol errors
+ FileNotFoundError— Library or file not found
+ ValueError— Invalid parameters
+
Type Hints
+The SDK includes comprehensive type annotations:
+from pilotprotocol import Driver, Conn
+from typing import Dict, Any
+
+with Driver() as d:
+ conn: Conn = d.dial("other-agent:1000")
+ info: Dict[str, Any] = d.info()
+
+ # Type checkers (mypy, pyright) will validate usage
+
+ Testing
+The SDK includes a complete test suite with 100% code coverage. To run tests:
+git clone https://github.com/TeoSlayer/pilotprotocol.git
+cd pilotprotocol/sdk/python
+pip install -e .[dev]
+pytest
+
+ CLI Tools
+The package includes CLI wrappers for the Go binaries:
+-
+
pilotctl— Main CLI tool (equivalent to the Go binary)
+ pilot-daemon— Start the daemon
+ pilot-gateway— Start the IP gateway
+
These are standard Python console script entry points that execute the bundled binaries.
+ +Platform Support
+The SDK provides platform-specific wheels for:
+-
+
- Linux — x86_64 (manylinux) +
- macOS — x86_64, ARM64 (Apple Silicon) +
Windows support is planned for future releases.
+ +Architecture
+The Python SDK uses ctypes to call Go functions exported via CGO:
-
+
- FFI Layer —
ctypesbindings tolibpilot.so/.dylib
+ - Single Source of Truth — All SDK calls go through the same Go code the CLI uses +
- Memory Management — Automatic cleanup of Go-allocated strings +
- Handle Pattern — Opaque handles for connections, listeners +
- Error Handling — Go errors converted to Python exceptions +
Architecture Diagram:
+┌─────────────┐ ctypes/FFI ┌──────────────┐ Unix socket ┌────────┐
+│ Python SDK │ ───────────────► │ libpilot.so │ ─────────────────► │ Daemon │
+│ (client.py)│ │ (Go c-shared)│ │ │
+└─────────────┘ └──────────────┘ └────────┘
+
+ Contributing
+See the Python SDK Contributing Guide for development setup, testing, and packaging instructions.
+ +Examples Repository
+Complete working examples are available in the GitHub repository:
+ +Examples include:
+-
+
- basic_client.py — Simple connection and message exchange +
- echo_server.py — Echo server implementation +
- data_exchange.py — Typed data exchange usage +
- pubsub.py — Event stream pub/sub patterns +
- file_transfer.py — File sending and receiving +
- context_managers.py — Using with statements for cleanup +
Additional Resources
+-
+
- GitHub Repository +
- PyPI Package +
- SDK README +
- Changelog +
- Issue Tracker +
Pilot Protocol