Metadata-Version: 2.4
Name: hermes-wpsxiezuo
Version: 0.8.0
Summary: WPSXiezuo (WPS协作) platform adapter for Hermes Agent
Author: Kingsoft
License: MIT
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Chat
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: pycryptodome<4,>=3.20.0
Requires-Dist: aiohttp<4,>=3.9.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"

# WPSXiezuo (WPS协作) Platform Adapter for Hermes Agent

This is a WPSXiezuo messaging platform adapter for [Hermes Agent](https://github.com/NousResearch/hermes-agent). It enables bidirectional messaging between Hermes Agent and **WPS协作** (via the WPS Open Platform).

**Gateway setup（用户指南）**：[docs/user-guide/messaging/wpsxiezuo.md](docs/user-guide/messaging/wpsxiezuo.md)（WebSocket、环境变量、排错等）。

## Features

- **Inbound Messages**: Receive and process messages from WPS协作 via WebSocket long-connection (HTTP Webhook 暂时移除，后续版本恢复)
- **Outbound Messages**: Send messages to WPS协作 chats
- **Encryption Support**: AES-256-CBC decryption for incoming event payloads
- **WPS3 Authentication**: Proper request signing with AppId + AppKey
- **Group Chat Support**: @mention handling in group conversations
- **Message Types**: Text, rich text, images, and files

## Prerequisites

1. **Hermes Agent** - Clone the official repository to a path **on your machine** (do not commit that path to this repo):
   ```bash
   git clone https://github.com/NousResearch/hermes-agent.git ~/hermes-agent
   export HERMES_AGENT_PATH="$HOME/hermes-agent"
   ```
   Compatibility is tracked in [`.hermes-compat.json`](.hermes-compat.json). Requires **Hermes Agent >= 0.12.0** (platform plugin support). Tested with Hermes `0.14.0`.

2. **WPS Open Platform Account** - Register at https://open.wps.cn/ and create an application

3. **Python Dependencies** (auto-installed with pip):
   ```bash
   pip install hermes-wpsxiezuo
   # or manually: pip install pycryptodome aiohttp
   ```

## Repository layout

| Path | Description |
|------|-------------|
| `docs/user-guide/messaging/wpsxiezuo.md` | Gateway 接入说明（用户指南） |
| `plugins/platforms/wpsxiezuo/` | **Platform plugin**（`plugin.yaml` + `adapter.py` + `register()`） |
| `src/wpsxiezuo.py` | Deprecated shim — re-exports plugin adapter |
| `tools/test_sign.py` / `tools/debug_crypto.py` | 本地签名/解密调试 |
| `pyproject.toml` | Python packaging — `pip install .` / `pip install hermes-wpsxiezuo` |
| `scripts/install.sh` | Shell-based install (alternative to pip) — plugin to `~/.hermes/plugins/` |
| `scripts/deploy.sh` | **Deprecated** — legacy Hermes core patch deploy |
| `scripts/rollback.sh` | Remove plugin / legacy adapter file |
| `./install.sh` | Thin wrapper → `scripts/install.sh` |
| `.env.wpsxiezuo` | Environment template (optional reference) |

## Quick install (platform plugin)

Requires **Hermes Agent >= 0.12** with platform plugin support (see [`.hermes-compat.json`](.hermes-compat.json)).

### via pip (recommended)

```bash
# 1. Install package (dependencies included)
pip install hermes-wpsxiezuo
# or from source: pip install .

# 2. Deploy plugin to ~/.hermes/plugins/
hermes-wpsxiezuo install --enable

# 3. Configure via Hermes CLI
hermes gateway setup   # choose "WPSXiezuo (WPS协作)"

# 4. Start gateway
hermes gateway run
```

### via install.sh (alternative)

```bash
# 1. Install plugin (symlink to ~/.hermes/plugins/platforms/wpsxiezuo)
./install.sh --enable --env-template

# 2. Install Python deps in your Hermes venv
pip install pycryptodome aiohttp

# 3. Configure & start
hermes gateway setup
hermes gateway run
```

No changes to the Hermes source tree are required. The plugin registers via `ctx.register_platform()` and Hermes `platform_registry` handles adapter creation, auth, cron delivery, toolsets, and setup wizard integration.

### Migrating from legacy `deploy.sh`

If you previously patched Hermes core with `./deploy.sh`:

```bash
./scripts/rollback.sh --legacy-core "$HERMES_AGENT_PATH"
./install.sh --enable
# Manually revert any remaining wpsxiezuo lines in Hermes core if rollback warns
```

## Legacy deployment (deprecated)

`deploy.sh` patches 15+ Hermes core files. Use only if you cannot upgrade to Hermes 0.12+ plugin support.

### Install dependencies (before gateway)

```bash
pip install pycryptodome aiohttp
hermes gateway setup   # choose "WPSXiezuo (WPS协作)"
```

See [docs/user-guide/messaging/wpsxiezuo.md](docs/user-guide/messaging/wpsxiezuo.md) for env var reference.

1. Go to https://open.wps.cn/
2. Navigate to your application → Event Subscription
3. Enable these events:
   - `kso.app_chat.message` (message events)
4. The adapter connects via WebSocket — no public URL required.

### Configure WPS Open Platform

```bash
hermes gateway run
```

## Hermes integration

This adapter ships as a **platform plugin** under `plugins/platforms/wpsxiezuo/`. Hermes >= 0.12 discovers it via `PluginManager` and `ctx.register_platform()` — no edits to `gateway/run.py`, `toolsets.py`, `cron/scheduler.py`, etc.

See [Hermes adding platform adapters (plugin path)](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/developer-guide/adding-platform-adapters.md).

## Legacy manual integration (deprecated)

If you cannot use the plugin path, the old `deploy.sh` patched these Hermes files manually:

1. **Platform Enum** (`gateway/config.py`):
   ```python
   WPSXIEZUO = "wpsxiezuo"
   ```

2. **Adapter Factory** (`gateway/run.py`):
   ```python
   elif platform == Platform.WPSXIEZUO:
       from gateway.platforms.wpsxiezuo import WPSXiezuoAdapter, check_wpsxiezuo_requirements
       if not check_wpsxiezuo_requirements():
           ...
       return WPSXiezuoAdapter(config)
   ```

3. **Authorization Maps** (`gateway/run.py`):
   ```python
   platform_env_map = {..., Platform.WPSXIEZUO: "WPSXIEZUO_ALLOWED_USERS"}
   platform_allow_all_map = {..., Platform.WPSXIEZUO: "WPSXIEZUO_ALLOW_ALL_USERS"}
   ```

4. **Send Message Tool** (`tools/send_message_tool.py`):
   ```python
   platform_map = {..., "wpsxiezuo": Platform.WPSXIEZUO}
   # _send_to_platform(...):
   elif platform == Platform.WPSXIEZUO:
       result = await _send_wpsxiezuo(pconfig, chat_id, chunk)
   ```

5. **Cron Scheduler / Cron Tool Docs** (`cron/scheduler.py`, `tools/cronjob_tools.py`):
   ```python
   platform_map = {..., "wpsxiezuo": Platform.WPSXIEZUO}
   ```

6. **Display Defaults / Channel Directory** (`gateway/display_config.py`, `gateway/channel_directory.py`):
   ```python
   _PLATFORM_DEFAULTS = {..., "wpsxiezuo": _TIER_LOW}
   # Include wpsxiezuo in session-based discovery for platforms without enumeration.
   ```

7. **Platform Hints** (`agent/prompt_builder.py`):
   ```python
   PLATFORM_HINTS = {
       ...,
       "wpsxiezuo": "You are on WPSXiezuo (WPS协作)...",
   }
   ```

## Testing

Use `tools/test_sign.py` / `tools/debug_crypto.py` for local signing and decryption debugging. **Do not put credentials in source** — use environment variables (same names as Hermes / `.env.wpsxiezuo`):

```bash
export WPSXIEZUO_APP_ID="your-app-id"
export WPSXIEZUO_APP_KEY="your-app-key"

python3 tools/test_sign.py
```

## Troubleshooting

### Issue: "pycryptodome is required for WPSXiezuo decryption"

**Solution:**
```bash
pip install pycryptodome
```

### Issue: Cannot decrypt event payload

**Solution:** The decryption key is derived from `MD5(APP_KEY).hexdigest()`. Ensure your `WPSXIEZUO_APP_KEY` is correct (same field as OAuth `client_secret` and KSO-1).

### Issue: Adapter not loading

**Solution:** Check Hermes Agent logs for import errors:
```bash
hermes gateway 2>&1 | grep -i wpsxiezuo
```

### Issue: `failed to obtain access_token` with `nodename nor servname provided, or not known`

This is **DNS resolution failure** for the configured API host (default `openapi.wps.cn`), not SSL: the machine running `hermes gateway` cannot resolve that hostname (offline network, corporate DNS, or container without DNS).

1. From the **same host**, run `ping` / `nslookup` against the host in your `WPSXIEZUO_API_BASE` (or the default `openapi.wps.cn`) and fix network/DNS until it resolves.
2. **`WPSXIEZUO_API_BASE` must match** the REST/OAuth base URL shown in the **WPS Open Platform console or official docs** for your app. If you point at the wrong host, OAuth may return **`invalid_client` / `client ... not exists`** even when `WPSXIEZUO_APP_KEY` is correct.
3. After changing env, re-copy `src/wpsxiezuo.py` to Hermes if you upgraded the adapter; re-run `deploy.sh` if you want `gateway/config.py`’s `_apply_env_overrides` block to inject `api_base` automatically for new installs.

Run `tools/test_sign.py` with the **same** `WPSXIEZUO_API_BASE` as Hermes to verify token on the same gateway.

## Rollback

```bash
./scripts/rollback.sh --plugin-only
# If you used legacy deploy.sh:
./scripts/rollback.sh --legacy-core "$HERMES_AGENT_PATH"
```

## Security Notes

1. **Keep credentials secure** - Never commit `.env.wpsxiezuo` or any file containing real `WPSXIEZUO_APP_*` values. `tools/test_sign.py` and `tools/debug_crypto.py` read credentials **only** from the environment.
2. **KSO-1 signing** - The adapter uses KSO-1 HMAC-SHA256 signing for WebSocket handshake authentication
3. **Filter self-messages** - The adapter automatically filters out messages sent by the bot itself

## License

This adapter follows the same license as Hermes Agent.

## Support

For issues related to:
- **This adapter**: Check the troubleshooting section above
- **Hermes Agent**: Visit https://github.com/NousResearch/hermes-agent/issues
- **WPS Open Platform**: Visit https://open.wps.cn/ documentation
