Skill: liuboacean/hermes-communication-bridge (version 1.2.0)

--- name: hermes-comm description: "WorkBuddy 与 Hermes 之间通过共享文件队列直接通信。触发词：发消息给hermes、收hermes消息、查看通信队列、双向通信、队列消息、异步通信" version: 1.2.0 category: autonomous-ai-agents --- # Hermes-WorkBuddy 通信桥 > **v1.x 注意**：此为队列式通信桥（queue.json）。如需更强大的**事件驱动闭环命令系统**，请改用 `hermes-memory-bridge` v2.0（`~/.workbuddy/skills/hermes-memory-bridge/`）。两者可并存，各司其职。 通过 `~/.hermes/shared/communication/queue.json` 共享文件队列，WorkBuddy 与 Hermes 直接双向通信。 ## 核心文件 - 队列：`~/.hermes/shared/communication/queue.json` - 历史：`~/.hermes/shared/communication/history.json` - 技能：`~/.workbuddy/skills/hermes-communication-bridge/scripts/communication_queue.py` ## CLI 命令 ```bash # WorkBuddy → Hermes 发消息 python3 ~/.workbuddy/skills/hermes-communication-bridge/scripts/communication_queue.py send workbuddy hermes "内容" # 收 Hermes → WorkBuddy 的消息 python3 ~/.workbuddy/skills/hermes-communication-bridge/scripts/communication_queue.py receive workbuddy # 查看队列统计 python3 ~/.workbuddy/skills/hermes-communication-bridge/scripts/communication_queue.py stats # 标记消息已处理 python3 ~/.workbuddy/skills/hermes-communication-bridge/scripts/communication_queue.py mark <msg_id> completed ``` ## 消息格式 ```json { "id": "msg_<timestamp>_<sender>", "sender": "workbuddy|hermes", "receiver": "hermes|workbuddy", "type": "message|task|query|response|status|file|command|alert", "content": "消息内容", "priority": "low|normal|high|urgent", "status": "pending|processing|completed|failed" } ``` ## 类型说明 - `message`：普通文本消息 - `task`：任务请求（带元数据） - `query`：查询请求 - `response`：响应 - `status`：状态更新 - `file`：文件传输 - `command`：系统命令 - `alert`：警报通知 ## 工作流 1. **WorkBuddy 发消息**：`send workbuddy hermes "内容"` 2. **Hermes 读取**：通过 cron 或 auto_poller 轮询队列，发现 pending 消息 3. **Hermes 回复**：写 `hermes → workbuddy` 的 pending 消息 4. **WorkBuddy 读取**：`receive workbuddy`，处理消息 5. **标记完成**：`mark <msg_id> completed` ## 版本历史 ### v1.1.0（2026-04-16） - **Bug Fix**：修复消息 ID 秒级时间戳碰撞问题，改用 `time.time_ns()` 生成纳秒级唯一 ID，避免同一秒内多条消息 ID 重复 - **Hermes 侧安装说明**：`process_queue.py` 和 `communication_queue.py` 需同时安装到 Hermes skill 目录（`~/.hermes/skills/autonomous-ai-agents/hermes-communication-bridge/`），Bridge cron 才能正常工作 - **验证通过**：双向通信延迟约 1 分钟，队列幂等处理正常 ### v1.0.0（2026-04-16） - 初始版本发布

path: config/default_config.json
content: queue_dir: /Users/liubo/.hermes/shared/communication
poll_interval: 10
max_message_age_days: 7
log_level: INFO
auto_start_poller: yes

path: config/message_types.json
content: {
  "message": {"description": "普通文本消息", "handler": "handle_general_message"},
  "task": {"description": "任务请求", "handler": "handle_task"},
  "query": {"description": "查询请求", "handler": "handle_query"},
  "response": {"description": "查询响应", "handler": "handle_response"},
  "status": {"description": "状态更新", "handler": "handle_status"},
  "file": {"description": "文件传输", "handler": "handle_file"},
  "command": {"description": "系统命令", "handler": "handle_command"},
  "alert": {"description": "警报通知", "handler": "handle_alert"}
}


path: scripts/auto_poller.py
content: #!/usr/bin/env python3
"""自动轮询脚本 - 定期检查来自 Hermes 的消息"""

import sys
import time
import json
import logging
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from communication_queue import CommunicationQueue

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

POLL_INTERVAL = 5

def poll_for_messages():
    queue = CommunicationQueue()
    while True:
        messages = queue.get_messages("workbuddy", status="pending")
        for msg in messages:
            logger.info(f"收到来自 {msg['sender']} 的消息: {msg['content'][:50]}...")
            queue.mark_as_processed(msg['id'], status="completed")
        time.sleep(POLL_INTERVAL)

if __name__ == "__main__":
    poll_for_messages()


path: scripts/communication_queue.py
content: #!/usr/bin/env python3
"""
Hermes-WorkBuddy 通信队列管理器
支持：消息发送、接收、状态管理、历史查询
"""

import json
import time
import os
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional

class CommunicationQueue:
    """通信队列管理器"""
    
    def __init__(self, queue_dir: Optional[str] = None):
        # 支持环境变量配置
        self.queue_dir = Path(queue_dir or os.environ.get(
            "HERMES_COMM_QUEUE_DIR", 
            Path.home() / ".hermes" / "shared" / "communication"
        ))
        self.queue_file = self.queue_dir / "queue.json"
        self.history_file = self.queue_dir / "history.json"
        
        # 确保目录存在
        self.queue_dir.mkdir(parents=True, exist_ok=True)
        self._init_queue_file()
    
    def _init_queue_file(self):
        """初始化队列文件"""
        if not self.queue_file.exists():
            default_queue = {
                "version": "1.0",
                "created_at": datetime.now().isoformat(),
                "messages": [],
                "stats": {
                    "total_messages": 0,
                    "pending_messages": 0,
                    "hermes_to_workbuddy": 0,
                    "workbuddy_to_hermes": 0
                }
            }
            self._write_json(self.queue_file, default_queue)
    
    def send_message(self, 
                    sender: str, 
                    receiver: str, 
                    content: str,
                    msg_type: str = "message",
                    priority: str = "normal",
                    metadata: Optional[Dict] = None) -> str:
        """
        发送消息到队列
        
        Args:
            sender: 发送者 (hermes|workbuddy)
            receiver: 接收者 (hermes|workbuddy)
            content: 消息内容
            msg_type: 消息类型 (message|task|file|status|query|response)
            priority: 优先级 (low|normal|high|urgent)
            metadata: 附加元数据
            
        Returns:
            消息ID
        """
        msg_id = f"msg_{int(time.time_ns())}_{sender[:3]}"
        
        message = {
            "id": msg_id,
            "timestamp": datetime.now().isoformat(),
            "sender": sender,
            "receiver": receiver,
            "type": msg_type,
            "content": content,
            "priority": priority,
            "status": "pending",
            "metadata": metadata or {}
        }
        
        # 读取并更新队列
        queue = self._read_queue()
        queue["messages"].append(message)
        
        # 更新统计
        queue["stats"]["total_messages"] += 1
        queue["stats"]["pending_messages"] += 1
        key = f"{sender}_to_{receiver}"
        if key in queue["stats"]:
            queue["stats"][key] += 1
        
        self._write_queue(queue)
        
        # 记录到历史
        self._add_to_history(message)
        
        return msg_id
    
    def get_messages(self, 
                    receiver: str, 
                    status: str = "pending",
                    limit: int = 10) -> List[Dict]:
        """
        获取指定接收者的消息
        
        Args:
            receiver: 接收者
            status: 消息状态 (pending|processing|completed|failed)
            limit: 返回数量限制
            
        Returns:
            消息列表
        """
        queue = self._read_queue()
        messages = [
            msg for msg in queue["messages"]
            if msg["receiver"] == receiver and msg["status"] == status
        ]
        return messages[:limit]
    
    def mark_as_processed(self, msg_id: str, status: str = "completed"):
        """
        标记消息为已处理
        
        Args:
            msg_id: 消息ID
            status: 新状态 (completed|failed)
        """
        queue = self._read_queue()
        
        for msg in queue["messages"]:
            if msg["id"] == msg_id:
                old_status = msg["status"]
                msg["status"] = status
                msg["processed_at"] = datetime.now().isoformat()
                
                # 更新统计
                if old_status == "pending" and status in ("completed", "failed"):
                    queue["stats"]["pending_messages"] -= 1
                
                self._write_queue(queue)
                return True
        
        return False
    
    def get_stats(self) -> Dict:
        """获取队列统计信息"""
        queue = self._read_queue()
        return queue["stats"]
    
    def clear_old_messages(self, days: int = 7):
        """清理指定天数前的已完成消息"""
        queue = self._read_queue()
        cutoff_time = time.time() - (days * 24 * 3600)
        
        # 保留未完成和最近的消息
        queue["messages"] = [
            msg for msg in queue["messages"]
            if (msg["status"] != "completed" or 
                time.mktime(datetime.fromisoformat(msg["timestamp"]).timetuple()) > cutoff_time)
        ]
        
        self._write_queue(queue)
    
    # 私有方法
    def _read_queue(self) -> Dict:
        """读取队列文件"""
        return self._read_json(self.queue_file)
    
    def _write_queue(self, queue: Dict):
        """写入队列文件"""
        self._write_json(self.queue_file, queue)
    
    def _add_to_history(self, message: Dict):
        """添加到历史记录"""
        history = self._read_json(self.history_file, default={"messages": []})
        history["messages"].append(message)
        # 限制历史记录大小
        if len(history["messages"]) > 1000:
            history["messages"] = history["messages"][-1000:]
        self._write_json(self.history_file, history)
    
    @staticmethod
    def _read_json(filepath: Path, default=None):
        """读取JSON文件"""
        if not filepath.exists():
            return default if default is not None else {}
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            return default if default is not None else {}
    
    @staticmethod
    def _write_json(filepath: Path, data: Dict):
        """写入JSON文件"""
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        except IOError as e:
            print(f"写入文件失败: {e}")


# CLI 接口
def main():
    import argparse
    
    parser = argparse.ArgumentParser(description="Hermes-WorkBuddy 通信队列管理器")
    subparsers = parser.add_subparsers(dest="command", help="命令")
    
    # send 命令
    send_parser = subparsers.add_parser("send", help="发送消息")
    send_parser.add_argument("sender", help="发送者")
    send_parser.add_argument("receiver", help="接收者")
    send_parser.add_argument("content", help="消息内容")
    send_parser.add_argument("--type", default="message", help="消息类型")
    send_parser.add_argument("--priority", default="normal", help="优先级")
    
    # receive 命令
    receive_parser = subparsers.add_parser("receive", help="接收消息")
    receive_parser.add_argument("receiver", help="接收者")
    receive_parser.add_argument("--status", default="pending", help="消息状态")
    receive_parser.add_argument("--limit", type=int, default=10, help="数量限制")
    
    # stats 命令
    stats_parser = subparsers.add_parser("stats", help="查看统计")
    
    # clear 命令
    clear_parser = subparsers.add_parser("clear", help="清理旧消息")
    clear_parser.add_argument("--days", type=int, default=7, help="保留天数")
    
    # mark 命令
    mark_parser = subparsers.add_parser("mark", help="标记消息状态")
    mark_parser.add_argument("msg_id", help="消息ID")
    mark_parser.add_argument("status", help="新状态")
    
    args = parser.parse_args()
    queue = CommunicationQueue()
    
    if args.command == "send":
        msg_id = queue.send_message(
            sender=args.sender,
            receiver=args.receiver,
            content=args.content,
            msg_type=args.type,
            priority=args.priority
        )
        print(f"✅ 消息已发送: {msg_id}")
        
    elif args.command == "receive":
        messages = queue.get_messages(
            receiver=args.receiver,
            status=args.status,
            limit=args.limit
        )
        if messages:
            print(f"📨 找到 {len(messages)} 条消息:")
            for msg in messages:
                print(f"  [{msg['timestamp']}] {msg['sender']} → {msg['receiver']}:")
                print(f"     内容: {msg['content'][:80]}...")
                print(f"     类型: {msg['type']}, 优先级: {msg['priority']}")
                print()
        else:
            print("📭 没有新消息")
            
    elif args.command == "stats":
        stats = queue.get_stats()
        print("📊 通信队列统计:")
        for key, value in stats.items():
            print(f"  {key}: {value}")
            
    elif args.command == "clear":
        queue.clear_old_messages(days=args.days)
        print(f"🧹 已清理 {args.days} 天前的已完成消息")
        
    elif args.command == "mark":
        success = queue.mark_as_processed(args.msg_id, args.status)
        if success:
            print(f"✅ 消息 {args.msg_id} 标记为 {args.status}")
        else:
            print(f"❌ 消息 {args.msg_id} 未找到")


if __name__ == "__main__":
    main()

path: scripts/hermes_comm.py
content: #!/usr/bin/env python3
"""Hermes 通信 CLI 工具"""

import sys
import argparse
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from communication_queue import CommunicationQueue

def send_to_hermes(content, msg_type="message", priority="normal"):
    queue = CommunicationQueue()
    msg_id = queue.send_message(sender="workbuddy", receiver="hermes",
                                 content=content, msg_type=msg_type, priority=priority)
    print(f"已发送消息到 Hermes: {msg_id}")
    return msg_id

def receive_from_hermes():
    queue = CommunicationQueue()
    messages = queue.get_messages("workbuddy", status="pending")
    if not messages:
        print("没有来自 Hermes 的新消息")
    for msg in messages:
        print(f"\n=== 来自 {msg['sender']} ===")
        print(f"类型: {msg['type']} | 优先级: {msg['priority']}")
        print(f"内容: {msg['content']}")
        queue.mark_as_processed(msg['id'], status="completed")
    return messages

def main():
    parser = argparse.ArgumentParser(description='Hermes 通信工具')
    parser.add_argument('action', choices=['send', 'receive'], help='send 或 receive')
    parser.add_argument('--content', '-c', help='消息内容（send 时用）')
    parser.add_argument('--type', '-t', default='message', help='消息类型')
    parser.add_argument('--priority', '-p', default='normal', help='优先级')
    args = parser.parse_args()

    if args.action == 'send':
        if not args.content:
            print("错误: send 需要 --content 参数")
            sys.exit(1)
        send_to_hermes(args.content, args.type, args.priority)
    else:
        receive_from_hermes()

if __name__ == "__main__":
    main()


path: scripts/process_queue.py
content: #!/usr/bin/env python3
"""处理队列中的消息 - Hermes 用这个轮询"""
import sys
import json
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from communication_queue import CommunicationQueue

def process_pending_messages():
    queue = CommunicationQueue()
    # 获取发给 hermes 的 pending 消息
    messages = queue.get_messages("hermes", status="pending")
    
    if not messages:
        print(f"[{datetime.now().isoformat()}] 无待处理消息")
        return
    
    for msg in messages:
        print(f"处理消息: {msg['id']} | 内容: {msg['content'][:50]}...")
        
        # Hermes 读取消息后，可以在这里回复
        # 回复写入队列
        reply = queue.send_message(
            sender="hermes",
            receiver="workbuddy",
            content=f"收到 WorkBuddy 的消息: {msg['content'][:30]}...，我来处理。",
            msg_type="response",
            priority="normal"
        )
        print(f"已回复: {reply}")
        
        # 标记原消息完成
        queue.mark_as_processed(msg['id'], status="completed")
        print(f"已标记完成: {msg['id']}")

from datetime import datetime
if __name__ == "__main__":
    process_pending_messages()


path: temp-repo2/README.md
content: # Hermes-WorkBuddy 通信桥

> 通过共享文件队列（`queue.json`）实现 WorkBuddy 与 Hermes Agent 的双向直接通信，无需外部服务依赖。

## 架构

```
WorkBuddy  ←── queue.json ──▶  Hermes
              (每小时 cron)
```

## 核心文件

| 文件 | 用途 |
|------|------|
| `scripts/communication_queue.py` | 队列管理器（CommunicationQueue 类） |
| `scripts/hermes_comm.py` | WorkBuddy 侧 CLI 工具 |
| `scripts/process_queue.py` | Hermes 侧消息处理器 |
| `scripts/auto_poller.py` | 持续轮询脚本（测试用） |
| `config/default_config.json` | 队列默认配置 |
| `config/message_types.json` | 消息类型定义 |

## 快速开始

### WorkBuddy → Hermes 发消息

```bash
python3 ~/.workbuddy/skills/hermes-communication-bridge/scripts/hermes_comm.py send -c "你好 Hermes！"
```

### 收取 Hermes 回复

```bash
python3 ~/.workbuddy/skills/hermes-communication-bridge/scripts/hermes_comm.py receive
```

### Hermes 侧配置 Cron（每小时自动处理）

```bash
hermes cron create --script ~/.workbuddy/skills/hermes-communication-bridge/scripts/process_queue.py "every 1h"
```

## 队列存储

- 队列文件：`~/.hermes/shared/communication/queue.json`
- 历史文件：`~/.hermes/shared/communication/history.json`

## 依赖

- Python 3.10+
- Hermes Agent（已安装并运行）

## 许可证

MIT


path: temp-repo2/config/default_config.json
content: queue_dir: /Users/liubo/.hermes/shared/communication
poll_interval: 10
max_message_age_days: 7
log_level: INFO
auto_start_poller: yes

path: temp-repo2/config/message_types.json
content: {
  "message": {"description": "普通文本消息", "handler": "handle_general_message"},
  "task": {"description": "任务请求", "handler": "handle_task"},
  "query": {"description": "查询请求", "handler": "handle_query"},
  "response": {"description": "查询响应", "handler": "handle_response"},
  "status": {"description": "状态更新", "handler": "handle_status"},
  "file": {"description": "文件传输", "handler": "handle_file"},
  "command": {"description": "系统命令", "handler": "handle_command"},
  "alert": {"description": "警报通知", "handler": "handle_alert"}
}


path: temp-repo2/scripts/auto_poller.py
content: #!/usr/bin/env python3
"""自动轮询脚本 - 定期检查来自 Hermes 的消息"""

import sys
import time
import json
import logging
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from communication_queue import CommunicationQueue

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

POLL_INTERVAL = 5

def poll_for_messages():
    queue = CommunicationQueue()
    while True:
        messages = queue.get_messages("workbuddy", status="pending")
        for msg in messages:
            logger.info(f"收到来自 {msg['sender']} 的消息: {msg['content'][:50]}...")
            queue.mark_as_processed(msg['id'], status="completed")
        time.sleep(POLL_INTERVAL)

if __name__ == "__main__":
    poll_for_messages()


path: temp-repo2/scripts/communication_queue.py
content: #!/usr/bin/env python3
"""
Hermes-WorkBuddy 通信队列管理器
支持：消息发送、接收、状态管理、历史查询
"""

import json
import time
import os
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional

class CommunicationQueue:
    """通信队列管理器"""
    
    def __init__(self, queue_dir: Optional[str] = None):
        # 支持环境变量配置
        self.queue_dir = Path(queue_dir or os.environ.get(
            "HERMES_COMM_QUEUE_DIR", 
            Path.home() / ".hermes" / "shared" / "communication"
        ))
        self.queue_file = self.queue_dir / "queue.json"
        self.history_file = self.queue_dir / "history.json"
        
        # 确保目录存在
        self.queue_dir.mkdir(parents=True, exist_ok=True)
        self._init_queue_file()
    
    def _init_queue_file(self):
        """初始化队列文件"""
        if not self.queue_file.exists():
            default_queue = {
                "version": "1.0",
                "created_at": datetime.now().isoformat(),
                "messages": [],
                "stats": {
                    "total_messages": 0,
                    "pending_messages": 0,
                    "hermes_to_workbuddy": 0,
                    "workbuddy_to_hermes": 0
                }
            }
            self._write_json(self.queue_file, default_queue)
    
    def send_message(self, 
                    sender: str, 
                    receiver: str, 
                    content: str,
                    msg_type: str = "message",
                    priority: str = "normal",
                    metadata: Optional[Dict] = None) -> str:
        """
        发送消息到队列
        
        Args:
            sender: 发送者 (hermes|workbuddy)
            receiver: 接收者 (hermes|workbuddy)
            content: 消息内容
            msg_type: 消息类型 (message|task|file|status|query|response)
            priority: 优先级 (low|normal|high|urgent)
            metadata: 附加元数据
            
        Returns:
            消息ID
        """
        msg_id = f"msg_{int(time.time())}_{sender[:3]}"
        
        message = {
            "id": msg_id,
            "timestamp": datetime.now().isoformat(),
            "sender": sender,
            "receiver": receiver,
            "type": msg_type,
            "content": content,
            "priority": priority,
            "status": "pending",
            "metadata": metadata or {}
        }
        
        # 读取并更新队列
        queue = self._read_queue()
        queue["messages"].append(message)
        
        # 更新统计
        queue["stats"]["total_messages"] += 1
        queue["stats"]["pending_messages"] += 1
        key = f"{sender}_to_{receiver}"
        if key in queue["stats"]:
            queue["stats"][key] += 1
        
        self._write_queue(queue)
        
        # 记录到历史
        self._add_to_history(message)
        
        return msg_id
    
    def get_messages(self, 
                    receiver: str, 
                    status: str = "pending",
                    limit: int = 10) -> List[Dict]:
        """
        获取指定接收者的消息
        
        Args:
            receiver: 接收者
            status: 消息状态 (pending|processing|completed|failed)
            limit: 返回数量限制
            
        Returns:
            消息列表
        """
        queue = self._read_queue()
        messages = [
            msg for msg in queue["messages"]
            if msg["receiver"] == receiver and msg["status"] == status
        ]
        return messages[:limit]
    
    def mark_as_processed(self, msg_id: str, status: str = "completed"):
        """
        标记消息为已处理
        
        Args:
            msg_id: 消息ID
            status: 新状态 (completed|failed)
        """
        queue = self._read_queue()
        
        for msg in queue["messages"]:
            if msg["id"] == msg_id:
                old_status = msg["status"]
                msg["status"] = status
                msg["processed_at"] = datetime.now().isoformat()
                
                # 更新统计
                if old_status == "pending" and status in ("completed", "failed"):
                    queue["stats"]["pending_messages"] -= 1
                
                self._write_queue(queue)
                return True
        
        return False
    
    def get_stats(self) -> Dict:
        """获取队列统计信息"""
        queue = self._read_queue()
        return queue["stats"]
    
    def clear_old_messages(self, days: int = 7):
        """清理指定天数前的已完成消息"""
        queue = self._read_queue()
        cutoff_time = time.time() - (days * 24 * 3600)
        
        # 保留未完成和最近的消息
        queue["messages"] = [
            msg for msg in queue["messages"]
            if (msg["status"] != "completed" or 
                time.mktime(datetime.fromisoformat(msg["timestamp"]).timetuple()) > cutoff_time)
        ]
        
        self._write_queue(queue)
    
    # 私有方法
    def _read_queue(self) -> Dict:
        """读取队列文件"""
        return self._read_json(self.queue_file)
    
    def _write_queue(self, queue: Dict):
        """写入队列文件"""
        self._write_json(self.queue_file, queue)
    
    def _add_to_history(self, message: Dict):
        """添加到历史记录"""
        history = self._read_json(self.history_file, default={"messages": []})
        history["messages"].append(message)
        # 限制历史记录大小
        if len(history["messages"]) > 1000:
            history["messages"] = history["messages"][-1000:]
        self._write_json(self.history_file, history)
    
    @staticmethod
    def _read_json(filepath: Path, default=None):
        """读取JSON文件"""
        if not filepath.exists():
            return default if default is not None else {}
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            return default if default is not None else {}
    
    @staticmethod
    def _write_json(filepath: Path, data: Dict):
        """写入JSON文件"""
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        except IOError as e:
            print(f"写入文件失败: {e}")


# CLI 接口
def main():
    import argparse
    
    parser = argparse.ArgumentParser(description="Hermes-WorkBuddy 通信队列管理器")
    subparsers = parser.add_subparsers(dest="command", help="命令")
    
    # send 命令
    send_parser = subparsers.add_parser("send", help="发送消息")
    send_parser.add_argument("sender", help="发送者")
    send_parser.add_argument("receiver", help="接收者")
    send_parser.add_argument("content", help="消息内容")
    send_parser.add_argument("--type", default="message", help="消息类型")
    send_parser.add_argument("--priority", default="normal", help="优先级")
    
    # receive 命令
    receive_parser = subparsers.add_parser("receive", help="接收消息")
    receive_parser.add_argument("receiver", help="接收者")
    receive_parser.add_argument("--status", default="pending", help="消息状态")
    receive_parser.add_argument("--limit", type=int, default=10, help="数量限制")
    
    # stats 命令
    stats_parser = subparsers.add_parser("stats", help="查看统计")
    
    # clear 命令
    clear_parser = subparsers.add_parser("clear", help="清理旧消息")
    clear_parser.add_argument("--days", type=int, default=7, help="保留天数")
    
    # mark 命令
    mark_parser = subparsers.add_parser("mark", help="标记消息状态")
    mark_parser.add_argument("msg_id", help="消息ID")
    mark_parser.add_argument("status", help="新状态")
    
    args = parser.parse_args()
    queue = CommunicationQueue()
    
    if args.command == "send":
        msg_id = queue.send_message(
            sender=args.sender,
            receiver=args.receiver,
            content=args.content,
            msg_type=args.type,
            priority=args.priority
        )
        print(f"✅ 消息已发送: {msg_id}")
        
    elif args.command == "receive":
        messages = queue.get_messages(
            receiver=args.receiver,
            status=args.status,
            limit=args.limit
        )
        if messages:
            print(f"📨 找到 {len(messages)} 条消息:")
            for msg in messages:
                print(f"  [{msg['timestamp']}] {msg['sender']} → {msg['receiver']}:")
                print(f"     内容: {msg['content'][:80]}...")
                print(f"     类型: {msg['type']}, 优先级: {msg['priority']}")
                print()
        else:
            print("📭 没有新消息")
            
    elif args.command == "stats":
        stats = queue.get_stats()
        print("📊 通信队列统计:")
        for key, value in stats.items():
            print(f"  {key}: {value}")
            
    elif args.command == "clear":
        queue.clear_old_messages(days=args.days)
        print(f"🧹 已清理 {args.days} 天前的已完成消息")
        
    elif args.command == "mark":
        success = queue.mark_as_processed(args.msg_id, args.status)
        if success:
            print(f"✅ 消息 {args.msg_id} 标记为 {args.status}")
        else:
            print(f"❌ 消息 {args.msg_id} 未找到")


if __name__ == "__main__":
    main()

path: temp-repo2/scripts/hermes_comm.py
content: #!/usr/bin/env python3
"""Hermes 通信 CLI 工具"""

import sys
import argparse
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from communication_queue import CommunicationQueue

def send_to_hermes(content, msg_type="message", priority="normal"):
    queue = CommunicationQueue()
    msg_id = queue.send_message(sender="workbuddy", receiver="hermes",
                                 content=content, msg_type=msg_type, priority=priority)
    print(f"已发送消息到 Hermes: {msg_id}")
    return msg_id

def receive_from_hermes():
    queue = CommunicationQueue()
    messages = queue.get_messages("workbuddy", status="pending")
    if not messages:
        print("没有来自 Hermes 的新消息")
    for msg in messages:
        print(f"\n=== 来自 {msg['sender']} ===")
        print(f"类型: {msg['type']} | 优先级: {msg['priority']}")
        print(f"内容: {msg['content']}")
        queue.mark_as_processed(msg['id'], status="completed")
    return messages

def main():
    parser = argparse.ArgumentParser(description='Hermes 通信工具')
    parser.add_argument('action', choices=['send', 'receive'], help='send 或 receive')
    parser.add_argument('--content', '-c', help='消息内容（send 时用）')
    parser.add_argument('--type', '-t', default='message', help='消息类型')
    parser.add_argument('--priority', '-p', default='normal', help='优先级')
    args = parser.parse_args()

    if args.action == 'send':
        if not args.content:
            print("错误: send 需要 --content 参数")
            sys.exit(1)
        send_to_hermes(args.content, args.type, args.priority)
    else:
        receive_from_hermes()

if __name__ == "__main__":
    main()


path: temp-repo2/scripts/process_queue.py
content: #!/usr/bin/env python3
"""处理队列中的消息 - Hermes 用这个轮询"""
import sys
import json
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from communication_queue import CommunicationQueue

def process_pending_messages():
    queue = CommunicationQueue()
    # 获取发给 hermes 的 pending 消息
    messages = queue.get_messages("hermes", status="pending")
    
    if not messages:
        print(f"[{datetime.now().isoformat()}] 无待处理消息")
        return
    
    for msg in messages:
        print(f"处理消息: {msg['id']} | 内容: {msg['content'][:50]}...")
        
        # Hermes 读取消息后，可以在这里回复
        # 回复写入队列
        reply = queue.send_message(
            sender="hermes",
            receiver="workbuddy",
            content=f"收到 WorkBuddy 的消息: {msg['content'][:30]}...，我来处理。",
            msg_type="response",
            priority="normal"
        )
        print(f"已回复: {reply}")
        
        # 标记原消息完成
        queue.mark_as_processed(msg['id'], status="completed")
        print(f"已标记完成: {msg['id']}")

from datetime import datetime
if __name__ == "__main__":
    process_pending_messages()


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)