cerbug45-agentmesh

TotalClaw 作者 totalclaw

面向 AI 智能体的端到端加密消息系统,支持本地与网络 Hub。

安装 / 下载方式

TotalClaw CLI推荐
totalclaw skills install shop:totalclaw:totalclaw~cerbug45-agentmesh
cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/totalclaw%3Atotalclaw~cerbug45-agentmesh/file -o cerbug45-agentmesh.md
## 概述(中文)

面向 AI 智能体的端到端加密消息系统,支持本地与网络 Hub。

## 技能正文

# AgentMesh SKILL.md

> **面向 AI 智能体的 WhatsApp 式端到端加密消息。**
> GitHub: https://github.com/cerbug45/AgentMesh | 作者: cerbug45

---

## 什么是 AgentMesh?

AgentMesh 为每个 AI 智能体提供**加密身份**,并使智能体
能够交换具有以下属性的消息:

| 属性 | 机制 |
|---|---|
| **加密** | AES-256-GCM 认证加密 |
| **认证** | Ed25519 数字签名(每条消息) |
| **前向保密** | X25519 ECDH 临时会话密钥 |
| **防篡改** | AEAD 认证标签 |
| **防重放** | Nonce + 计数器去重 |
| **私密** | Hub(代理)永远看不到消息内容 |

无需 TLS 证书。本地使用无需服务器。一次 `pip install`。

---

## Installation

### 要求

- Python **3.10 或更新**
- `pip`

### 选项 1 – 从 GitHub 安装(推荐)

```bash
pip install git+https://github.com/cerbug45/AgentMesh.git
```

### 选项 2 – 克隆并本地安装

```bash
git clone https://github.com/cerbug45/AgentMesh.git
cd AgentMesh
pip install .
```

### 选项 3 – 开发安装(可编辑,含测试)

```bash
git clone https://github.com/cerbug45/AgentMesh.git
cd AgentMesh
pip install -e ".[dev]"
pytest           # run all tests
```

### 验证安装

```python
python -c "import agentmesh; print(agentmesh.__version__)"
# → 1.0.0
```

---

## 快速开始(5 分钟)

```python
from agentmesh import Agent, LocalHub

hub   = LocalHub()                  # in-process broker
alice = Agent("alice", hub=hub)     # keys generated automatically
bob   = Agent("bob",   hub=hub)

@bob.on_message
def handle(msg):
    print(f"[{msg.recipient}] ← {msg.sender}: {msg.text}")

alice.send("bob", text="Hello, Bob! This is end-to-end encrypted.")
```

Output:
```
[bob] ← alice: Hello, Bob! This is end-to-end encrypted.
```

---

## 核心概念

### 智能体

 `Agent` 是具有**加密身份**(两对密钥)的 AI 智能体:

- **Ed25519 身份密钥** — 签署每条出站消息
- **X25519 交换密钥** — 用于 ECDH 会话建立

```python
from agentmesh import Agent, LocalHub

hub   = LocalHub()
alice = Agent("alice", hub=hub)

# See the agent's fingerprint (share out-of-band to verify identity)
print(alice.fingerprint)
# → a1b2:c3d4:e5f6:g7h8:i9j0:k1l2:m3n4:o5p6
```

### Hub

Hub 是**消息路由器**。它存储公钥包(用于发现)
并路由加密信封。它无法解密消息。

| Hub | 用例 |
|---|---|
| `LocalHub` | 单 Python 进程(演示、测试、笔记本) |
| `NetworkHub` | 多进程/多机(生产) |

### 消息

```python
@bob.on_message
def handle(msg):
    msg.sender     # str  – sender agent_id
    msg.recipient  # str  – recipient agent_id
    msg.text       # str  – shortcut for msg.payload["text"]
    msg.type       # str  – shortcut for msg.payload["type"] (default: "message")
    msg.payload    # dict – full decrypted payload
    msg.timestamp  # int  – milliseconds since epoch
```

---

## 使用指南

### 发送带额外数据的消息

```python
alice.send(
    "bob",
    text     = "Run this task",
    task_id  = 42,
    priority = "high",
    data     = {"key": "value"},
)
```

除 `text` 外的所有关键字参数都包含在 `msg.payload` 中。

### 链式处理器

```python
# Handler as decorator
@alice.on_message
def handler_one(msg):
    ...

# Handler as lambda
alice.on_message(lambda msg: print(msg.text))

# Multiple handlers – all called in registration order
alice.on_message(log_handler)
alice.on_message(process_handler)
```

### 持久化密钥

将密钥保存到磁盘,使智能体在重启后保持**相同身份**:

```python
alice = Agent("alice", hub=hub, keypair_path=".keys/alice.json")
```

- 首次运行时创建文件(新密钥)。
- 后续运行加载文件(相同密钥 = 相同指纹)。
- 安全存储此文件 — 包含私钥。

### 对等发现

```python
# List all agents registered on the hub
peers = alice.list_peers()   # → ["bob", "carol", "dave"]

# Check agent status
print(alice.status())
# {
#   "agent_id": "alice",
#   "fingerprint": "a1b2:…",
#   "active_sessions": ["bob"],
#   "known_peers": ["bob"],
#   "handlers": 2
# }
```

---

## 网络模式(多机)

### 1. 启动 Hub 服务器

在**代理机器**(或其独立终端)上:

```bash
# Option A – module
python -m agentmesh.hub_server --host 0.0.0.0 --port 7700

# Option B – entry-point (after pip install)
agentmesh-hub --host 0.0.0.0 --port 7700
```

### 2. 智能体从任意位置连接

```python
# Machine A
from agentmesh import Agent, NetworkHub
hub   = NetworkHub(host="192.168.1.10", port=7700)
alice = Agent("alice", hub=hub)

# Machine B (different process / different computer)
from agentmesh import Agent, NetworkHub
hub = NetworkHub(host="192.168.1.10", port=7700)
bob = Agent("bob", hub=hub)

bob.on_message(lambda m: print(m.text))
alice.send("bob", text="Cross-machine encrypted message!")
```

### 网络 Hub 架构

```
┌──────────────────────────────────────────────────────┐
│                   NetworkHubServer                   │
│  Stores public bundles.  Routes encrypted envelopes. │
│  Cannot read message contents.                       │
└──────────────────────┬───────────────────────────────┘
                       │ TCP (newline-delimited JSON)
           ┌───────────┼───────────┐
           │           │           │
      Agent A      Agent B      Agent C
   (encrypted)  (encrypted)  (encrypted)
```

---

## 安全架构

### 加密栈

```
┌─────────────────────────────────────────────────────┐
│  Application layer (dict payload)                   │
├─────────────────────────────────────────────────────┤
│  Ed25519 signature  (sender authentication)         │
├─────────────────────────────────────────────────────┤
│  AES-256-GCM  (confidentiality + integrity)         │
├─────────────────────────────────────────────────────┤
│  HKDF-SHA256 key derivation (directional keys)      │
├─────────────────────────────────────────────────────┤
│  X25519 ECDH  (shared secret / forward secrecy)     │
└─────────────────────────────────────────────────────┘
```

### 安全属性

| 攻击 | 防御 |
|---|---|
| 窃听 | AES-256-GCM 加密 |
| 消息篡改 | AES-GCM 认证标签 (AEAD) |
| 冒充 | 每条消息的 Ed25519 签名 |
| 重放攻击 | Nonce + 单调计数器去重 |
| 密钥泄露 | X25519 临时会话(前向保密) |
| Hub 泄露 | Hub 仅存储公钥;无法解密 |

### Hub 能看到什么

- ✅ 智能体 ID(用于路由消息)
- ✅ 公钥包(发现所需)
- ✅ 元数据:发送者、接收者、时间戳、消息计数器
- ❌ **消息内容**(始终加密)
- ❌ **载荷数据**(始终加密)

---

## Examples

| 文件 | 说明 |
|---|---|
| `examples/01_simple_chat.py` | Two agents, basic send/receive |
| `examples/02_multi_agent.py` | Coordinator + 4 workers, task distribution |
| `examples/03_persistent_keys.py` | Keys saved to disk, identity survives restart |
| `examples/04_llm_agents.py` | LLM agents (OpenAI / any API) in a pipeline |

运行任意示例:

```bash
python examples/01_simple_chat.py
```

---

## API 参考

### `Agent(agent_id, hub=None, keypair_path=None, log_level=WARNING)`

| 方法 | 说明 |
|---|---|
| `send(recipient_id, text="", **kwargs)` | 发送加密消息 |
| `send_payload(recipient_id, payload: dict)` | 底层发送 |
| `on_message(handler)` | 注册消息处理器(装饰器或调用) |
| `connect(peer_id)` | 预建立会话(可选,自动连接) |
| `connect_with_bundle(bundle)` | P2P:直接使用公钥包连接 |
| `list_peers()` | 列出 Hub 上所有对等 ID |
| `status()` | 含智能体状态的字典 |
| `fingerprint` | 人类可读的十六进制身份指纹 |
| `public_bundle` | 含公钥的字典(与对等方分享) |

### `LocalHub()`

| 方法 | 说明 |
|---|---|
| `register(agent)` | 注册智能体(自动调用) |
| `deliver(envelope)` | 路由加密信封 |
| `get_bundle(agent_id)` | 获取对等方公钥包 |
| `list_agents()` | 列出所有已注册智能体 ID |
| `message_count()` | 已路由消息数 |

### `NetworkHub(host, port=7700)`

与 `LocalHub` 相同接口,但通过 TCP 与 `NetworkHubServer` 通信。

### `NetworkHubServer(host="0.0.0.0", port=7700)`

| 方法 | 说明 |
|---|---|
| `start(block=True)` | 开始监听(block=False 为后台线程) |

### 底层加密(高级)

```python
from agentmesh.crypto import (
    AgentKeyPair,        # key generation, serialisation, fingerprint
    CryptoSession,       # encrypt / decrypt
    perform_key_exchange,# X25519 ECDH → CryptoSession
    seal,                # sign + encrypt (high-level)
    unseal,              # decrypt + verify (high-level)
    CryptoError,         # raised on any crypto failure
)
```

---

## Troubleshooting

### `CryptoError: Replay attack detected`
你正在发送相同的加密信封两次。
每次 `send()` 产生新信封 — 不要重用信封。

### `CryptoError: Authentication tag mismatch`
信封在传输中被修改。
检查传输未损坏二进制数据(使用 JSON 安全 base64)。

### `ValueError: Peer 'xxx' not found on hub`
接收者尚未在 Hub 注册。
确保两个智能体使用同一 Hub 实例 (LocalHub) 或
连接到同一 Hub 服务器 (NetworkHub)。

### `RuntimeError: No hub configured`
你创建了无 Hub 的 `Agent("name")`。
向构造函数传入 `hub=LocalHub()` 或 `hub=NetworkHub(...)`。

---

## 贡献

```bash
git clone https://github.com/cerbug45/AgentMesh.git
cd AgentMesh
pip install -e ".[dev]"
pytest -v
```

Issues and PRs welcome at https://github.com/cerbug45/AgentMesh/issues

---

## 许可证

MIT © cerbug45 — 见 [LICENSE](LICENSE)